Spring MVC - No mapping found for HTTP request with URI [duplicate] - spring

This question already has answers here:
Why does Spring MVC respond with a 404 and report "No mapping found for HTTP request with URI [...] in DispatcherServlet"?
(13 answers)
Closed 6 years ago.
I'm aware that there are loads of questions on the topic but none of the solutions i found here worked for me.
I'm using Spring with Jetty 6 so i don't have a web.xml file. The mapping for the spring dispatcher servlet is set to "/" in jetty's config
dispatcher:
<bean class="org.mortbay.jetty.servlet.ServletHolder">
<property name="name" value="spring" />
<property name="servlet">
<bean class="org.springframework.web.servlet.DispatcherServlet" />
</property>
<property name="initParameters">
<map>
<entry key="contextConfigLocation" value="classpath:com/project/config/spring-servlet.xml" />
</map>
</property>
</bean>
... mapping:
<bean class="org.mortbay.jetty.servlet.ServletMapping">
<property name="servletName" value="spring"></property>
<property name="pathSpec" value="/"></property>
</bean>
The spring-servlet.xml looks like this:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="..." ...>
<context:component-scan base-package="com.project.web" />
<mvc:annotation-driven />
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/pages/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
</beans>
And i have a simple controller called HelloController:
#Controller
public class HelloController {
#RequestMapping(method = RequestMethod.GET, value="/welcome")
public String sayHello(ModelMap model){
model.addAttribute("message", "Spring 3 MVC Hello World");
return "hello";
}
}
Reading the logs it seem to work but i get the following error:
No mapping found for HTTP request with URI [/WEB-INF/pages/hello.jsp] in DispatcherServlet with name 'spring'
which i don't understand. it maps the "/welcome" to /WEB-INF/pages/hello.jsp but it still says page cannot be found, which is just there where it seems to look for it. I added the WEB-INF folder to the classpath but it's still the same. Do you have any idea why's that?

Are you sure the package name is correct in this?
<context:component-scan base-package="com.project.web" />

The request mapping path in the controller is relative to your http://your-domain/your-app/. If your app name is welcome use url http://localhost:25001/welcome/welcome or change the requestmapping to #RequestMapping(method = RequestMethod.GET, value="/") so you can use url http://localhost:25001/welcome

Is your hello.jsp directly under WEB-INF/pages?
Can you change the Dispatcher Servlet mapping to this and try
<property name="pathSpec" value="*.html"></property>

Related

Spring MVC REST produces XML on default

I have a problem with Spring MVC and REST. The problem is that when i post a url without extension or whatever extension other then json or html or htm i am always getting an xml response. But i want it to default to text/html response. I was searching in many topics and cant find the answear to this.
Here is my Controller class :
#RequestMapping(value="/user/{username}", method=RequestMethod.GET)
public String showUserDetails(#PathVariable String username, Model model){
model.addAttribute(userManager.getUser(username));
return "userDetails";
}
#RequestMapping(value = "/user/{username}", method = RequestMethod.GET,
produces={"application/xml", "application/json"})
#ResponseStatus(HttpStatus.OK)
public #ResponseBody
User getUser(#PathVariable String username) {
return userManager.getUser(username);
}
Here is my mvc context config:
<mvc:resources mapping="/resources/**"
location="/resources/"/>
<context:component-scan
base-package="com.chodak.controller" />
<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
<property name="defaultContentType" value="text/html" />
<property name="mediaTypes">
<map>
<entry key="json" value="application/json"/>
<entry key="xml" value="application/xml"/>
</map>
</property>
</bean>
<bean id="viewResolver"
class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass">
<value>
org.springframework.web.servlet.view.tiles3.TilesView
</value>
</property>
</bean>
<bean id="tilesConfigurer"
class="org.springframework.web.servlet.view.tiles3.TilesConfigurer">
<property name="definitions">
<list>
<value>/WEB-INF/tiles.xml</value>
</list>
</property>
</bean>
Actually when I tried the built in Eclipse browser it works fine, but when I use firefox or chrome it shows xml response on a request with no extension. I tried using ignoreAcceptHeader, but no change.
Also works on IE :/
If anyone has an idea please help, Thank you.
I actually found out how to do it, i dont really understand why but it is working now, I added default views to the contentresolver like :
<property name="defaultViews">
<list>
<!-- JSON View -->
<bean
class="org.springframework.web.servlet.view.json.MappingJacksonJsonView">
</bean>
<!-- JAXB XML View -->
<bean class="org.springframework.web.servlet.view.xml.MarshallingView">
<constructor-arg>
<bean class="org.springframework.oxm.jaxb.Jaxb2Marshaller">
<property name="classesToBeBound">
<list>
<value>com.chodak.tx.model.User</value>
</list>
</property>
</bean>
</constructor-arg>
</bean>
</list>
</property>
and removed the getUser method, the one annoted to produce xml and json. If I leave it with the added default views its still not working. If anyone can explain why it would be awesome :)
You can do
import org.springframework.http.MediaType;
import org.springframework.web.servlet.config.annotation.ContentNegotiationConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
#Configuration
// #EnableWebMvc already autoconfigured by Spring Boot
public class MvcConfiguration {
#Bean
public WebMvcConfigurer contentNegotiationConfigurer() {
return new WebMvcConfigurerAdapter() {
#Override
public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
configurer.favorPathExtension(false)
.favorParameter(true)
.parameterName("mediaType")
.ignoreAcceptHeader(true)
.useJaf(false)
.defaultContentType(MediaType.APPLICATION_JSON)
.mediaType("xml", MediaType.APPLICATION_XML)
.mediaType("json", MediaType.APPLICATION_JSON);
// this line alone gave me xhtml for some reason
// configurer.defaultContentType(MediaType.APPLICATION_JSON_UTF8);
}
};
}
(tried with Spring Boot 1.5.x)
see https://spring.io/blog/2013/05/11/content-negotiation-using-spring-mvc
"What we did, in both cases:
Disabled path extension. Note that favor does not mean use one approach in preference to another, it just enables or disables it. The order of checking is always path extension, parameter, Accept header.
Enable the use of the URL parameter but instead of using the default parameter, format, we will use mediaType instead.
Ignore the Accept header completely. This is often the best approach if most of your clients are actually web-browsers (typically making REST calls via AJAX).
Don't use the JAF, instead specify the media type mappings manually - we only wish to support JSON and XML."

How to set default method for Delegate method of MultiActionController ?

I'm using Spring MVC for a web app project and I'm trying to avoid using annotations.
I came across as far as getting MultiActionController and delegate working.
The question is, how do I set the default method in the delegate of a MultiActionController ?
By MultiActionController, I mean something like this
public class TestController1 extends MultiActionController{
public TestController1(){
System.out.println("TestController1 initialising...");
}
}
My xml settings are...
<bean id="multiactionController1" class="test.TestController1">
<property name="delegate" ref="testDelegater1"/>
<property name="methodNameResolver" ref="paramResolver"/>
</bean>
<!-- Delegaters -->
<bean id="testDelegater1" class="test.TestController1Delegator"/>
<!-- param method name resolver -->
<bean id="paramResolver" class="org.springframework.web.servlet.mvc.multiaction.ParameterMethodNameResolver">
<property name="paramName" value="action"/>
</bean>
<!-- Simple Url Handler Mapping -->
<bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<map>
<entry key="/multiaction1/**" value-ref="multiactionController1"/>
<entry key="/item/**" value-ref="itemController"/>
</map>
</property>
</bean>
So when I send a request like '*/item' , notice it doesn't have an action parameter, instead of giving me an error I would like to have a default method.
Use following implementation of MethodNameResolver, it has defaultMethodName property.
org.springframework.web.servlet.mvc.multiaction.ParameterMethodNameResolver
I was able to solve this by following instructions in this page.
http://www.cwinters.com/blog/2004/02/18/spring_setting_a_default_action_for_multiactioncontroller.html
As far as I've figured, you need to implement your own MethodNameResolver that returns default method name if no method name has been specified.
I Hope this helps : )

Mapping .jsp Spring

Today I'm working on a project in Java Spring, especially in CONTEXT-SERVLET.xml (context) where normally declare a bean to link a .jsp with a Java class or controller (mapping).
Traditional workflow is: a viewA.jsp is linked (mapping) to controller.java (controller) and this controller.java dispatches another viewB.jsp.
Can you link a viewA.jsp to another viewB.Jsp without going through a controller?
How do this in CONTEXT-SERVLET.xml?
You can use ParameterizableViewController to redirect a request to jsp file without visiting controller.
For example
1. Mapping /welcome.htm to welcomeController
<bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<prop key="/welcome.htm">welcomeController</prop>
</props>
</property>
</bean>
2. Mapping viewName property of welcomeController to WelcomePage
<bean name="welcomeController"
class="org.springframework.web.servlet.mvc.ParameterizableViewController">
<property name="viewName" value="WelcomePage" />
</bean>
3. Defining view resolver
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver" >
<property name="prefix">
<value>/WEB-INF/pages/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
It will map /welcome.htm to /WEB-INF/pages/welcomePage.jsp.
Source for more details.
< mvc:view-controller path="/" view-name="home" />
This is a shortcut for defining a ParameterizableViewController that immediately forwards to a view when invoked. Use it in static cases when there is no Java controller logic to execute before the view generates the response.
see link http://static.springsource.org/spring/docs/current/spring-framework-reference/html/mvc.html#mvc-view-controller

Spring MVC Page is not rendering the success page using simpleformcontroller

Iam wrote simple spring mvc apps.But I unable to redirect one page to another page. I mentioned code snippet below
Claims-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props><prop key="/loginpage.htm">loginFormController</prop></props>
</property>
</bean>
<bean id="loginFormController" class="com.aims.controller.LoginFormController">
<property name="sessionForm"><value>true</value></property>
<property name="commandName"><value>LoginFormCommand</value></property>
<property name="commandClass"><value>com.aims.commands.LoginFormCommand</value></property>
<property name="validator"><ref bean="loginformValidator"/></property>
<property name="formView"><value>loginpage</value></property>
<property name="successView"><value>body</value></property>
</bean>
<bean id="loginformValidator" class="com.aims.validator.LoginFormValidator"/>
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass"><value>org.springframework.web.servlet.view.JstlView</value></property>
<property name="suffix"><value>.jsp</value></property>
</bean>
</beans>
Controller:
public class LoginFormController extends SimpleFormController {
public ModelAndView onSubmit(Object command, BindException bindException) throws Exception {
System.out.println("LoginFormController:onSubmit============");
LoginFormCommand loginform = (LoginFormCommand) command;
System.out.println("username" + loginform.getUsername() + "Password"
+ loginform.getPassword());
return new ModelAndView(new RedirectView("/WEB-INF/view/jsp/"
+ getSuccessView()));
}}
I have two jsp one is
Webroot>loginpage.jsp
view->jsp>body.jsp
When the browser opens its automatically called loginpage.jsp(web.xml>welecome-file) and after success iam trying to call view->jsp>body.jsp.But it doesn't move to body.jsp.Please need help.
With a redirect view, you must specify the actual URL of the target, not a path to an internal jsp. Instead of rendering a jsp, Spring MVC will redirect the user to this URL.
Example: new ModelAndView(new RedirectView("/example/helloworld.html")).
Of course, the target has to exist.

Help with spring-json using annotated controllers

I've scourged the internet for an example that would use both spring-json and annotated controllers, I'm new to spring so I've had no luck adapting the configuration on spring-json's samples (it uses SimpleController et. al.)
Currently I have a controller with 2 mappings, one lists results in html (and works), the other should render json for some ajax calls but when I access the url it returns a 404 and asks for /myapp/jsp/jsonView.jsp. The code on the show method does execute and it even validates the presence of the id param, so it seems that the problem is that it doesn't know how render, as far as I know that's what the viewResolver bean does.
Thanks in advance for any help :)
Here's what I've got:
#Controller
public class ItemController {
//This one works
#RequestMapping(value = "/items", method = RequestMethod.GET)
public ModelMap list() {
ModelMap map = new ModelMap();
map.addAttribute("item", "value");
return map;
}
//This one returns 404, asks for jsonView.jsp
#RequestMapping(value = "/items.json", method = RequestMethod.GET)
public ModelAndView show(#RequestParam(value = "id", required = true) String id) {
Map model = new HashMap();
model.put("firstname", "Peter");
model.put("secondname", "Schmitt");
return new ModelAndView("jsonView", model);
}
}
on myapp-servlet.xml:
<bean name="viewResolver" class="org.springframework.web.servlet.view.XmlViewResolver"/>
on views.xml:
<beans>
<bean name="jsonView" class="org.springframework.web.servlet.view.json.JsonView">
<property name="encoding">
<value>UTF-8</value>
</property>
<property name="contentType">
<value>application/json</value>
</property>
<property name="jsonWriter">
<ref bean="sojoJsonWriter"/>
</property>
<property name="jsonErrors">
<list>
<ref bean="statusError"/>
<ref bean="modelflagError"/>
</list>
</property>
</bean>
<bean name="sojoJsonWriter" class="org.springframework.web.servlet.view.json.writer.sojo.SojoJsonStringWriter">
<property name="convertAllMapValues">
<value>true</value>
</property>
</bean>
<bean name="statusError" class="org.springframework.web.servlet.view.json.error.HttpStatusError">
<property name="errorCode">
<value>311</value>
</property>
</bean>
<bean name="modelflagError" class="org.springframework.web.servlet.view.json.error.ModelFlagError">
<property name="name">
<value>failure</value>
</property>
<property name="value">
<value>true</value>
</property>
</bean>
web.xml:
<servlet>
<servlet-name>myapp</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>myapp</servlet-name>
<url-pattern>/myapp/*</url-pattern>
</servlet-mapping>
There could be another alternative: Are you able to upgrade to spring 3 (it has release state now)? There is a fantastic ContentNegotiationResolver which helps a lot when it comes to content-negotatioon and view-resolving.
<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
<property name="mediaTypes">
<map>
<entry key="xml" value="application/xml"/>
<entry key="json" value="application/json"/>
...
If now appending .json to your URL path or using respective 'Accept' HTTP header, passed object (see model.put(...)) is serialized accordingly. For json spring 3 is using jackson by default.
The problem was with the view resolver on the servlet.xml, added a p:order attribute so it would load before the InternalResourceViewResolver
<bean name="viewResolver" class="org.springframework.web.servlet.view.XmlViewResolver" p:order="1"/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" p:prefix="/jsp/"p:suffix=".jsp" p:order="10"/>

Resources