my dog learned polymorphism*
The moose likes Spring and the fly likes Spring MVC Request Mapping Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Frameworks » Spring
Bookmark "Spring MVC Request Mapping" Watch "Spring MVC Request Mapping" New topic
Author

Spring MVC Request Mapping

Fred Beema
Greenhorn

Joined: Aug 31, 2010
Posts: 3
I am trying to use Spring MVC version 3.0.4 for the first time and I suspect I do not have something configured correctly since I am getting the following error in the log "noHandlerFound No mapping found for HTTP request with URI" following by the URI I am requesting.

my 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"
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">

<display-name>User Test</display-name>
<description>
This application provides both the backend iRemitt services and a web frontend.
</description>

<!-- Location of Spring application context -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/context/iremitt-persistence.xml
</param-value>
</context-param>


<!--
Define a listener so we can put Spring context data in files
other than myusertest-servlet.xml. Without this, the application
files defined above as context parameters would not get loaded.
-->
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>

<!--
Specify the dispatcher servlet, and have it load up the
Spring application context on startup.
-->
<servlet>
<servlet-name>myusertest</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>


<!--
Map uris to the spring servlet defined above. The *.html mapping
is used to deal with the welcome file, index.html, which is mapped
to the welcome controller elsewhere (in the application context).
-->
<servlet-mapping>
<servlet-name>myusertest</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
<servlet-name>myusertest</servlet-name>
<url-pattern>/user/*</url-pattern>
</servlet-mapping>

<servlet-mapping>
<servlet-name>myusertest</servlet-name>
<url-pattern>/search/*</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>myusertest</servlet-name>
<url-pattern>/about/*</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>myusertest</servlet-name>
<url-pattern>/contact/*</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>myusertest</servlet-name>
<url-pattern>/privacy/*</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>myusertest</servlet-name>
<url-pattern>/terms/*</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>myusertest</servlet-name>
<url-pattern>/status/*</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>myusertest</servlet-name>
<url-pattern>/message/*</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>myusertest</servlet-name>
<url-pattern>/find/*</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>myusertest</servlet-name>
<url-pattern>/help/*</url-pattern>
</servlet-mapping>


<!--
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/error/*</url-pattern>
</servlet-mapping>
-->

<!--
Allow logins to persist for eight hours.
-->
<session-config>
<session-timeout>480</session-timeout>
</session-config>

<!--
Specify the "welcome file". This is actually mapped above to
the spring dispatcher servlet, so the actual file doesn't have
to have any content.
-->
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>

</web-app>


------------------------------------------------------------------------
myusertest-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:util="http://www.springframework.org/schema/util"
xmlns:aop="http://www.springframework.org/schema/aop"
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/util
http://www.springframework.org/schema/util/spring-util-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">


<context:component-scan base-package="com.soacom.iremitt"></context:component-scan>
<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
</bean>

<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">

<!-- Set the max upload size to 100k -->
<property name="maxUploadSize" value="500000"/>
</bean>

<!--
Resource Bundles
-->
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename" value="messages"/>
</bean>


<!--
Session Beans
-->
<bean id="userSession"
class="com.soacom.iremitt.session.UserSession" scope="session">
<aop:scoped-proxy/>
</bean>

<!--
Controllers
-->


<!--
This is the way to do it without tiles
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView"
/>
<property name="prefix" value="/WEB-INF/tiles/"/>
</bean>
-->

<!--
Tiles configuration and view resolver
-->
<bean id="tilesConfigurer"
class="org.springframework.web.servlet.view.tiles2.TilesConfigurer">
<property name="definitions">
<list>
<value>/WEB-INF/iremitt-tiles.xml</value>
<value>/WEB-INF/iremitt-tree-tag.tld</value>
</list>
</property>
</bean>

<bean id="resourceBundleViewResolver" class="org.springframework.web.servlet.view.ResourceBundleViewResolver">
<property name="basename" value="views-transfer"/>
<property name="order" value="2"/>
<!--property name="defaultParentView" value="modelView"/-->
</bean>

<bean id="viewResolver"
class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass">
<value>org.springframework.web.servlet.view.tiles2.TilesView</value>
</property>
<property name="order" value="1"/>
</bean>


</beans>

------------------------------------------------------
jsp file

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<%@ taglib uri="http://www.springframework.org/tags" prefix="spring" %>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form" %>

<form:form modelAttribute="userCommand" method="post" action="${pageContext.request.contextPath}/user/create"
enctype="multipart/form-data" >

<!--<form:errors path="*" cssClass="errorblock" element="div"/> -->
<div class="round_Box_Container grid_8">
<div class="grid_2">
<label for="userName">Username:</label>
</div>
<div class="grid_3">
<form:input path="userName"/>
<form:errors path="userName" cssClass="error" element="div"/>
</div>
<div class="clear"> </div>
<div class="grid_2">
<label for="password">Password:</label>
</div>
<div class="grid_3">
<form:password path="password"/>
<form:errors path="password" cssClass="error" element="div"/>
</div>
<div class="clear"> </div>
<div class="grid_2">
<label for="confirmPassword">Confirm Password:</label>

</div>
<div class="grid_3">
<form:password path="confirmPassword"/>
<form:errors path="password" cssClass="error" element="div" />
</div>
<div class="clear"> </div>
<div class="grid_2">
<label for="givenName">First Name:</label>
</div>
<div class="grid_3">
<form:input path="givenName"/>
<form:errors path="givenName" cssClass="error" element="div"/>
</div>
<div class="clear"> </div>
<div class="grid_2">
<label for="surName">Last Name:</label>
</div>
<div class="grid_3">
<form:input path="surName"/>
<form:errors path="surName" cssClass="error" element="div"/>
</div>
<div class="clear"> </div>
<div class="grid_2">
<label for="address">Address:</label>
</div>
<div class="grid_3">
<form:input path="address"/>
<form:errors path="address" cssClass="error" element="div" />
</div>
<div class="clear"> </div>
<div class="grid_2">
<label for="zipCode">Zip Code:</label>
</div>
<div class="grid_3">
<form:input path="zipCode"/>
</div>
<div class="clear"> </div>
<div class="grid_2">
<label for="city">City:</label>
</div>
<div class="grid_3">
<form:input path="city"/>
<form:errors path="city" cssClass="error" element="div" />
</div>
<div class="clear"> </div>
<div class="grid_2">
<label for="state">State:</label>
</div>
<div class="grid_3">
<form:input path="state"/>
</div>
<div class="clear"> </div>
<div class="grid_2">
<label for="countryName">Country:</label>
</div>
<div class="grid_3">
<form:select id="countryName" path="countryName" size="1">
<formption value="NONE" label="Select " />
<formptions items="${countries}" itemValue="countryName" itemLabel="countryName" />
</form:select>
<form:errors path="countryName" cssClass="error" element="div"/>
</div>
<div class="clear"> </div>
<div class="grid_2">
<label for="email">Email Address:</label>
</div>
<div class="grid_3">
<form:input path="email"/>
<form:errors path="email" cssClass="error" element="div"/>
</div>
<div class="clear"> </div>
<div class="grid_2">
<label for="phoneNumber">Phone:</label>
</div>
<div class="grid_3">
<form:input path="phoneNumber"/>
</div>
<div class="clear"> </div>
<div class="grid_2">
<label for="imageFile">Profile Picture:</label>
</div>
<div class="grid_3">
<input type="file" name="imageFile" id="imageFile"/>
</div>
<div class="clear"> </div>
<div class="grid_2"> </div>
<div class="grid_3">
<input type="submit" value="Sign up"/>
</div>
</div>
</form:form>


--------------------------------------------------
controller

package com.soacom.iremitt.controller;

import com.soacom.iremitt.domain.Country;
import com.soacom.iremitt.domain.User;
import com.soacom.iremitt.service.UserRegistrationService;
import com.soacom.iremitt.service.UserRoleService;
import com.soacom.iremitt.session.UserSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.Date;
import java.util.Calendar;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import static com.soacom.iremitt.commons.IremittConstants.ADMIN_ROLE;
import static com.soacom.iremitt.commons.IremittConstants.CUSTOMER_ROLE;


@Controller
@RequestMapping("/user")
public class UserController {

private Logger logger = LoggerFactory.getLogger(getClass());
@Autowired
private UserRegistrationService userService;
@Autowired
private UserSession session;
@Autowired
private UserRoleService userRoleService;

@Autowired
private UserCreateValidator userCreateValidator;


@ModelAttribute("countries")
public Collection<Country> getCountries(){
return userService.getCountries();
}
@ModelAttribute("userCommand")
public UserCommand formBacking() {
UserCommand userCommand = new UserCommand();
userCommand.setRole((session.isLoggedIn()) ? ADMIN_ROLE : CUSTOMER_ROLE);
return userCommand;

}
/**
* Creates a user based on the information on the input form.
*/
@RequestMapping(value = "/create", method = RequestMethod.POST)
public ModelAndView userCreate( @ModelAttribute("userCommand") UserCommand userCommand, BindingResult result,
HttpServletRequest request, HttpServletResponse response) {
userCreateValidator.validate(userCommand, result);
if (result.hasErrors()){
Map<String, Object> model = new HashMap<String, Object>();
model.put("userCommand", userCommand);
return new ModelAndView("userCreate", model);
}

String userName = userCommand.getUserName();
boolean loggedIn = session.isLoggedIn();
if (userService.isUserNameExist(userName)) {
logger.info("User Exist: " + userName);
Map<String, Object> model = new HashMap<String, Object>();
model.put("userCommand", userCommand);
model.put("message", "user exists");
return new ModelAndView("userCreate", model);
}
String roleCode = (loggedIn) ? ADMIN_ROLE : CUSTOMER_ROLE;
User user = new User(userName, userCommand.getEmail(), userCommand.getGivenName(),
userCommand.getSurName(), userCommand.getAddress(), userCommand.getZipCode(), userCommand.getCity(),
userCommand.getState(), userCommand.getCountryName(),userCommand.getPhoneNumber(),
userRoleService.getUserRoleByCode(roleCode),
new Date(Calendar.getInstance().getTimeInMillis()));

MultipartFile multipartFile = userCommand.getImageFile();

try {
// Insert the entry into the database.
Long userId = userService.insertUserWithPassword(user, user.getPassword());
logger.debug("Entry Inserted " + userId);
System.out.println("I'm here");
if (!loggedIn) {
session.setUser(userService.getUserById(userId));
} else {
userId = session.getUser().getId();
}


if (multipartFile != null) {
// TODO Validate image time in validator.
userService.saveImageForUser(user, multipartFile);
userService.updateUser(user);
}

ModelAndView mav = new ModelAndView("redirect:/view");
mav.addObject("id", userId);
return mav;

} catch (Exception e) {
logger.info("Exception: " + e.getMessage(), e);
e.printStackTrace();
// On service error, try again
Map<String, Object> model = new HashMap<String, Object>();
model.put("userCommand", userCommand);
model.put("message", e.getMessage());
return new ModelAndView("userCreate", model);
}
}

/**
* Displays the user central page. Displays interesting information
* regarding users. Output format is specified by the format parameter.
* Occurs on soacom.iremitt.com/user/
*
* @param request
* @param response
* @return
*/

@RequestMapping(value = "/", method = RequestMethod.GET)
public ModelAndView central(HttpServletRequest request,
HttpServletResponse response) {

// Collection<User> mostActive = userService.getMostActiveCustomers();
Collection<User> newest = userService.getMostActiveCustomers();
Integer noc = userService.getCustomerCount();

ModelAndView mav = new ModelAndView("userCentral");
mav.addObject("session", session);
mav.addObject("newest", newest);
mav.addObject("noOfUsers", noc);

return mav;
}

/**
* Displays a given user's profile page. Output format is specified by the
* format parameter. Occurs on soacom.iremitt.com/user/#userId#
*
* @param request
* @param response
* @return
*/
@RequestMapping(value = "/view", method = RequestMethod.GET )
public ModelAndView view(HttpServletRequest request,
HttpServletResponse response) {
UserCommand command = new UserCommand();
Long userId = Long.valueOf(request.getParameter("id"));
User user = userService.getUserById(userId);
String fileSuffix = user.getAvatarFileSuffix();
String fileName;

command.setId(user.getId());
command.setEmail(user.getEmail());
command.setGivenName(user.getGivenName());
command.setSurName(user.getSurName());
command.setCustomer(userService.isCustomer(user));
command.setAdmin(userService.isAdmin(user));
command.setBankAdmin(userService.isBankAdmin(user));
command.setBankRep(userService.isBankRep(user));
command.setBankSuperAdmin(userService.isBankSuperAdmin(user));
command.setSuperAdmin(userService.isSuperAdmin(user));
command.setRecipients(userService.getRecipients(userId));
fileName = "/avatars/user/";
if (fileSuffix != null) {
command.setAvatarFileName(fileName + userId + "." + fileSuffix);
} else {
command.setAvatarFileName(fileName + "default_user.png");
}

// Collection<Currency> currencies = curService.getMajorCurrencies();

ModelAndView mav = new ModelAndView("userViewProfile");
mav.addObject("userCommand", command);
mav.addObject("session", session);
return mav;
}


/**
* Logs out the current user.
*
* @param request
* @param response
* @return
*/
@RequestMapping(value = "/logout" )
public ModelAndView logout(HttpServletRequest request,
HttpServletResponse response) {
session.setUser(null);
return new ModelAndView("redirect:/");
}
/*
/**
* Removes the membership between the given user and recipient.
*
* @param request
* @param response
*/
/*
public void removeRecipient(HttpServletRequest request,
HttpServletResponse response) {
Long userId = Long.valueOf(request.getParameter("userId"));
Long recipId = Long.valueOf(request.getParameter("recipId"));
if (session.isLoggedIn() && session.getUser().getId().equals(userId)) {
Recipient recip = recipientService.getRecipient(recipId);
if (recip.getUser().getId().equals(userId)) {
recipientService.removeRecipient(recip);
}
}
}

*/
public UserSession getSession() {
return session;
}

public void setSession(UserSession session) {
this.session = session;
}
}




Can anyone tell me why I am getting the following error when trying to access this controller
PageNotFound W org.springframework.web.servlet.DispatcherServlet noHandlerFound No mapping found for HTTP request with URI [/myusertest/user/create] in DispatcherServlet with name 'myusertest'

Thanks
Prasad Krishnegowda
Ranch Hand

Joined: Apr 25, 2010
Posts: 507

You are mapping user/* to the spring dispatcher servlet, but where is the mapping for the user/create in the xml file..


Regards, Prasad
SCJP 5 (93%)
Fred Beema
Greenhorn

Joined: Aug 31, 2010
Posts: 3
Prasad Krishnegowda wrote:You are mapping user/* to the spring dispatcher servlet, but where is the mapping for the user/create in the xml file..

Thank you very much. I thought that /user/* will work for all user mapping. That problem is solved but I'm facing with another problem.
The userCreate.jsp form input values are always empty even though the values are entered. Do you know why? What am I doing wrong here.


-----------------------------\
<%@ taglib uri="http://www.springframework.org/tags" prefix="spring" %>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form" %>

<form:form modelAttribute="userCommand" method="post" action="${pageContext.request.contextPath}/user/create"
enctype="multipart/form-data" >

<form:errors path="*" cssClass="errorblock" element="div"/>
<div class="round_Box_Container grid_8">
<div class="grid_2">
<label for="userName">Username:</label>
</div>
<div class="grid_3">
<form:input path="userName"/>
<form:errors path="userName"/>
</div>
<div class="clear"> </div>
<div class="grid_2">
<label for="password">Password:</label>
</div>
<div class="grid_3">
<form:password path="password"/>
<form:errors path="password" cssClass="error" />
</div>
<div class="clear"> </div>
<div class="grid_2">
<label for="confirmPassword">Confirm Password:</label>

</div>
<div class="grid_3">
<form:password path="confirmPassword"/>
<form:errors path="password" cssClass="error" />
</div>
<div class="clear"> </div>
<div class="grid_2">
<label for="givenName">First Name:</label>
</div>
<div class="grid_3">
<form:input path="givenName"/>
<form:errors path="givenName" cssClass="error" />
</div>
<div class="clear"> </div>
<div class="grid_2">
<label for="surName">Last Name:</label>
</div>
<div class="grid_3">
<form:input path="surName"/>
<form:errors path="surName" cssClass="error"/>
</div>
<div class="clear"> </div>
<div class="grid_2">
<label for="address">Address:</label>
</div>
<div class="grid_3">
<form:input path="address"/>
<form:errors path="address" cssClass="error" />
</div>
<div class="clear"> </div>
<div class="grid_2">
<label for="zipCode">Zip Code:</label>
</div>
<div class="grid_3">
<form:input path="zipCode"/>
</div>
<div class="clear"> </div>
<div class="grid_2">
<label for="city">City:</label>
</div>
<div class="grid_3">
<form:input path="city"/>
<form:errors path="city" cssClass="error" />
</div>
<div class="clear"> </div>
<div class="grid_2">
<label for="state">State:</label>
</div>
<div class="grid_3">
<form:input path="state"/>
</div>
<div class="clear"> </div>
<div class="grid_2">
<label for="country">Country:</label>
</div>
<div class="grid_3">
<form:select id="country" path="country" size="1">
<formption value="NONE" label="Select " />
<formptions items="${countries}" itemValue="countryName" itemLabel="countryName" />
</form:select>
<form:errors path="country" cssClass="error" />
</div>
<div class="clear"> </div>
<div class="grid_2">
<label for="email">Email Address:</label>
</div>
<div class="grid_3">
<form:input path="email"/>
<form:errors path="email" cssClass="error" />
</div>
<div class="clear"> </div>
<div class="grid_2">
<label for="phoneNumber">Phone:</label>
</div>
<div class="grid_3">
<form:input path="phoneNumber"/>
</div>
<div class="clear"> </div>
<div class="grid_2">
<label for="imageFile">Profile Picture:</label>
</div>
<div class="grid_3">
<input type="file" name="imageFile" id="imageFile"/>
</div>
<div class="clear"> </div>
<div class="grid_2"> </div>
<div class="grid_3">
<input type="submit" value="Sign up"/>
</div>
</div>
</form:form>
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Spring MVC Request Mapping
 
Similar Threads
Binding problem in JSP with Spring
WARN [org.springframework.web.servlet.PageNotFound]No mapping found for HTTP request, error-code404
Spring exception Neither BindingResult nor plain target object for bean name 'name' a
Problem in using javascript in spring web mvc system:
Javascript new window is not opening from a jsp page