Can't use freemarker with Spring MVC 3 - spring

I created a simple Spring MVC 3 application and want to use freemarker template engine. I cofigure *-context.xml as describes in off Spring's docs, but in browser I get 404 Page not found error. this is my code:
HelloWorldController.java
#Controller
#RequestMapping("/hello")
public class HelloWorldController {
private static final Logger log = Logger.getLogger(HelloWorldController.class);
#RequestMapping(value="/{name}", method = RequestMethod.GET)
public String hello(#PathVariable String name, Model model) {
String result = "Hello, " + name;
model.addAttribute("result", result);
return "hello";
}
}
this is my hello.ftl in WEB-INF/freemarker folder
<!doctype html>
<html>
<head>
<title>Hello</title>
</head>
<body>
<h1>
Hello world!
</h1>
<P> The time on the server is ${result}. </P>
</body>
</html>
and my servlet-context.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
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">
<!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->
<!-- Enables the Spring MVC #Controller programming model -->
<annotation-driven />
<!-- freemarker config -->
<beans:bean id="freemarkerConfig" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
<beans:property name="templateLoaderPath" value="/WEB-INF/freemarker/"/>
</beans:bean>
<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
<resources mapping="/resources/**" location="/resources/" />
<!-- Resolves views selected for rendering by #Controllers to .jsp resources in the /WEB-INF/views directory -->
<beans:bean class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">
<beans:property name="prefix" value="" />
<beans:property name="suffix" value=".ftl" />
<beans:property name="cache" value="false" />
</beans:bean>
<context:component-scan base-package="org.example.simple" />
</beans:beans>
what is wrong and why I get 404 when I go to localhost:8080/simple/hello/username ?
please, help
EDIT:
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">
<!-- The definition of the Root Spring Container shared by all Servlets and Filters -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/root-context.xml</param-value>
</context-param>
<!-- Creates the Spring Container shared by all Servlets and Filters -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- Processes application requests -->
<servlet>
<servlet-name>appServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>appServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>

its probably wrong configuration for spring mvc, not freemarker. Seems that spring cant find your Controller. Did you add dispatcherServlet in your web.xml?

Related

Spring JPA, JSON, Security Exception No bean named 'springSecurityFilterChain' is defined

I apologize that this is a common question - but I am a bit lost trying to correct my code. I have a JPA/JSON/Spring Security application that is failing to start with the exception: "No bean named 'springSecurityFilterChain' is defined". I have attached my web.xml and security-context xml below. Fromwhat I can work out the later may not being loaded correctly? Any help appreciated. I have been through other questions with no luck
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>Application</display-name>
<!-- The definition of the Root Spring Container shared by all Servlets and Filters -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath:root-context.xml
classpath:security-context.xml
</param-value>
</context-param>
<!-- Creates the Spring Container shared by all Servlets and Filters -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- Processes application requests -->
<servlet>
<servlet-name>api</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/api/servlet-context.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>api</servlet-name>
<url-pattern>/api/*</url-pattern>
</servlet-mapping>
<!-- Spring Security -->
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
security-context.xml (/WEB-INF/spring/api/security-context.xml)
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:sec="http://www.springframework.org/schema/security"
xsi:schemaLocation="
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.2.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd">
<!-- Rest authentication entry point configuration -->
<http auto-config="true" use-expressions="true" create-session="stateless"
entry-point-ref="restServicesEntryPoint" authentication-manager-ref="authenticationManagerForRest">
<intercept-url pattern="/api/**" />
<sec:form-login authentication-success-handler-ref="mySuccessHandler" />
<sec:access-denied-handler ref="myAuthenticationAccessDeniedHandler" />
<http-basic />
</http>
<!-- Entry point for REST service. -->
<beans:bean id="restServicesEntryPoint" class="foo.bar.RestAuthenticationEntryPoint1" />
<!-- Custom User details service which is provide the user data -->
<beans:bean id="customUserDetailsService" class="foo.bar.CustomUserDetailsService" />
<!-- Connect the custom authentication success handler -->
<beans:bean id="mySuccessHandler" class="foo.bar.RestAuthenticationSuccessHandler" />
<!-- Using Authentication Access Denied handler -->
<beans:bean id="myAuthenticationAccessDeniedHandler" class="foo.bar.RestAuthenticationAccessDeniedHandler" />
<!-- Authentication manager -->
<authentication-manager alias="authenticationManagerForRest">
<authentication-provider user-service-ref="customUserDetailsService" />
</authentication-manager>
<!-- Enable the annotations for defining the secure role -->
<global-method-security secured-annotations="enabled" />
</beans:beans>
SpringSecurityConfig.java
#Configuration
#ImportResource({ "/WEB-INF/spring/security-context.xml" })
#ComponentScan("foo.bar.security")
public class SpringSecurityConfig {
public SpringSecurityConfig() {
super();
}
}

Spring MVC routing in Google App Engine

I'm trying to build a spring mvc web on google app engine. But I can't make the routing/mapping work.
I have my HelloController, which indicates that I want to map to /hello
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
#Controller
#RequestMapping("/hello")
public class HelloController {
#RequestMapping(method = RequestMethod.GET)
public String Index() {
return "hello";
}
}
and a very simple hello.jsp file
<html>
<head><title>Hello :: Spring Application</title></head>
<body>
<h1>Hello - Spring Application</h1>
<p>Greetings.</p>
</body>
</html>
however, when I try to access /hello, I will get 404 not found.
here is my xml mapping file mvc-servlet.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
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.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<context:component-scan base-package="com.example.web" />
<mvc:annotation-driven />
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
What am I missing ? How to fix it ?
Do you have a web.xml ?
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/root-context.xml</param-value>
</context-param>
<!-- Creates the Spring Container shared by all Servlets and Filters -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- Processes application requests -->
<servlet>
<servlet-name>appServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>appServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
ContextLoaderListener ties the ApplicationContext lifecycle to
ServletContext lifecycle and automate the creation of
ApplicationContext. ApplicationContext is the place for Spring beans
and we can provide it’s configuration through contextConfigLocation
context parameter. root-context.xml file provides the configuration
details for WebApplicationContext.
Her eis a tutorial http://www.journaldev.com/2433/spring-mvc-tutorial-for-beginners-with-spring-tool-suite

bean not injecting on spring MVC

im learning Spring MVC and i was working on a basic form example, but i dont why a bean its not injecting the information correctly so i would like to know if someone can direct me.
The controller
package com.carloscortina.Test;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.carloscortina.toy.model.Member;
#Controller
public final class NomineeController {
private static final Logger log=
Logger.getLogger(NomineeController.class);
private String thanksViewName ="thanks";
public void setThanksViewName(String thanksViewName) {
this.thanksViewName = thanksViewName;
}
#RequestMapping(method = RequestMethod.GET)
public Member form() { return new Member();}
#RequestMapping(method = RequestMethod.POST)
public String processFormData(Member member){
log.info("Processing nominee: " + member);
log.info("thanksViewName: " + thanksViewName);
return thanksViewName;
}
the root-context.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- Root Context: defines shared resources visible to all other web components -->
<bean id="formAnswer"
class="com.carloscortina.Test.NomineeController"
p:thanksViewName="thanks" />
</beans>
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">
<!-- The definition of the Root Spring Container shared by all Servlets and Filters -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/root-context.xml</param-value>
</context-param>
<!-- Creates the Spring Container shared by all Servlets and Filters -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- Processes application requests -->
<servlet>
<servlet-name>appServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>appServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
Servlet-context.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
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">
<!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->
<!-- Enables the Spring MVC #Controller programming model -->
<annotation-driven />
<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
<resources mapping="/resources/**" location="/resources/" />
<!-- Resolves views selected for rendering by #Controllers to .jsp resources in the /WEB-INF/views directory -->
<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix" value="/WEB-INF/views/" />
<beans:property name="suffix" value=".jsp" />
</beans:bean>
<context:component-scan base-package="com.carloscortina.Test" />
im using STS as IDE and the Spring mvc template included.
im not sure the bean its not being injected in the controller so when the form its submitted it redirects correctly, if i hardcode the thanks in the controller it works.
Thanks in advance for the help i know that this might be a basic error , so thank you.
*Edit
Well, maybe it related to the annotation driven, but I'm still not sure, i havent been able to make this thing work.
So the controller cant rad a bean from the root-context.xml?
or anyone can tell me how to do it with auto wire, the idea its just to not hardcode the value of thanksViewName on the controller.
You need to add the following to your servlet-context.xml configuration file, you don't need to declare annotated beans in the XML file.
<mvc:annotation-driven />
<context:component-scan base-package="com.carloscortina" />
My suggestion would be to download Spring Stool Suite (STS) and create a new spring template project (selecting the MVC template), it will create a runnable project and that way you can see how everything is put together.

My Spring application does not open another page

I have created a Spring application using netbeans, I did not change any of configuration. In index.jsp I have a link to another page but it does not get to the second page and shows "The requested resource () is not available."
in the server console it shows the following warning
"WARNING: No mapping found for HTTP request with URI [/Myapp/emp.htm] in DispatcherServlet with name 'dispatcher'"
my emp.jsp file is in jsp folder.
index.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Welcome to Spring Web MVC project</title>
</head>
<body>
emp
</body>
</html>
dispatcher-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:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
<bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping"/>
<!--
Most controllers will use the ControllerClassNameHandlerMapping above, but
for the index controller we are using ParameterizableViewController, so we must
define an explicit mapping for it.
-->
<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" />
<!--
The index controller.
-->
<bean name="indexController"
class="org.springframework.web.servlet.mvc.ParameterizableViewController"
p:viewName="index" />
<bean name="/emp.htm" class="controller.Employee"/> <<I changed this to "/Myapp/emp.htm" as well but does not work
</beans>
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>*.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>
Employee.java
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package controller;
import org.springframework.web.servlet.mvc.Controller;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.io.IOException;
public class Employee implements Controller {
protected final Log logger = LogFactory.getLog(getClass());
#Override
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
logger.info("Returning hello view");
return new ModelAndView("emp.jsp");
}
}
Change the <a href> to get the actual url like this
<a href="<c:url value="/emp"/>" />
Also make sure that the Dispatcher servlet is mapped in your web.xml
<servlet>
<servlet-name>DispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>DispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
More about Spring MVC implementation can be found here
I've solved it by adding
<prop key="emp.htm">empController</prop>
and
<bean name="empController"
class="org.springframework.web.servlet.mvc.ParameterizableViewController"
p:viewName="emp" />
#Daniel
Yes, I can see that emp.jsp is a simple message jsp. The thing is this is how MVC pattern works(no thing to do with Spring). MVC is all about having a dispatcher sitting in front of all request and route the request to proper resources(e.g. controller,servlet, etc)
If the message in the jsp is dynamic generated, I reckon the request should go through a controller and forwarded to emp.jsp. If the whole point of emp.jsp is just some kinda of static page, you can put emp.js under webapp/static/emp.jsp and in your spring servlet configuration file indicate that everything under /static should by pass Spring ServletDispatcher.
The configuration file will look like this
<mvc:resources mapping="/static/**" location="/static/" />
By doing so, the request /static/emp.jsp will work and do not go through Spring DispatcherServlet.

Why doesn't bean name of /home.jsp not work for BeanNameUrlHandlerMapping?

In the following program, if I replace "/home.htm" with "/home.jsp" in dispatcher-servlet.xml and index.jsp, then the server is not able to find home.jsp. Are strings ending with ".jsp" invalid as bean name?
dispatcher-servlet.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.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd">
<bean id="handlerMapping" class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/>
<bean name="/home.htm" class="com.sample.HomePageController" />
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/jsp/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
</beans>
index.jsp
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Dynamic Tiles</title>
</head>
<body>
<form action="/home.htm" method="post">
Please enter your name:
<input type="text" name="visitorName" />
<input type="submit" value="Go"/>
</form>
</body>
</html>
HomePageController.java
package com.sample;
import org.apache.log4j.Logger;
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 HomePageController extends AbstractController {
private static Logger logger = Logger.getLogger(HomePageController.class);
HomePageController () {
logger.info("Constructing HomePageController object");
};
public ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception {
logger.info("Handling request for home.jsp");
return new ModelAndView("home", "visitorName", request.getParameter("visitorName"));
}
}
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">
<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>
</web-app>
There are several pieces of your application that need to be modified for it to work as intended. The first piece is the Dispatcher Servlet mapping in web.xml. In Spring the dispatcher is used to route particular requests from the client to Spring controllers within the application. What requests are routed via the dispatcher is determined by the url-pattern specified in the web.xml file for the servlet: org.springframework.web.servlet.DispatcherServlet.
In your case we want to set the url-pattern to something that does not conflict with accessing your jsp files. Since you have specified a viewResolver in your Spring configuration that prefixes generic names with /WEB-INF/jsp/ and suffixes them with .jsp, we must use a url-pattern other than .jsp.
If the .jsp url-pattern were used, a request would first be processed by the dispatcher servlet and routed to any mapped controller. If the controller attempts to use a view name to navigate to another page, for example, home, the view name is prefixed/suffixed resulting in a url: /WEB-INF/jsp/home.jsp. This constructed URL matches the .jsp url-pattern specified for the dispatcher and an attempt to route /WEB-INF/jsp/home.jsp is made, most likely failing because no mapping is found.
To remedy this problem we setup your web.xml 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">
<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>*.do</url-pattern>
</servlet-mapping>
</web-app>
As you can see, we map the dispatcher to the url-pattern *.do. This allows the dispatcher to be used to route requests without interference with common file prefixes.
Changing the url-pattern to *.do requires us to change the action on your form. I modified your form to the following:
Index.jsp
<%# page contentType="text/html;charset=UTF-8" language="java"%>
<html>
<head>
<title>Dynamic Tiles</title>
</head>
<body>
<form action="home.do" method="post">
Please enter your name: <input type="text" name="visitorName" />
<input type="submit" value="Go" />
</form>
</body>
</html>
I also assumed that all of your .jsp files are located within the WEB-INF directory. This requires us to use a controller to access each of these .jsp files. Mappings to the controllers must be created in your Spring configuration file for the dispatcher and the appropriate controller for index.jsp must be created. Notice that I am using the .do suffix for the mappings.
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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="handlerMapping"
class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping" />
<bean name="/home.do" class="com.sample.HomePageController" />
<bean name="/index.do" class="com.sample.IndexPageController" />
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/jsp/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
</beans>
IndexPageController.java
package com.sample;
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 IndexPageController extends AbstractController {
#Override
protected ModelAndView handleRequestInternal(HttpServletRequest arg0,
HttpServletResponse arg1) throws Exception {
return new ModelAndView("index");
}
}
Just to be thorough, I created a home.jsp file to test the application since one was not provided. Here is my home.jsp file:
Home.jsp
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# page session="false" %>
<html>
<head>
<title>Home</title>
</head>
<body>
<h1>
Hello, ${visitorName}
</h1>
<P> The time on the server is ${serverTime}. </P>
</body>
</html>
You decided that dispatcher would only handle .htm-ended urls but then you want it to handle .jsp-ended url. For the latter to work just change url-pattern element's content in web.xml to, for example, something like this:
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>*.jsp</url-pattern>
</servlet-mapping>

Resources