Spring MVC http 500 error apache - spring

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 404.
what's wrong with the code..??
I am using Eclipse oxygen in that apache 8.5

Your servlet name in definition is HelloWorld
but in mapping servlet, is hello.
These names must be the same.

<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>
here you have used HelloWorld as the servlet name previously and you referring to that as hello later on which is not correct so please correct that just change the hello in servelt-mapping to HelloWorld and access the servlet as HelloWorld.ap it will work.

Related

404 - Http the requested is not available JavaEE Spring MVC

I am not very familiar with Spring MVC DriverManagerDataSource.I am trying to return a JSP from my controller. My Controller method is running well but when returning view, I'm getting a 404 error.
I don't know why I got this error If I'm telling this: in the web.xml
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
spring-servlet
<?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:context = "http://www.springframework.org/schema/context"
xmlns:mvc = "http://www.springframework.org/schema/mvc"
xsi:schemaLocation =
"
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
">
<context:component-scan base-package="controllers"></context:component-scan> <!-- com.javatpoint. -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<bean class = "org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name = "driverClassName" value = "com.mysql.jdbc.Driver"></property>
<property name = "url" value = "jdbc:mysql://localhost:3306/empleados"></property>
<property name = "username" value = "---"></property>
<property name = "password" value = "---"></property>
</bean>
<bean id="jt" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="ds"></property>
</bean>
<bean id = "dao" class = "dao.EmpDao">
<property name = "template" ref = "jt"></property>
</bean>
</beans>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
<display-name>SpringMVC</display-name>
<context-param>
<param-name>contextClass</param-name>
<param-value>
org.springframework.web.context.support.AnnotationConfigWebApplicationContext
</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
HomeController.java
package EjemploCRUD.SpringMVC.controller;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
#Controller
public class HomeController {
#RequestMapping(value="/")
public ModelAndView test(HttpServletResponse response) throws IOException{
return new ModelAndView("index");
}
}
MvcConfiguration.java
package EjemploCRUD.SpringMVC.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
#Configuration
#ComponentScan(basePackages="EjemploCRUD.SpringMVC")
#EnableWebMvc
public class MvcConfiguration extends WebMvcConfigurerAdapter{
#Bean
public ViewResolver getViewResolver(){
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".jsp");
return resolver;
}
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}
}
Error
Type Status Report
Message The requested resource [/SpringMVC/] is not available
Description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists.
folder structure,
in your application you used both (java-based and xml-based) configuration types. in this answer, used the xml-based configuration.
try with following steps.
modify the spring-servlet.xml file as follows,
<context:component-scan base-package="controllers, EjemploCRUD.SpringMVC.controller"></context:component-scan>
<mvc:resources mapping="/resources/**" location="/resources/" />
config the location of spring-servlet.xml file in web.xml file as follows,
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-servlet.xml</param-value>
</context-param>
in your application spring-servlet.xml and web.xml files are located under the WEB-INF/views directory.but these files not relevant to the view.hence, please move these two files into WEB-INF folder(best practice).
as per the web.xml file, configured the views (jsp files) path is WEB-INF/views directory. but in your folder structure index.jsp file is located under the WEB-INF folder. hence, get this error. please move index.jsp file into WEB-INF/views folder.

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>

Spring MVC HTTP 404 error

I learning SpringMVC so I am followed Spring 3.0 MVC Series from HERE.
As you can see, I completed Part1, Part2, and I am right now on Part3 where I am learning how to handle forms with Spring 3 MVC.
But I get this HTTP 404 eror, when I try to run my application. Project strucutre and this error you can see at image below.
How I can fix this?
ContactController.java code:
package net.viralpatel.spring3.controller;
import net.virtalpatel.spring3.form.Contact;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;
#Controller
#SessionAttributes
public class ContactController {
#RequestMapping(value = "/addContact", method = RequestMethod.POST)
public String addContact(#ModelAttribute("contact")
Contact contact, BindingResult result) {
System.out.println("First Name:" + contact.getFirstname() +
"Last Name:" + contact.getLastname());
return "redirect:contacts.html";
}
#RequestMapping("/contacts")
public ModelAndView showContacts() {
return new ModelAndView("contact", "command", new Contact());
}}
spring-servlet.xml code:
<?xml version="1.0" encoding="UTF-8"?>
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:component-scan
base-package="net.viralpatel.spring3.controller" />
<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>
****index.jsp code:****
<jsp:forward page="contacts.html"></jsp:forward>
web.xml code:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">
<display-name>Spring3MVC</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
Just change contact to contacts
change
return new ModelAndView("contact", "command", new Contact());
to
return new ModelAndView("contacts", "command", new Contact());
The issue is in your forward it will check for the contact.jsp but actually you have contacts.jsp (you have suffix property as .jsp )
your index.jsp is forwarded to contacts.html.
But you spring configuration does not have mapping for /contacts.html, you have mapped /contacts instead.
You need to change the /contacts mapping to
#RequestMapping("/contacts.html")
public ModelAndView showContacts() {
return new ModelAndView("contact", "command", new Contact());
}
localhost:8080/Spring3MVC/index.jsp As you can see, I try first to open index.jsp and then redirect to contact.jsp – Zookey 44 mins ago
I think you have it mixed up. 1) There is a typo, you say contact.jsp but the file name is contacts.jsp (file name in eclipse)
2) Where is the contacts.html file ?
I would suggest, you first return to the jsp and see if you can get your controller to return the jsp after that try redirecting to the html file after you create one.

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.

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