Spring - configuring a HelloWorld controller - spring

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.

Related

spring mvc 404 error in my project [duplicate]

This question already has answers here:
Why does Spring MVC respond with a 404 and report "No mapping found for HTTP request with URI [...] in DispatcherServlet"?
(13 answers)
Closed 5 years ago.
Im new to MVC. Ive been able to do the tutorial of a couple examples with no problem. Im going to send this project .war file to a potential employer. And he's impatiently waiting.
Im getting a 404 error when trying to run http://localhost:8080/ProductStore/index
My project dir structure is as follows:
ProductStore
src/java/main
com.productstore.dao
ProductsDoa.java
com.productstore.controller
Productscontroler.java
com.productstore.domain
Products.java
com.productstore.service
ProductsService.java
WEB-INF
jsp
index.jsp
spring-servlet.xml
web.xml
Im at a complete loss.
My config files are as follows:
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.xsd"
id="WebApp_ID" version="2.5">
<display-name>Spring3-Hibernate</display-name>
<welcome-file-list>
<welcome-file>/WEB-INF/jsp/index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
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:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:lang="http://www.springframework.org/schema/lang"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd
http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">
<mvc:annotation-driven />
<context:annotation-config />
<context:component-scan base-package="com.productstore" />
<bean 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="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="classpath:messages" />
<property name="defaultEncoding" value="UTF-8" />
</bean>
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
p:location="/WEB-INF/jdbc.properties" />
<bean id="dataSource"
class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"
p:driverClassName="${jdbc.driverClassName}"
p:url="${jdbc.databaseurl}" p:username="${jdbc.username}"
p:password="${jdbc.password}" />
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation">
<value>classpath:hibernate.cfg.xml</value>
</property>
<property name="configurationClass">
<value>org.hibernate.cfg.AnnotationConfiguration</value>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${jdbc.dialect}</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<tx:annotation-driven />
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
</beans>
My controller class is as follows:
package com.productstore.controller;
package com.productstore.controller;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.productstore.domain.Products;
import com.productstore.service.ProductsService;
#Controller
public class ProductsController {
#Autowired
private ProductsService productsService;
#RequestMapping(value = "/index", method = RequestMethod.GET)
public String listProducts (Map<String, Object> map) {
System.out.println("index");
map.put("products", new Products());
map.put("productsList", productsService.listProducts());
return "index";
}
#RequestMapping(value = "/add", method = RequestMethod.POST)
public String addProducts(#ModelAttribute("products")
Products products, BindingResult result) {
productsService.addProducts(products);
return "redirect:/index";
}
#RequestMapping("/delete/{Id}")
public String deleteProducts(#PathVariable("Id")
Integer Id) {
productsService.removeProducts(Id);
return "redirect:/index";
}
}
If your application starts without errors the problem could be in your servlet mapping.
You map it as:
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
which means mapping to root context. Try to change it to following
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
Just insure whether you have entry of component scan in servlet-context.xml file.
<context:component-scan base-package="com.productstore.service.*" />
let me know if you still face the issue.

#Autowired is not working in restfull service with spring

This is the mapping part:
#Path("/hello")
public class BookRestController {
#Autowired
BookService service;
#GET
public String getMsg() {
System.out.println("in controller");
List<BookDto> dto=service.loadAll();
System.out.println(dto);
return "dto";
}
}
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>springJdbc</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<description></description>
<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>/</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>jersey-serlvet</servlet-name>
<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>jersey-serlvet</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
</web-app>
servlet-dispatcher.xml code:
<?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"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:tx="http://www.springframework.org/schema/tx"
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
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- controller package detail -->
<context:component-scan base-package="com.app.controller,com.app.service,com.app.dao.hib" />
<!-- -->
<mvc:annotation-driven/>
<!-- -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver" p:maxUploadSize="1500000"/>
<!-- -->
<mvc:resources mapping="/static/**" location="/static/" />
<!-- view resolver -->
<bean id="viewResolver1" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/jsps/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
<!-- creating connection detail of hibernate (connection pooling) -->
<bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/db1"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</bean>
<!-- Hibernate mapping and configuration file details (Session factory details) -->
<bean id="mySessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="myDataSource" />
<property name="annotatedClasses">
<list>
<value>com.app.entity.BookEntity</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<!-- <prop key="hibernate.hbm2ddl.auto">create</prop> -->
</props>
</property>
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="mySessionFactory" />
</bean>
</beans>
It's giving null pointer exception on service or anything I am using as autowired i.e it's having problems autowiring. Can anyone help with this?I guess i am missing something which is used to implement restFull service coz the application is working fine with simple spring application
Interface :
public interface BookService {
}
Class which implements interface BookService:
#Service
public class BookServiceImpl implements BookService {
}
To autowire BookServiceImpl class, you have to put #Autowired annotation on interface name in BookRestController class and #Controller annotation on your controller class:
#Controller
public class BookRestController {
#Autowired
private BookService bookService;
}
also you have to take care of configuration, like for component scanning you have to add following line in your spring configuration file. Put
<context:component-scan base-package="com.org.dao"/>
in spring configuration xml and change com.org.dao to your package name where dao files placed in application.
This is answered in this thread - Spring DI - Autowired property is null in a REST service
Essentially Jersey doesn't automatically do Spring autowiring for you. You need to get the Spring stuff to happen with the Jersey servlet object.

Spring #Transactional not creating transactions

I am seriously beating my head against a wall with Spring transactions. I have searched for days trying to get #Transactional to work. Any help would GREATLY appreciated!
I am using Spring 3.2 for a web app accessing a MySQL database (I'm using Spring MVC, JDBC, and Security). The mysql tables are using InnoDB. I'm struggling to get declarative transactions to work (I tried using programmatic transactions and that worked successfully). I have controllers calling service methods that are annotated with #Transactional. The controllers are configured in the servlet xml file and the services/dao's are configued in a separate application xml file. I cannot seem to find the right configuration for #Transactional to be picked up and create transactions. There are no errors - just no transactioning. Here are the details of my setup:
Web application using DispatcherServlet, configured with a servlet XML file, using annotated controllers. Controllers have Service interfaces injected.
Service methods are annotated with #Transactional and call injected DAO classes.
Service classes are annotated with #Named, and the app is configured to pick these up in spring-app-context.xml using component-scan.
Transactioning configuration is setup in spring-app-context.xml (not in the servlet configuration file).
web.xml:
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/config/spring-app-context.xml
/WEB-INF/config/spring-security-context.xml
</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<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/config/spring-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>
spring-servlet-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:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
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">
<!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->
<!-- Scans within the base package of the application for #Components to configure as beans -->
<!-- #Controller, #Service, #Configuration, etc. -->
<context:component-scan base-package="ewarrants.web" />
<!-- Enables the Spring MVC #Controller programming model -->
<mvc:annotation-driven />
<bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
<context:property-placeholder location="/WEB-INF/config/ewarrants.properties"/>
</beans>
Here is a sample controller setup:
#Inject
IUserService userService;
#RequestMapping(value = "/register", method = RequestMethod.POST)
public String processRegistration(#Valid #ModelAttribute UserRegistrationVM incomingVM, BindingResult result, Model model) throws Exception {
...
userService.registerNewUser(newUser);
return "redirect:<location>";
}
Here is spring-app-context:
<?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"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
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
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd">
<!-- Scans within the base package of the application for #Components to configure as beans -->
<!-- #Controller, #Service, #Configuration, etc. -->
<context:component-scan base-package="ewarrants.core" />
<tx:annotation-driven transaction-manager="txManager" />
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="<url>"/>
<property name="username" value="<user>"/>
<property name="password" value="<password>"/>
</bean>
<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<context:property-placeholder location="/WEB-INF/config/ewarrants.properties"/>
</beans>
Here is a sample service implementation:
#Named
public class UserService extends Service implements IUserService {
#Inject
private IUserDao userDao;
#Override
#Transactional(propagation=Propagation.REQUIRED, rollbackFor=Exception.class)
public void registerNewUser(User user) throws Exception {
...
// add the user record
int newUserID = userDao.insertUser(user);
// carry out more database inserts
}
}

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.

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

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.

Resources