Spring MVC Controller URL not mapped - spring

I am trying to make simple project in Spring MVC,but getting this error :
WARNING: No mapping found for HTTP request with URI [/SpringMVCForm/login.htm] in DispatcherServlet with name 'springform'
HTTP Status 404 - Not Found.
Not able to get what I am missing. Please let me know.
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID" version="4.0">
<display-name>SpringMVCForm</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>springform</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springform</servlet-name>
<url-pattern>*.htm</url-pattern>
</servlet-mapping>
</web-app>
springform-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-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
<context:component-scan base-package="com.mvcform.*" />
<mvc:annotation-driven />
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
</beans>
LoginController.java
package com.mvcform.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
#Controller
#RequestMapping("/login.htm")
public class LoginController {
#RequestMapping(method=RequestMethod.POST)
public ModelAndView processCredentials(#RequestParam("userId") String userId, #RequestParam("password") String password) {
String message = "Invalid Credentials";
if (userId != null && userId.length() >= 5) {
if (userId.equals(password)) {
//message = "Welcome " + userId + " !!!";
return new ModelAndView("redirect:/showform");
}
}
return new ModelAndView("index", "message", message);
}
}
index.jsp:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Spring MVC Form</title>
</head>
<body>
<h1> Index.jsp </h1>
<h1>Enter your user id and password</h1>
<form action="login.htm" method="post">
<table>
<tr>
<td> User Id </td>
<td> <input type="text" name="userId" /></td>
</tr>
<tr>
<td>Password </td>
<td> <input type="password" name="password" /></td>
</tr>
<tr>
<td>
<input type="submit" value="Submit" />
</td>
</tr>
</table>
</form>
</body>
</html>
I think Spring is not able to scan base package: com.mvcform.*
Please let me know what I am missing here.

1) if you configured correct then you must check the json format which you sending to server to save it may be wrong (refere the urlenter link description here)
2) please check your controller controller doesn't have this url "URI [/SpringMVCForm/login.htm]" you have only /login.htm url.

Remove
#RequestMapping("/login.htm")
and keep only
#RequestMapping("/login")
in controller

Related

Issue in Spring page navigation Mapping not found error in logs

I am new to Spring and trying one user registration example using maven with spring mvc.
I am able to lunch my home page but when i click on the login link than getting 404 error page not found.
Below are my application details:-
Web.xml
<web-app id = "WebApp_ID" version = "2.4"
xmlns = "http://java.sun.com/xml/ns/j2ee"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>Archetype Created Web Application</display-name>
<welcome-file-list>
<welcome-file>home.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>spring-mvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring-mvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
DispacterServlet:-
<?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.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<import resource="classpath.*:jbr/config/user-beans.xml" />
<context:component-scan base-package="jbr.springmvc" />
<context:annotation-config />
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
Controller:-
package jbr.springmvc.controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
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.servlet.ModelAndView;
import jbr.springmvc.model.Login;
import jbr.springmvc.model.User;
import jbr.springmvc.service.UserService;
#Controller
public class LoginController {
#Autowired
UserService userService;
#RequestMapping(value = "/login", method = RequestMethod.GET)
public ModelAndView showLogin(HttpServletRequest request, HttpServletResponse response) {
ModelAndView mav = new ModelAndView("login");
mav.addObject("login", new Login());
return mav;
}
#RequestMapping(value = "/loginProcess", method = RequestMethod.POST)
public ModelAndView loginProcess(HttpServletRequest request, HttpServletResponse response,
#ModelAttribute("login") Login login) {
ModelAndView mav = null;
User user = userService.validateUser(login);
if (null != user) {
mav = new ModelAndView("welcome");
mav.addObject("firstname", user.getFirstname());
} else {
mav = new ModelAndView("login");`enter code here`
mav.addObject("message", "Username or Password is wrong!!");
}
return mav;
}
}
Login.jsp
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%# page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1" %>
<!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=ISO-8859-1">
<title>Login</title>
</head>
<body>
<form:form id="loginForm" modelAttribute="login" action="loginProcess" method="post">
<table align="center">
<tr>
<td>
<form:label path="username">Username: </form:label>
</td>
<td>
<form:input path="username" name="username" id="username" />
</td>
</tr>
<tr>
<td>
<form:label path="password">Password:</form:label>
</td>
<td>
<form:password path="password" name="password" id="password" />
</td>
</tr>
<tr>
<td></td>
<td align="left">
<form:button id="login" name="login">Login</form:button>
</td>
</tr>
<tr></tr>
<tr>
<td></td>
<td>Home
</td>
</tr>
</table>
</form:form>
<table align="center">
<tr>
<td style="font-style: italic; color: red;">${message}</td>
</tr>
</table>
</body>
</html>
I have tried so many some but not able to find any solution for this.
Please help me to identify where I am doing wrong.It's my first application in spring so not able to perform any more analysis.
Please guide me with this
You Have specified home.jsp in your welcome file list. I don't see a home.jsp file in your file path. May be that's throwing you 404. You have a login.jsp. Make your controller return "login" from your controller. Either wise works. Since you mentioned as a beginner, you can check here for bootstrapping a basic app.
https://github.com/mrakhunathan/SpringWebSkeleton.git

java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'configbean' available as request attribute

When try to run spring sample application using maven i have got the exception mentioned.
Here is my program
Firstpage1.jsp [present in Webcontent]
<html>
<head>
<title>Finacle data retriever</title>
</head>
<body>
<h2>Enter the configuration details</h2>
<form:form method="POST" action="/formexample/Configgen" commandName="configbean">
<table>
<tr>
<td><form:label path="tnu">Total number of Users</form:label></td>
<td><form:input path="tnu" /></td>
</tr>
<tr>
<td><form:label path="cnu">Concurrent number of Users</form:label></td>
<td><form:input path="cnu" /></td>
</tr>
<tr>
<td><form:label path="kat">Keep Alive Timeout</form:label></td>
<td><form:input path="kat" /></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="Submit" /></td>
</tr>
</table>
</form:form>
</body>
</html>
result.jsp [ Webcontent/WEB-INF/jsp]
<%#taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<html>
<head>
<title>Result page</title>
</head>
<body>
<h2> Result page information</h2>
<table>
<tr>
<td>Total Number of users</td>
<td>${congibean.tnc}</td>
</tr>
<tr>
<td>Concurrent Number of users</td>
<td>${congibean.cnu}</td>
</tr>
<tr>
<td>Keep alive timeout</td>
<td>${congibean.kat}</td>
</tr>
</table>
</body>
</html>
**spring dependencies are present in maven dependencies.**
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_2_5.xsd"
id="WebApp_ID" version="2.5">
<jsp-config>
<taglib>
<taglib-uri>/WEB-INF/spring-form.tld</taglib-uri>
<taglib-location>spring-form.tld</taglib-location>
</taglib>
</jsp-config>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/formex-servlet.xml</param-value>
</context-param>
<welcome-file-list>
<welcome-file>Firstpage1.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>formex</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>formex</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
formex-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"
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.2.xsd">
<context:component-scan base-package="formexamplepack1"></context:component-scan>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>
formexamplepack1 - package
configbean.java
package formexamplepack1;
public class configbean {
private int tuc;
private int cnu;
private int kat;
public int getTuc() {
return tuc;
}
public void setTuc(int tuc) {
this.tuc = tuc;
}
public int getCnu() {
return cnu;
}
public void setCnu(int cnu) {
this.cnu = cnu;
}
public int getKat() {
return kat;
}
public void setKat(int kat) {
this.kat = kat;
}
}
ConfigurationController.java
package formexamplepack1;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
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;
#Controller
#RequestMapping(value = "/Configgen")
public class ConfigurationController {
#RequestMapping(method=RequestMethod.GET)
public String showform(ModelMap model) {
configbean configbean=new configbean();
model.addAttribute("configbean",configbean);
return "Firstpage";
}
#RequestMapping(method=RequestMethod.POST)
public String getdetails(#ModelAttribute("configbean")configbean configbean,ModelMap model,BindingResult bindingResult){
model.addAttribute("tnu", configbean.getTuc());
model.addAttribute("cnu", configbean.getCnu());
model.addAttribute("kat",configbean.getKat());
return "result";
}
}
Help me in resolving the below exception. I have gone through all the answers but not able to figure out. Using java 1.8 and spring jars latest [4.2.6]
tomcat- 7.0.68
Below is the exception
org.apache.jasper.JasperException: java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'configbean' available as request attribute
org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:556)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:472)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:395)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:339)
javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
root cause
java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'configbean' available as request attribute
org.springframework.web.servlet.support.BindStatus.<init>(BindStatus.java:144)
org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getBindStatus(AbstractDataBoundFormElementTag.java:168)
org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getPropertyPath(AbstractDataBoundFormElementTag.java:188)
org.springframework.web.servlet.tags.form.LabelTag.autogenerateFor(LabelTag.java:130)
org.springframework.web.servlet.tags.form.LabelTag.resolveFor(LabelTag.java:120)
org.springframework.web.servlet.tags.form.LabelTag.writeTagContent(LabelTag.java:90)
org.springframework.web.servlet.tags.form.AbstractFormTag.doStartTagInternal(AbstractFormTag.java:84)
org.springframework.web.servlet.tags.RequestContextAwareTag.doStartTag(RequestContextAwareTag.java:80)
org.apache.jsp.Firstpage1_jsp._jspx_meth_form_005flabel_005f0(Firstpage1_jsp.java:216)
org.apache.jsp.Firstpage1_jsp._jspx_meth_form_005fform_005f0(Firstpage1_jsp.java:152)
org.apache.jsp.Firstpage1_jsp._jspService(Firstpage1_jsp.java:105)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:439)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:395)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:339)
javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
Try:
without ModelAttribute annotation
Binding Result direct after the command object
like:
#RequestMapping(method=RequestMethod.POST)
public String getdetails(configbean configbean, BindingResult bindingResult){
model.addAttribute("tnu", configbean.getTuc());
model.addAttribute("cnu", configbean.getCnu());
model.addAttribute("kat",configbean.getKat());
return "result";
}
you are trying to use ${congibean.tnc} in your result.jsp file , but you are not passing it as a model attribute . Instead you are trying to pass "tnu","cnu" and "kat" .
As a result it's giving you a jasper exception , as the compiler is unable to find any model attribute called "configbean" .
To solve this either pass only "configBean" as your model Attribute in the getdetails() method , or change your result.jsp file to use only "${tnc}", "${cnu}" and "${kat}"

Spring MVC - app with no default index page and textfield not showing

All,
A Spring newbie here.
I am trying to build a spring mvc(Sping 4.1.6 release) app. This app does not have a default landing page(like index.jsp, I have removed index.jsp from my app). This app will be called from another app by URL links or directly typing the path. My issue is I am not able to get this working. When I type localhost:8080/app/user.jsp(this is in WEB-INF/jsp folder) or localhost:8080/app/jsp/user.jsp(I would prefer not to use this path though).
Another question: I tweaked the app to have an index.jsp redirecting to user.jsp in the WEB-INF folder(not the WEB-INF/jsp) and the Controller #RequestMapping("/"), the user.jsp loads but the textbox is not displayed.
My web.xml
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>selfsrvc</display-name>
<servlet>
<servlet-name>spring-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring-dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
my spring-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: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">
<context:component-scan base-package="com.company"></context:component-scan>
<mvc:annotation-driven />
<mvc:resources mapping="/**" location="/" />
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name = "prefix" value="/WEB-INF/jsp/" />
<property name = "suffix" value=".jsp" />
</bean>
<bean class="org.springframework.context.support.ResourceBundleMessageSource"
id="messageSource">
<property name="basename" value="messages" />
</bean>
My Controller
#Controller
#RequestMapping("/user.jsp")
public class userController {
#RequestMapping(method = RequestMethod.GET)
public String initForm(Model model){
user user = new user();
model.addAttribute("user", user);
System.out.println("IIIIIIIIInside user Controller");
return "user";
}
}
My jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!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=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form:form method="POST" commandName="user">
<table>
<tr>
<td>Enter your name:</td>
<td><form:input path="user" /></td>
</tr>
<tr>
<td><input type="submit" name="submit" value="Submit"></td>
</tr>
<tr>
</table>
</form:form>
</body>
</html>
I am not sure what I am missing in both the scenarios. Thanks.
EDIT: The suggestion by minion solved my issue. Thanks.
There are couple of issues or changes you need to do. Here is the Gist of the issue :
Your spring servlet is mapped to / and the requested url is of the
pattern *.jsp. So it would never hit the controller that you wrote.
So change your controller to like one below.
#Controller
#RequestMapping("/user")
public class userController {
#RequestMapping(method = RequestMethod.GET)
public String initForm(Model model){
user user = new user();
model.addAttribute("user", user);
System.out.println("IIIIIIIIInside user Controller");
return "user";
}
Use the url localhost:8080/app/jsp/user to hit the controller.
}

Spring MVC, Form Submission not working

Can some one help me with this?
My Controller class looks like this, and i have created the customer model class..
/**
* Handles requests for the application home page.
*/
#Controller
#RequestMapping("/customer")
public class CustomerController {
#RequestMapping(method = RequestMethod.GET)
public ModelAndView student() {
return new ModelAndView("customer", "command", new Customer());
}
#RequestMapping(value = "/addCustomer", method = RequestMethod.POST)
public String addStudent(#ModelAttribute Customer customer,
ModelMap model) {
model.addAttribute("customerName", customer.getCustomerName());
model.addAttribute("emailId", customer.getEmailId());
model.addAttribute("sex", customer.getSex());
return "customerDetails";
}
}
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">
<display-name>Customer Form Handling</display-name>
<!-- 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>Customer</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/Customer/servlet-context.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Customer</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
JSP Pages
customer.jsp
<%#taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<html>
<head>
<title>Customer Form Handling</title>
</head>
<body>
<h2>Customer Information</h2>
<form:form method="POST" commandName = "command" action="/addCustomer">
<table>
<tr>
<td><form:label path="customerName">customerName</form:label></td>
<td><form:input path="customerName" /></td>
</tr>
<tr>
<td><form:label path="emailId">emailId</form:label></td>
<td><form:input path="emailId" /></td>
</tr>
<tr>
<td><form:label path="sex">sex</form:label></td>
<td><form:input path="sex" /></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="Submit"/>
</td>
</tr>
</table>
</form:form>
</body>
</html>
customerDetails.jsp
<%#taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<html>
<head>
<title>Customer Form Handling</title>
</head>
<body>
<h2>Customer Detail Information</h2>
<table>
<tr>
<td>CustomerName</td>
<td>${customerName}</td>
</tr>
<tr>
<td>emailId</td>
<td>${emailId}</td>
</tr>
<tr>
<td>sex</td>
<td>${sex}</td>
</tr>
</table>
</body>
</html>
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 />
<!-- 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.customerinfo.controller" />
</beans:beans>
But when I run this application in Tomcat Server.. The first url points to
localhost:8080/controller/.
If I append localhost:8080/controller/customer I get the first form page..
But once I click on submit.. it says page not found error.
It's a relative path problem. Your form action is /addCustomer (has / prefix), if you resolve it it's http://localhost:8080/addCustomer. What you wanted is probably http://localhost:8080/appname/customer/addCustomer.
In some cases simply changing it into customer/addCustomer might resolve it, but if your page can also be accessed by http://localhost:8080/appname/customer/ (pay attention to the trailing slash) then this could be a problem. The relative path will translate into http://localhost:8080/appname/customer/customer/addCustomer
Of course now you can think to just do /appname/customer/addCustomer and problem solved, but in fact you are now hard-coding the context path name. If one day the context path changes all this code will break.
One approach I like to use so my JSP can figure out the context path is by defining a root variable
<c:set var="root" value="${pageContext.request.contextPath}"/>
...
<form:form action="${root}/customer/addCustomer">
try as
<form:form method="POST" commandName = "command" action="addCustomer">
instead of
<form:form method="POST" commandName = "command" action="/addCustomer">

Spring 3 MVC extra #RequestMapping value getting appended to returned view

I have a view 'hi.jsp' with user name and password text fields. I need to submit 'hi.jsp' to 'LoginController.java'. If there is any error in the data submitted then 'LoginController.java' must redirect the request back to 'hi.jsp' (with text fields retaning the entered data) with respective error messages. After changing data and re-submitting 'hi.jsp' I get 404 error.
So the first submission is successful however problem occurs during second submission.
The source code of files is mentioned below:
hi.jsp
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# taglib uri="http://www.springframework.org/tags/form" prefix="s" %>
<%# page session="false" %>
<html>
<body>
<s:form method="POST" modelAttribute="loginObj" action="login/validatelogin">
<label for="userName">UserName</label>
<s:input path="userName" id="userName" size="15"/><br>
<div style="{color:red}"> <s:errors path="userName"></s:errors></div>
<label for="password">Password</label>
<s:input path="password" id="password" size="15" /><br>
<s:errors path="password"></s:errors>
<input name="submit" type="submit" value="login"/>
</s:form>
</body>
</html>
LoginController.java
package rajeev.spring.spitter.mvc.controller;
import javax.validation.Valid;
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;
#Controller
#RequestMapping("/login")
public class LoginController {
#RequestMapping(value="/validatelogin", method=RequestMethod.POST)
public String validateLogin(#Valid #ModelAttribute("loginObj") LoginBean loginObj, BindingResult bindingResult)
{
System.out.println(bindingResult.hasErrors());
if(bindingResult.hasErrors())
{
return "hi";
}
return "home";
}
}
spitter-servlet.xml (spring configuration)
<?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:jdbc="http://www.springframework.org/schema/jdbc"
xsi:schemaLocation="http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<mvc:annotation-driven/>
<context:component-scan base-package="rajeev.spring.spitter.mvc.controller"></context:component-scan>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</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"
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>Spring Hello World</display-name>
<welcome-file-list>
<welcome-file>/</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>springDispatcher</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spitter-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springDispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
During the second submission of 'hi.jsp' tomcat log also displays a warning:
WARNING: No mapping found for HTTP request with URI [/SpringMVC/login/login/validatelogin] in DispatcherServlet with name 'springDispatcher'
It seems that during second submission of 'hi.jsp' an extra '/login' is getting appended to the submission path of the form.
Kindly suggest if something is wrong with above code or do I need to modify it to make it working.
Thanks for your help.
This is because the relative form post URL changed when you map your handler method into a different URL
<s:form method="POST" modelAttribute="loginObj" action="login/validatelogin">
Common solution to this problem is to use absolute path, but instead of hardcoding, lookup your context-path using
<c:set var="root" value="${pageContext.request.contextPath}"/>
Then on your form
<s:form method="POST" modelAttribute="loginObj" action="${root}/login/validatelogin">
Other option you might consider is to use Post-Redirect pattern in your controller handler method to avoid switching the URL
public String validateLogin(#Valid #ModelAttribute("loginObj") LoginBean loginObj, BindingResult bindingResult) {
....
return "redirect:/login";
}
Try this:
<c:url var="myAction" value="/login/validatelogin"/>
<s:form method="POST" modelAttribute="loginObj" action="${myAction}">

Resources