Spring 3 MVC - Controller is called but views are not found - spring

I'm trying to set up a skeleton Spring 3 MVC project but i'm having difficulties getting the views to render. I have followed the structure as described in the mvc-basic sample project and at http://blog.springsource.com/2009/12/21/mvc-simplifications-in-spring-3-0/?utm_source=feedburner&utm_medium=feed&utm_campaign=Feed%3A+Interface21TeamBlog+%28SpringSource+Team+Blog%29 to set up the web.xml, app-config.xml and mvc-config.xml files. The controller gets called but when it reaches the point of finding the view and rendering it i get a 404 error. The files are as follows:
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 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">
<!-- Handles all requests into the application -->
<servlet>
<servlet-name>myServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/app-config.xml
</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>myServlet</servlet-name>
<url-pattern>/app/*</url-pattern>
</servlet-mapping>
</web-app>
app-config.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:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
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">
<!-- Scans the classpath of this application for #Components to deploy as beans -->
<context:component-scan base-package="com.myProject" />
<!-- Application Message Bundle -->
<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="/WEB-INF/messages/messages" />
<property name="cacheSeconds" value="0" />
</bean>
<!-- Configures Spring MVC -->
<import resource="mvc-config.xml" />
</beans>
mvc-config.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:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<!-- Configures the #Controller programming model -->
<mvc:annotation-driven />
<mvc:view-controller path="/app" view-name="welcome"/>
<!-- Configures Handler Interceptors -->
<mvc:interceptors>
<!-- Changes the locale when a 'locale' request parameter is sent; e.g. /?locale=de -->
<bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor" />
</mvc:interceptors>
<!-- Saves a locale change using a cookie -->
<bean id="localeResolver" class="org.springframework.web.servlet.i18n.CookieLocaleResolver" />
<!-- Resolves view names to protected .jsp resources within the /WEB-INF/views directory -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>
In "Java Resources : src" -> com.myProject -> HelloWorldController.java i have:
package com.myProject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
#Controller
#RequestMapping(value="/helloworld")
public class HelloWorldController {
#RequestMapping(method=RequestMethod.GET)
public ModelAndView helloWorld() {
ModelAndView mav = new ModelAndView();
mav.setViewName("helloworld");
mav.addObject("message", "Hello World!");
return mav;
}
#RequestMapping(value="/Second", method = RequestMethod.GET)
public ModelAndView Second(){
ModelAndView mav = new ModelAndView();
mav.setViewName("Second");
mav.addObject("message", "Hello World!");
return mav;
}
}
and in WebContent/WEB-INF/views i have:
WebContent (folder)
WEB-INF (folder)
views (folder)
helloworld (folder)
helloworld.jsp (.jsp view)
helloworld.jsp (.jsp view)
welcome.jsp (.jsp view)
The views have straighforward html in them. When i request http://localhost:8080/projectname/app i correctly get the the views -> welcome.jsp page. However when i request http://localhost:8080/projectname/app/helloworld or http://localhost:8080/projectname/app/helloworld/ execution hits the correct controller actions but i get HTTP Status 404 - /projectname/WEB-INF/views/helloworld.jsp
Can anyone advise as to what is wrong?
Thanks

There are a few issues. The first one is that you only dispatch /app/* urls to Spring in your web.xml:
<url-pattern>/app/*</url-pattern>
That's fine if the request mapping was /app/helloworld, but means that /helloworld doesn't even get to spring. What you're probably wanting to do is to use a urlrewrite filter to map requests into the /app/* space.
Take a dependency on tuckey and then add this to your web.xml:
<filter>
<filter-name>UrlRewriteFilter</filter-name>
<filter-class>org.tuckey.web.filters.urlrewrite.UrlRewriteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>UrlRewriteFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
Then add a file called urlrewrite.xml in your WEB-INF directory, containing:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE urlrewrite PUBLIC "-//tuckey.org//DTD UrlRewrite 3.0//EN" "http://tuckey.org/res/dtds/urlrewrite3.0.dtd">
<urlrewrite default-match-type="wildcard">
<rule>
<from>/images/**</from>
<to>/images/$1</to>
</rule>
<rule>
<from>/scripts/**</from>
<to>/scripts/$1</to>
</rule>
<rule>
<from>/styles/**</from>
<to>/styles/$1</to>
</rule>
<rule>
<from>/**</from>
<to>/app/$1</to>
</rule>
<outbound-rule>
<from>/app/**</from>
<to>/$1</to>
</outbound-rule>
</urlrewrite>
After that, a request to /helloworld should go to the correct place. You'll probably want to change the root view controller too:
<mvc:view-controller path="/" view-name="welcome"/>

Looks like it is because you have not specified the viewClass property.
Can you try with
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
<property name="prefix" value="/WEB-INF/views/"/>
<property name="suffix" value=".jsp"/>
</bean>
It works for welcome page due to this
<mvc:view-controller path="/app" view-name="welcome"/>

I think the view needs to be in views/helloworld.jsp and not in views/helloworld/helloworld.jsp

You should set view Name as
mav.setViewName("/helloWorld/helloWorld");

You should change "mvc-config" to yourname-servlet.xml" yourname should be match with your servlet name in ur web.xml file that in ur case should be myservlet-servlet.xml because the spring dispatcher servlet look for the file with "-servlet" extension file name in WEB-INF folder.
and in your myservlet-servlet.xml file for suffix part you should say in this way : "WEB-INF/yourfoldername(e.g. view)" till your controller look for ur view name that u mentioned in ur controller method (e.g ModelAndView("hello")).

As you have following configuration:
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/"/>
<property name="suffix" value=".jsp"/>
</bean>
and your controller returning clean view name.
Verify your view files exists inside /WEB-INF/views/ while you run application.

Related

Spring MVC - 404 - The origin server did not find a current representation

Im trying to deploy a Spring MVC web app.
I want to redirect my index.jsp to another .jsp but i get this error.
HTTP Status 404 – Not Found
--------------------------------------------------------------------------------
Type Status Report
Description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists.
My project Struture:
src/main/java
com.example.beans
com.example.controller
com.example.dao
src/main/webapp/
WEB-INF
/jsp
test.jsp
spring-servlet.xml
web.xml
index.jsp
spring-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: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">
<!-- Provide support for component scanning -->
<context:component-scan
base-package="com.example />
<!--Provide support for conversion, formatting and validation -->
<mvc:annotation-driven />
<mvc:resources mapping="/resources/**"
location="/resources/" />
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<bean id="ds"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName"
value="com.mysql.jdbc.Driver"></property>
<property name="url"
value="jdbc:mysql://localhost:3306/dbexample></property>
<property name="username" value="root"></property>
<property name="password" value="root"></property>
</bean>
<bean id="jt" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="ds"></property>
</bean>
<bean id="dao" class="com.example.dao.ObjectDao">
<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"
id="WebApp_ID" version="3.0">
<display-name>Example</display-name>
<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>
Controller
#Controller
public class MainController {
#RequestMapping("hello")
public String redirect() {
return "viewpage";
}
#RequestMapping("/")
public String display() {
return "index";
}
#RequestMapping("test")
public String test() {
return "test";
}
index.jsp
<html>
<body>
<h2>Hello World!</h2>
View test
Click here...
</body>
</html>
When i clik on test I get this error in the sts log:
org.springframework.web.servlet.DispatcherServlet noHandlerFound
WARNING: No mapping for GET /example/hello
You should use '/' for mapping for your controllers.
You could try this:
#RequestMapping("/example/hello")
public String redirect() {
return "viewpage";
}
And it's better to use relative path for links:
View test
Click here...
More about pageContext see this

Spring - configuring a HelloWorld controller

I am new to spring, and I just want going to the following url http://localhost:8080/DispatcherExample/dispatcher/welcome to take me to the index.jsp page. DispatcherExample is the name of the project, dispatcher is the url of the dispatcher servlet and welcome is the url mapped to the controller method. Here are my classes:
WelcomeController.java
package com.paymon;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
#Controller
public class WelcomeController {
#RequestMapping("/welcome")
public ModelAndView welcome()
{
System.out.println("welcome entered");
ModelAndView model = new ModelAndView();
model.setViewName("index");
return model;
}
}
web.xml
<web-app>
<!-- The front controller of this Spring Web application, responsible for handling all application requests -->
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<!-- Map all requests to the DispatcherServlet for handling -->
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/dispatcher/</url-pattern>
</servlet-mapping>
</web-app>
dispatcher-servlet.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd">
<context:component-scan base-package="com.paymon" />
<mvc:annotation-driven />
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver" >
<property name="prefix">
<value></value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
</beans>
There are 2 things you have to check.
First, location of your jsp file. If it is in root folder then its fine otherwise put the location of jsp file in prefix.
<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>
Second, if your jsp file is in root folder then it can be accessed using following url.
http://localhost:8080/DispatcherExample/welcome
If you want your url to be the following
http://localhost:8080/DispatcherExample/dispatcher/welcome
Then add #RequestMapping("/dispatcher/welcome")
Note:
DispatcherExample is the name of the war/project
Don't get confused with servlet-name dispatcher, it has no contribution in url, it is just used to identify that servlet in web.xml
Advice:
If you are new, use spring boot and annotation based configuration, the xml configuration is a primitive thing now.

Spring MVC Themes Not working

I am trying to execute a Spring MVC application that uses Spring MVC theme feature. I am following this example https://www.youtube.com/watch?v=OiQql85qsos But somehow its not working, here is the project structure in STS
I just have a HomeController
#Controller
public class HomeController {
#RequestMapping("/")
public String getHomePage(){
return "home";
}
}
Here is the 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"
id="WebApp_ID" version="3.0">
<display-name>SpringMVCThemes</display-name>
<servlet>
<servlet-name>config</servlet-name>
<servlet- class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>config</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
Below is the config-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: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-4.1.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd">
<mvc:annotation-driven></mvc:annotation-driven>
<context:component-scan base-package="co.edureka.controllers"/>
<mvc:resources mapping="/resources/**" location="/resources/*" />
<mvc:resources mapping="/images/**" location="/resources/images/" />
<mvc:resources mapping="/css/**" location="/resources/css/" />
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
<bean id="themeSource"
class="org.springframework.ui.context.support.ResourceBundleThemeSource">
<property name="basenamePrefix" value="META-INF.theme-" />
</bean>
<bean id="themeChangeInterceptor"
class="org.springframework.web.servlet.theme.ThemeChangeInterceptor">
<property name="paramName" value="theme" />
</bean>
<bean id="themeResolver"
class="org.springframework.web.servlet.theme.CookieThemeResolver">
<property name="defaultThemeName" value="default" />
</bean>
<mvc:interceptors>
<ref bean="themeChangeInterceptor"/>
</mvc:interceptors>
</beans>
Here is the content of theme-black.properties (under WebContent/META-INF)
css=resources/css/theme-black.css
Below is the content of theme-black.css (under WebContent/resources/css)
body {
background-color: #DBF5FF;
color: #007AAB;
}
Here is the home.jsp but on clicking on other themes link it does not change the themes
I checked the cookies , there is a cookie with name org.springframework.web.servlet.theme.CookieThemeResolver.THEME
How to make it work ?
First off all your interceptor setup is flawed. You are using <mvc:annotation-driven /> and as such should use the <mvc:interceptors /> to register your interceptors. You should remove the DefaultAnnotationHandlerMapping bean.
<mvc:interceptors>
<ref bean="themeChangeInterceptor"/>
</mvc:interceptors>
Next to be able to use the selected theme in your JSP you have to use the theme tag from the Spring tag library.
<%# taglib prefix="spring" uri="http://www.springframework.org/tags"%>
Then in your header include the stylesheet you want to use.
<head>
<link rel="stylesheet" href="<spring:theme code='styleSheet'/>" type="text/css"/>
</head>

Not able to run spring application using XML configuration

I am new to spring, trying to run the Spring application through XML configuration, but i am not getting any error in console. But the application is not running and i am getting the 404 error. I didn't add the servlet-api jar in WEB-INF/lib. Can anyone please help me? Thanks in advance.
package com.raistudies.action;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;
public class HelloWorldAction extends AbstractController {
#Override
protected ModelAndView handleRequestInternal(HttpServletRequest arg0,
HttpServletResponse arg1) throws Exception {
System.out.println(" helloworld... ");
ModelAndView mav = new ModelAndView();
mav.setViewName("hello");
mav.addObject("helloMessage", "Hello World from My First Spring 3 mvc application with xml configuration...");
return mav;
}
}
hello.jsp - WEB-INF/jsp/
<html>
<head>
<title>Hello World with spring 3 MVC XML configuration</title>
</head>
<body>
<h1>Welcome! Spring MVC XML configuration is working well</h1>
${helloMessage}
</body>
</html>
index.jsp - WEB-INF
<html>
<head>
<title>rai studies</title>
</head>
<body>
Welcome...
<br>Click here to check the output :-)
</body>
</html>
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" 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_3_0.xsd"
id="WebApp_ID_1" version="3.0">
<display-name>HWEWS3MVCIEA</display-name>
<servlet>
<servlet-name>SpringMVCDispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/app-config.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>SpringMVCDispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
app-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
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-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd">
<bean name="/hello.htm" class="com.raistudies.action.HelloWorldAction" />
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
libraries under the WEB-INF/lib
commons-logging-1.1.2.jar
jstl-1.2.jar
log4j-1.2.16.jar
spring-aspects-3.2.5.RELEASE.jar
spring-beans-3.2.5.RELEASE.jar
spring-context-3.2.5.RELEASE.jar
spring-core-3.2.5.RELEASE.jar
spring-expression-3.2.5.RELEASE.jar
spring-web-3.2.5.RELEASE.jar
spring-webmvc-3.2.5.RELEASE.jar
supportingLibrary under WEB-INF/supportingLibrary
servlet-api-2.5.jar
Your bean definition of the Action is not correct. You have to define a controller bean with some valid name like:
<bean name="helloWorldController" class="com.raistudies.action.HelloWorldAction" />
Then you need to add the url mapping definition to your configuration to map requests to the defined controller.
<bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<prop key="/hello.htm">helloWorldController</prop>
</props>
</property>
</bean>

New to Spring unable to get controller working

I am new to Spring and have looked at countless examples and cannot figure out this problem. The issue that I have is that when I click the link from my index.jsp page it does not forward to the hello.jsp page. I do not know why. I have spent 2 days looking up examples and trying countless examples trying to determine what the problem is to no avail. I am hoping you can tell me what the issue is. I am using NetBeans 7.2, Tomcat 7, JDK 7, Spring 3.2.1. The redirect.jsp works to get to the index.jsp page, but clicking the link on the index.jsp page gives me a 404 error.
The way I understand it, the welcome-file is the redirect.jsp (not sure how this file is handled and why it is not gine through the dispatcher - because it is a jsp?). This redirects to an htm file. The dispatcher finds a url mapping that matches the index.htm and calls the indexController, which sends to the "index" view, which is "/WEB-INF/jsp/" + index + ".jsp".
When Tomcat starts up I see the following messages:
Mapped URL path [/helloworld] onto handler 'helloWorldController'
Mapped URL path [/helloworld/*] onto handler 'helloWorldController'
Mapped URL path [/index.htm] onto handler 'indexController'
Clicking the link in the index.jsp gives the following warning message:
No mapping found for HTTP request with URI [/WTSpring3/hello.htm]
My web files are layed out as follows:
web
WEB-INF
jsp
hello.jsp
index.jsp
applicationContext.xml
dispatcher-servlet.xml
web.xml
redirect.jsp
redirect.jsp
<% response.sendRedirect("index.htm"); %>
index.jsp (this is the one I can never get to work. I am not sure if I have the link incorrect of the Spring setup).
<html><body>
Say Hello
</body></html>
hello.jsp
<html>
<body>${message}</body>
</html>
web.xml
- note he url-pattern here is *.htm, which is what I use in my index.jsp.
<?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>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>*.htm</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>redirect.jsp</welcome-file>
</welcome-file-list>
</web-app>
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:tx="http://www.springframework.org/schema/tx"
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.2.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd">
<bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping" />
<context:component-scan base-package="net.mvp.spring3.controller" />
<bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<prop key="index.htm">indexController</prop>
</props>
</property>
</bean>
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/WEB-INF/jsp/"
p:suffix=".jsp" />
<bean name="indexController"
class="org.springframework.web.servlet.mvc.ParameterizableViewController"
p:viewName="index" />
</beans>
HelloWorldController.java
package net.mvp.spring3.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.portlet.ModelAndView;
#Controller
public class HelloWorldController {
#RequestMapping("hello")
public ModelAndView helloWorld() {
String message = "Hallo Asgard";
return new ModelAndView("hello", "message", message);
}
}
Add a new bean to dispatcher-servlet.xml
<bean id="helloWorldController"
class="net.mvp.spring3.controller.HelloWorldController" />
replace your bean with id urlMapping with the given below code
<bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<prop key="index.htm">indexController</prop>
<prop key="hello.htm">helloWorldController</prop>
</props>
</property>
Note : No need to change the #RequestMapping("hello")
Can you change hello.htm filename to hello2.jsp or something like this? I mean, try to use different name from request mapping.
#Controller
public class HelloWorldController {
#RequestMapping("hello") // what the user calls for, the request
public ModelAndView helloWorld() {
String message = "Hallo Asgard";
return new ModelAndView("hello2", "message", message); // the response
//"hello" in ModelAndView is the same "hello" as the one in views.xml
}
}
hello2.jsp
<html>
<body>${message}</body>
</html>
There are probably other ways to do this but this is how i learned it, with view beans.
What happens is the following:
the user clicks a link with a certain name i.e. www.yoursite.com/hello
spring looks for 'hello' in the requestmappings.
if the requestmapping is found, the corresponding method is executed.
that method returns a ModelAndView containing the alias(hello) of an url(WEB-INF/jsp/hello.jsp) that must be defined in the views.xml that is in the same location as your jsp files.
finally the page from the url(WEB-INF/jsp/hello.jsp) of the alias hello is shown to the user.
The views.xml defines the aliases for the urls of the different jsp files. So in that file you say that hello corresponds to WEB-INF/jsp/hello.jsp.
It looks something along these lines:
<bean id="jspViewResolver" 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>
<bean id="excelViewResolver" class="org.springframework.web.servlet.view.XmlViewResolver">
<property name="order" value="1"/>
<property name="location" value="/WEB-INF/views.xml"/>
</bean>
<!-- in views.xml -->
<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="hello" class="org.springframework.web.servlet.ModelAndView">
<property name="hello" value="/WEB-INF/jsp/hello.jsp" />
</bean>
</beans>
The requestmapping in your controller looks the same:
#Controller
public class HelloWorldController {
#RequestMapping("hello") // what the user calls for, the request
public ModelAndView helloWorld() {
String message = "Hallo Asgard";
return new ModelAndView("hello", "message", message); // the response
//"hello" in ModelAndView is the same "hello" as the one in views.xml
}
}
I hope that helps you out.

Resources