Spring MVC without annotation - HTTP 404 page not found error coming - spring

I am trying to write a simple Spring MVC web application without using annotations. However, when I access specific URL, I am getting HTTP 404 error. The relevant code snippet is below:
web.xml changes done for front controller:
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:web="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.4">
<display-name>POCProject</display-name>
<servlet>
<servlet-name>FrontController</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>FrontController</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
The servlet name is --> FrontController
Hence, have the following configuration file --> FrontController-servlet.xml
<beans ...>
<bean id="HandlerMapping" class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/>
<bean name="/userdetails" class="com.example.controllers.UserDetailsController"/>
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix"> <value>/WEB-INF/</value> </property>
<property name="suffix"> <value>.html</value> </property>
</bean>
</beans>
In above configuration file, the Handler mapping class is --> org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping
The controller class for URL /userdetails is --> com.example.controllers.UserDetailsController
The code for this controller is below:
public class UserDetailsController extends AbstractController {
#Override
protected ModelAndView handleRequestInternal(HttpServletRequest req, HttpServletResponse res) throws Exception {
ModelAndView mw = new ModelAndView("userInfo");
return mw;
}
}
So, for a request with /userdetails the controller should send the view userInfo.html
However when I invoke this, I am getting HTTP 404 error.
I have deployed this in Apache tomcat, and the below is the message that I get in the tomcat console.
WARNING: No mapping found for HTTP request with URI [/POCProject/WEB-INF/userInfo.html] in DispatcherServlet with name "FrontController"
Any inputs on what I am missing here?

The javadoc for InternalResourceViewResolver says that it is a (emphasize mine):
Wrapper for a JSP or other resource within the same web application. Exposes model objects as request attributes and forwards the request to the specified resource URL using a RequestDispatcher.
A JSP is internally converted in a true servlet by Tomcat (or by any servlet container) that is a resource suitable for forwarding. But a simple HTML is not.
That means that Spring InternalResourceViewResolver cannot use HTML views and you must convert them to JSP files.

Related

http status 500-Error instantiating servlet class org.springframework.web.servlet.DispatcherServlet

Above is the directory hierarchy of my program
I am new to spring and learning MVC concepts I have written a program which takes input(Name) into a text box and prints Hello...'name'. Tha following is my directory structure and the various files I have created.
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1">
<display-name>MVC_HelloWorld</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<!-- default configuration -->
<servlet>
<servlet-name>HelloWorld</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>*.ap</url-pattern> <!-- this same extension should bbe used in form action -->
</servlet-mapping>
</web-app>
HelloWorld-servlet.xml
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN"
"http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<!-- default handler mapping -->
<!-- file should be created under web inf annd it's view resolver file -->
<!-- handler(Not rqd in case of default handler) -->
<bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping" />
<!-- controller configuration -->
<bean name="/HelloWorld.ap" class="controller.HelloController"> <!-- mapping url pattern to controller class using 'name' -->
<!-- view resolver -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" vlaue="/"/> <!-- default location (prefix used foor rqd page locations) -->
|<property name="sufix" value=".jsp"/> <!-- sufix used forr rqd page extensions -->
</bean>
</bean>
</beans>
HelloController.java
package controller;
import java.util.HashMap;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;
import com.sun.javafx.collections.MappingChange.Map;
public class HelloController implements Controller {
#Override
public ModelAndView handleRequest(HttpServletRequest req, HttpServletResponse res) throws Exception {
String name=req.getParameter("name");
Map m= new HashMap(); // creating output object
m.put("msg","Hello..."+name);
ModelAndView mav=new ModelAndView("success"+m);
return mav;
}
}
index.jsp
<h1> Hello World</h1>
<form action="./hello.ap">
NAME: <input type="text" name="name">
<input type="Submit" value="Say Hello">
</form>
success.jsp
${msg}
when I am running this code the index.jsp page is running properly bur upon further execution It shows Error 500. what's wrong with the code..?? I am using Eclipse oxygen in that apache 8.5
You configuration in web.xml are wrong.
You are trying to map the dispatch servlet as the controller.
In spring mvc like in other mvc frameworks (struts etc.) there is one major servlet that use to dispatch all requests.
org.springframework.web.servlet.DispatcherServlet is usually named “dispatcher” and should be mapped to a top level url usually “\”
e.g.
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/dispatcher-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
...
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
And the controller is mapped under this url e.g. HelloWorld
#Controller
#RequestMapping("/HelloWorld");"
public class HelloController implements Controller {}
As your initial project is far from the classic vanilla starter Spring MVC project and it looks like you are using a very old Spring version (or spring tutorial). I suggest to start fresh from some online tutorial.
E.g.
http://www.journaldev.com/2433/spring-mvc-tutorial
http://www.mkyong.com/spring-mvc/gradle-spring-mvc-web-project-example/
Try below edit to web.xml.
<servlet-mapping>
<servlet-name>HelloWorld</servlet-name>
<url-pattern>*.ap</url-pattern> <!-- this same extension should bbe used in form action -->
</servlet-mapping>

How do I map this URL to a Spring controller method?

I'm using Spring 3.1.1.RELEASE. I'm having fits mapping URLs to controller methods. I would like to map the URL "/my-context-path/organizations/add" to the controller method below. In my controller, I have
#Controller
#RequestMapping("/organizations")
public class OrganizationController
{
…
#RequestMapping(value = "/add", method = RequestMethod.GET)
public ModelAndView doGetadd()
{
… do some stuff …
return new ModelAndView("organizations/add");
} // doGetadd
In my web.xml I have
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">
<display-name>SB Admin</display-name>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/organizations/*</url-pattern>
</servlet-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/dispatcher-servlet.xml</param-value>
</context-param>
and in my dispathcer-servlet.xml I have
...
<!-- Enable annotation driven controllers, validation etc... -->
<mvc:annotation-driven />
<context:component-scan base-package="org.myco.subco" />
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/views/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
but requests for my desired context-path result in "No mapping found for HTTP request with URI [/myproject-1.0-SNAPSHOT/organizations/add] in DispatcherServlet with name 'dispatcher" errors (using JBoss 7). How do I map this thing properly? Note that I have multiple methods in my controller that I want to different URLs within the "/organizations" space.
Try this.
Change the dispatcher servlet mapping to :
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
And for the OrganizationController the mapping would be
#Controller
#RequestMapping("/organizations")
public class OrganizationController
And for the ContractsController the mapping would be
#Controller
#RequestMapping("/contracts")
public class OrganizationController
According to the Spring Doc the ModelAndView constructor parameter is the name of the view file.
So that file could be addView.jsp .
As well as the fact that you're (as far as my Spring knowledge goes) actually mapping it to /Application-Name/organizations/organizations/add due to :
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/organizations/</url-pattern>
</servlet-mapping>
And
#Controller
#RequestMapping("/organizations")
public class OrganizationController
I'd recommend changing the requestmapping from the controller to
#Controller
#RequestMapping("/")
public class OrganizationController
The <url-pattern>/organizations/</url-pattern> basiccally defines the 'virtual path' on which your site will be accessible.
Al mappings you do on controllers will append to it, makeing it /organizations/whateverpagecomeshere.jsp
And make sure that View file exists !

Sending HTML/JSON from REST Spring MVC Web app

I have developed a REST web application with Spring MVC and I can send JSON objects to a client.
I would like to construct a Javascript/AJAX client that connects to my web application but I don't know how to send the first HTML page (using JSP).
I understand I should serve JSP pages with some embedded AJAX. This AJAX will send requests to my web services.
Update:
The requirement I am not able to achieve is to write the default URI (http://localhost:8084) in browser and see the HTML page I have written in JSP page (home.jsp).
My approach is following:
I have a Controller that sends the root JSP page
#Controller
public class SessionController {
#RequestMapping(value="/", method=RequestMethod.GET)
public String homeScreen(){
return "home";
}
}
But when I run the server I receive this warning
WARNING: No mapping found for HTTP request with URI [/home] in DispatcherServlet with name 'dispatcher'
and nothing is loaded in browser.
Here is my application-context file:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd">
<context:component-scan base-package="com.powerelectronics.freesun.web" />
<mvc:annotation-driven />
</beans>
And web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
</web-app>
Is my approach correct? Am I wrong at any basic concept?
Can I modify something in my code to make it run?
I would like to see the first page loaded in browser and keep going in that direction.
Thanks in advance.
Try adding a #ResponseBody annotation on the method:
#Controller
public class SessionController {
#RequestMapping(value="/", method=RequestMethod.GET)
#ResponseBody
public String homeScreen(){
return "home";
}
}
This should output home on the page.
If you'd like to use View technologies, e.g. JSP, review the following chapter on the official Spring Framework documentation: http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/htmlsingle/spring-framework-reference.html#view
Update
"Just as with any other view technology you're integrating with Spring, for JSPs you'll need a view resolver that will resolve your views ". If you'd like to use JSP you should then add the following to your Web application context, then return the name of the file that shall be processed:
<!-- the ResourceBundleViewResolver -->
<bean id="viewResolver" class="org.springframework.web.servlet.view.ResourceBundleViewResolver">
<property name="basename" value="views"/>
</bean>
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
Is the above present in your Web application context? You can review the official documentation for further information: http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/htmlsingle/spring-framework-reference.html#view-jsp-resolver
Place a welcome file tag in web.xml file.
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
You must be having this index.jsp outside of WEB-INF. Put following code in it.
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%
response.sendRedirect("home");
%>
</body>
</html>
When application is loaded, it will call index.jsp and jsp will redirect it to /home action.
Then your controller will get called.
#Controller
public class SessionController {
// see the request mapping value attribute here, it is /home
#RequestMapping(value="/home", method=RequestMethod.GET)
public String homeScreen(){
return "home";
}
}
This will call your home jsp.
If you want to to return JSON from your spring controller, then you need jackson mapper bean initialized in spring context xml file.
<beans:bean id="jacksonMessageChanger" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
<beans:property name="supportedMediaTypes" value="application/json" />
</beans:bean>
<beans:bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<beans:property name="messageConverters">
<util:list id="beanList">
<beans:ref bean="jacksonMessageChanger" />
</util:list>
</beans:property>
</beans:bean>
You need to add jar or maven dependency to use jackson mapper.
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.8.5</version>
</dependency>
And to return JSON from controller, method would be like this :
#RequestMapping(value="/getContacts", method=RequestMethod.GET)
public #ResponseBody List<Contacts> getContacts(){
List<Contacts> contactList = prepareContactList();
return contactList;
}
This way you will get List in the success function of ajax call in the form of object and by iterating it you can get the details.
Finally I solve this only with configuring the dispatcher in web.xml on a different way.
First I added the view resolver to the servlet configuration file as David Riccitelli suggested me:
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/WEB-INF/jsp/" p:suffix=".jsp"/>
And then I configured the servlet mapping in web.xml:
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
That's what I was looking for, and no extra configuration is needed.
Doing this I call my root URL http://localhost:8084 and I can see the home screen I have coded in home.jsp.
Thanks for your support and suggestions.

The spring web mvc framework handle the jsp file dispatch as another request

I am new to spring web mvc framework,and I use struts 2 before.
I create a new dynamic web project using eclipse EE,and add all the jars to the /web-info/lib.
The whole hierarchy of the project is like this:
SpringMVCTest
WEB-INF
web.xml
example-servlet.xml
jsp
hello.jsp
lib
xxxx.jars
.....
This is the servlet definition:
<servlet>
<servlet-name>example</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>example</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
This is the example-servlet.xml:
<context:component-scan base-package="com.kk.web.controllers" />
<bean id="viewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
And the controller:
package com.kk.web.controllers;
#Controller("example")
#RequestMapping("/example")
public class ExampleController {
#RequestMapping("/hello")
#ResponseBody
public String hello() {
return "hello";
}
#RequestMapping("/hello_jsp")
public ModelAndView hello_jsp(){
ModelAndView mv=new ModelAndView("hello");
mv.addObject("message", "welcome");
return mv;
}
}
It worked when I run:
http://localhost:8080/SpringMVCTest/example/hello
But when I run:
http://localhost:8080/SpringMVCTest/example/hello_jsp
I got the warn:
2011-10-17 10:36:15 org.springframework.web.servlet.DispatcherServlet noHandlerFound
Warn: No mapping found for HTTP request with URI [/SpringMVCTest/WEB-INF/jsp/hello.jsp] in DispatcherServlet with name 'example'
It seems that the ExampleController works,it dispatch the request "/example/hello_jsp" to the right view "jsp/hello.jsp".
But then the spring take the file dispatch "/jsp/hello.jsp" as another request,then it will not find the matched url mapping in the "example" controller.
Why?? IMO,a requst must come from the client to server,the controller receive only one request here "/exmaple/hello_jsp",isn't it?
And How to fix it?
BTW,I can set the url pattern to "/*.xxx",but I do not want the suffix in the url.
Any ideas?
Previous answer did not work...
This posting looks similar: http://forum.springsource.org/showthread.php?55982-No-mapping-found-for-HTTP-request-with-MVC-requests
Summary: change
<servlet-mapping>
<servlet-name>example</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
to
<servlet-mapping>
<servlet-name>example</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
and checking my latest Spring MVC app I use the latter pattern (no * on the end).

Spring MVC: how to create a default controller for index page?

I'm trying to do one of those standard spring mvc hello world applications but with the twist that I'd like to map the controller to the root. (for example: http://numberformat.wordpress.com/2009/09/02/hello-world-spring-mvc-with-annotations/ )
So the only real difference is that they map it to host\appname\something and I'd like to map it to host\appname.
I placed my index.jsp in src\main\webapp\jsp and mapped it in the web.xml as the welcome file.
I tried:
#Controller("loginController")
public class LoginController{
#RequestMapping("/")
public String homepage2(ModelMap model, HttpServletRequest request, HttpServletResponse response){
System.out.println("blablabla2");
model.addAttribute("sigh", "lesigh");
return "index";
}
As my controller but I see nothing appear in the console of my tomcat.
Does anyone know where I'm messing up?
My web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">
<!-- Index -->
<welcome-file-list>
<welcome-file>/jsp/index.jsp</welcome-file>
</welcome-file-list>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/mvc-dispatcher-servlet.xml</param-value>
</context-param>
<servlet>
<servlet-name>springweb</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springweb</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
The mvc-dispatcher-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"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:annotation-config />
<context:component-scan base-package="de.claude.test.*" />
<bean id="viewResolver"
class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
I'm using Spring 3.0.5.release
Or is this not possible and do I need to put my index.jsp back in the root of the web-inf and put a redirect to somewhere inside my jsp so the controller picks it up?
I had the same problem, even after following Sinhue's setup, but I solved it.
The problem was that that something (Tomcat?) was forwarding from "/" to "/index.jsp" when I had the file index.jsp in my WebContent directory. When I removed that, the request did not get forwarded anymore.
What I did to diagnose the problem was to make a catch-all request handler and printed the servlet path to the console. This showed me that even though the request I was making was for http://localhost/myapp/, the servlet path was being changed to "/index.html". I was expecting it to be "/".
#RequestMapping("*")
public String hello(HttpServletRequest request) {
System.out.println(request.getServletPath());
return "hello";
}
So in summary, the steps you need to follow are:
In your servlet-mapping use <url-pattern>/</url-pattern>
In your controller use RequestMapping("/")
Get rid of welcome-file-list in web.xml
Don't have any files sitting in WebContent that would be considered default pages (index.html, index.jsp, default.html, etc)
Hope this helps.
The redirect is one option. One thing you can try is to create a very simple index page that you place at the root of the WAR which does nothing else but redirecting to your controller like
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<c:redirect url="/welcome.html"/>
Then you map your controller with that URL with something like
#Controller("loginController")
#RequestMapping(value = "/welcome.html")
public class LoginController{
...
}
Finally, in web.xml, to have your (new) index JSP accessible, declare
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
We can simply map a Controller method for the default view. For eg, we have a index.html as the default page.
#RequestMapping(value = "/", method = GET)
public String index() {
return "index";
}
once done we can access the page with default application context.
E.g http://localhost:8080/myapp
It works for me, but some differences:
I have no welcome-file-list in web.xml
I have no #RequestMapping at class level.
And at method level, just #RequestMapping("/")
I know these are no great differences, but I'm pretty sure (I'm not at work now) this is my configuration and it works with Spring MVC 3.0.5.
One more thing. You don't show your dispatcher configuration in web.xml, but maybe you have some preffix. It has to be something like this:
<servlet-mapping>
<servlet-name>myServletName</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
If this is not your case, you'll need an url-rewrite filter or try the redirect solution.
EDIT: Answering your question, my view resolver configuration is a little different too:
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/view/" />
<property name="suffix" value=".jsp" />
</bean>
It can be solved in more simple way:
in web.xml
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>*.htm</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.htm</welcome-file>
</welcome-file-list>
After that use any controllers that your want to process index.htm with #RequestMapping("index.htm"). Or just use index controller
<bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<prop key="index.htm">indexController</prop>
</props>
</property>
<bean name="indexController" class="org.springframework.web.servlet.mvc.ParameterizableViewController"
p:viewName="index" />
</bean>
Just put one more entry in your spring xml file i.e.mvc-dispatcher-servlet.xml
<mvc:view-controller path="/" view-name="index"/>
After putting this to your xml put your default view or jsp file in your custom JSP folder as you have mentioned in mvc-dispatcher-servlet.xml file.
change index with your jsp name.
One way to achieve it, is by map your welcome-file to your controller request path in the web.xml file:
[web.xml]
<web-app ...
<!-- Index -->
<welcome-file-list>
<welcome-file>home</welcome-file>
</welcome-file-list>
</web-app>
[LoginController.java]
#Controller("loginController")
public class LoginController{
#RequestMapping("/home")
public String homepage2(ModelMap model, HttpServletRequest request, HttpServletResponse response){
System.out.println("blablabla2");
model.addAttribute("sigh", "lesigh");
return "index";
}
The solution I use in my SpringMVC webapps is to create a simple DefaultController class like the following: -
#Controller
public class DefaultController {
private final String redirect;
public DefaultController(String redirect) {
this.redirect = redirect;
}
#RequestMapping(value = "/")
public ModelAndView redirectToMainPage() {
return new ModelAndView("redirect:/" + redirect);
}
}
The redirect can be injected in using the following spring configuration: -
<bean class="com.adoreboard.farfisa.controller.DefaultController">
<constructor-arg name="redirect" value="${default.redirect:loginController}"/>
</bean>
The ${default.redirect:loginController} will default to loginController but can be changed by inserting default.redirect=something_else into a spring properties file / setting an environment variable etc.
As #Mike has mentioned above I have also: -
Got rid of <welcome-file-list> ... </welcome-file-list> section in the web.xml file.
Don't have any files sitting in WebContent that would be considered default pages (index.html, index.jsp, default.html, etc)
This solution lets Spring worry more about redirects which may or may not be what you like.

Resources