I created a Spring MVC Project but the errors of form are not displayed .Why?
I try to create a simple form.This is the code of my Project.The project works but in jsp the error are not dispayed..Where did I go wrong?Thanks
Student.java
package coreservlets;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
public class Student {
#Size(min=4,max=5,message="Size wrong")
#NotNull
private String name;
#Size(min=4,max=5,message="Size wrong")
#NotNull
private Integer age;
#Size(min=4,max=5,message="Size wrong")
#NotNull
private Integer id;
public String getName(){return name;}//getName
public void setName(String name){this.name=name;}//setName
public Integer getAge(){return age;}//getAge
public void setAge(Integer age){this.age=age;}//setAge
public Integer getId(){return id;}//getId
public void setId(Integer id){this.id=id;}//setId
}//Student
StudentController.java
package coreservlets;
import javax.validation.Valid;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
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;
#Controller
public class StudentController {
#RequestMapping(value="/",method=RequestMethod.GET)
public ModelAndView student(){
return new ModelAndView("student", "command", new Student());
}//student
#RequestMapping(value="/addStudent", method=RequestMethod.POST)
public String addStudent(#ModelAttribute #Valid Student student,ModelMap model){
model.addAttribute("name",student.getName());
model.addAttribute("age",student.getAge());
model.addAttribute("id",student.getId());
return "result";
}//addStudent
}//StudentController
student.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%#taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<!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>Spring MVC Form Handling</title>
</head>
<body>
<h2>Student Information</h2>
<form:form method="post" action="/SpringMVCFormExample/addStudent" >
<table>
<tr>
<td><form:label path="name">Name</form:label></td>
<td><form:input path="name"/></td>
<form:errors path="name" />
</tr>
<tr>
<td><form:label path="age">Age</form:label></td>
<td><form:input path="age"/></td>
<form:errors path="age" />
</tr>
<tr>
<td><form:label path="id">Id</form:label></td>
<td><form:input path="id"/></td>
<form:errors path="id" />
</tr>
<tr>
<td colspan="2">
<input type="submit" value="Submit"/>
</td>
</tr>
</table>
</form:form>
result.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%#taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Spring MVC Form Handling</title>
</head>
<body>
<h2>Submitted Student Information</h2>
<table>
<tr>
<td>Name</td>
<td>${name}</td>
</tr>
<tr>
<td>Age</td>
<td>${age}</td>
</tr>
<tr>
<td>Id</td>
<td>${id}</td>
</tr>
</table>
</body>
</html>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" 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>Spring MVC Form</display-name>
<servlet>
<servlet-name>SpringMVCForm</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>SpringMVCForm</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
SpringMVCForm-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd">
<context:component-scan base-package="coreservlets" />
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
Use BindingResult class as parameter in your method.
your method should look like this
public String addStudent(#ModelAttribute #Valid Student student,ModelMap model,BindingResult result)
Spring MVC will validate the model object annotated by the #Valid annotation after binding its properties with inputs from JSP form that uses Spring’s form tags. Any constraint violations will be exposed as errors in the BindingResult object, thus we can check the violation in the controller’s method like this:
if (result.hasErrors()) {
// form validation error
} else {
// form input is ok
}
The following code will return the user to the student form when a validation error occurs. When there is no validation error, the result template will be shown
#RequestMapping(value="/addStudent", method=RequestMethod.POST)
public String addStudent(#Valid Student student, BindingResult errors, Model model){
if (errors.hasErrors()) {
return "student";
}
model.addAttribute("name",student.getName());
model.addAttribute("age",student.getAge());
model.addAttribute("id",student.getId());
return "result";
}
You need to make sure that BindingResult errors is positioned exactly after #ModelAttribute #Valid Student student
Check out this and this tutorial for more info.
On another note, you should probably be redirecting the user after a successful POST. See this for more details
If you set the validation at model level you should use BindingResult:
#RequestMapping(value="/addStudent", method=RequestMethod.POST)
public String addStudent(#ModelAttribute #Valid Student student,ModelMap model,BindingResult errors){
if (errors.hasErrors()) {
List<FieldError> lerr = errors.getFieldErrors();
for (FieldError err: lerr) {
// manage the errorrs
}
}
model.addAttribute("name",student.getName());
model.addAttribute("age",student.getAge());
model.addAttribute("id",student.getId());
return "result";
}
if you want to handle validation at client level you can jquery.validate.js.
Related
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
I am a beginner and trying to run simple code and I encounter the warning No mapping found for HTTP request with URI [/Project_Tracker/] in DispatcherServlet with name 'spring
Any help would be great! Thanks!!!
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>Project Tracker</display-name>
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet- class>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
spring-dispatcher.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.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<context:component-scan base-package="com.projecttrack" />
<mvc:annotation-driven/>
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
</beans>
AnnotationController.java
package com.projecttracker.controllers;
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
public class AnnotationController {
#RequestMapping(value="/LoginPage.html", method=RequestMethod.GET)
public ModelAndView getLoginRequest(){
ModelAndView model=new ModelAndView("LoginPage");
model.addObject("projectTitle","Project Track");
return model;
}
#RequestMapping(value="/LoginSuccess.html", method=RequestMethod.POST)
public ModelAndView getLoginResponse(#RequestParam("userName") String name,
#RequestParam("passWord") String password){
UserInfo userinfo1=new UserInfo();
userinfo1.setuserName(name);
userinfo1.setpassWord(password);
ModelAndView model=new ModelAndView("LoginSuccess");
model.addObject("userinfo1",userinfo1);
return model;
}
}
UserInfo.java (POJO class)
package com.projecttracker.controllers;
public class UserInfo {
private String userName;
private String passWord;
public String getuserName(){
return userName;
}
public void setuserName(String name){
userName=name;
}
public String getpassWord(){
return passWord;
}
public void setpassWord(String password){
passWord=password;
}
}
LoginPage.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>
<h2>${projectTitle}</h2>
<body>
<form action="/ProjectTrack/LoginSuccess.html" method="post">
<fieldset>
<h3>Sign In</h3>
User name:
<input type="text" name="userName"><br><br>
Password:
<input type="text" name="passWord"><br><br>
<input type="submit" value="Login"><br><br>
</fieldset>
</form>
</body>
</html>
LoginSuccess.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>Project Track</title>
</head>
<body>
<br>
${userinfo1.userName}<br>
${userinfo1.passWord}<br>
</body>
</html>
You can add / to
#RequestMapping(value="/LoginPage.html", method=RequestMethod.GET) like:
#RequestMapping(value= {"/", "/LoginPage.html"), method=RequestMethod.GET)
Or you can create a index page or welcome page in root path. What you met is just there is not a controller method which is mapped to /.
I am very much new to developing java applications using Spring framework. I have previously developed applications using MVC architecture but this Spring is really killing me.
I mean I can't a get a single new thing right in less than hour. Anyway, I am stuck in a very common problem while handling forms. I have tried for hours, searched the web for my problem and none of them have worked. Is it something to do with Netbeans? I don't know.
index.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<form:form action="apptest.htm" commandName="userForm" method="POST">
Name:<form:input path="name" />
<br>
Age:<form:input path="age" />
<br>
City:<form:input path="city" />
<br>
<input type="submit" value="Submit">
<br>
</form:form>
</body>
</html>
InsertController.java
package SpringApp.Controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.portlet.ModelAndView;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import SpringApp.DAO.PeopleDAO;
import SpringApp.DAO.People;
import java.util.Map;
import org.springframework.web.bind.annotation.ModelAttribute;
#Controller
#RequestMapping("/apptest.htm")
/**
*
* #author ROHAN
*/
public class InsertController {
#RequestMapping(method = RequestMethod.GET)
public String viewRegistration(Map<String, Object> model) {
People userForm = new People();
model.put("userForm", userForm);
return "index";
}
#RequestMapping(method = RequestMethod.POST)
/*public String insertion(ModelMap modelMap) {
ApplicationContext ctx=new ClassPathXmlApplicationContext("Beans.xml");
PeopleDAO dao=(PeopleDAO)ctx.getBean("people");
int status=dao.saveEmployee(new People("Kitty",22,"khardah"));
modelMap.put("msg2","success");
return "test";
}*/
public String processRegistration(#ModelAttribute(value="userForm") People people,
Map<String, Object> model) {
model.put("name",people.getName());
model.put("city",people.getCity());
return "test";
}
}
People.java (Bean class)
package SpringApp.DAO;
public class People {
private int id;
private String name;
private int age;
private String city;
public People()
{
super();
}
public People(String name,int age,String city)
{
this.name=name;
this.age=age;
this.city=city;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
#Override
public String toString() {
return "User [name=" + name + ", age=" + age+ ", city=" + city + "]";
}
}
dispatcher-servlet.xml
<?xml version='1.0' encoding='UTF-8' ?>
<!-- was: <?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:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-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">
<bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping"/>
<context:annotation-config />
<context:component-scan base-package="SpringApp" />
<mvc:annotation-driven />
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/WEB-INF/jsp/"
p:suffix=".jsp" />
</beans>
index.jsp is my welcome page as configured in web.xml. Whenever I run the project, I get the following message:
29-Feb-2016 02:46:14.550 SEVERE [http-nio-8035-exec-183] org.apache.catalina.core.StandardWrapperValve.invoke Servlet.service() for servlet [jsp] in context with path [/SpringApp] threw exception [An exception occurred processing JSP page /index.jsp at line 17
14: </head>
15: <body>
16: <form:form action="apptest.htm" commandName="userForm" method="POST">
17: Name:<form:input path="name" />
18: <br>
19: Age:<form:input path="age" />
20: <br>
Stacktrace:] with root cause
java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'userForm' available as request attribute
at org.springframework.web.servlet.support.BindStatus.<init>(BindStatus.java:141)
at org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getBindStatus(AbstractDataBoundFormElementTag.java:168)
at org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getPropertyPath(AbstractDataBoundFormElementTag.java:188)
at org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getName(AbstractDataBoundFormElementTag.java:154)
at org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.autogenerateId(AbstractDataBoundFormElementTag.java:141)
at org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.resolveId(AbstractDataBoundFormElementTag.java:132)
at org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.writeDefaultAttributes(AbstractDataBoundFormElementTag.java:116)
at org.springframework.web.servlet.tags.form.AbstractHtmlElementTag.writeDefaultAttributes(AbstractHtmlElementTag.java:422)
at org.springframework.web.servlet.tags.form.InputTag.writeTagContent(InputTag.java:142)
at org.springframework.web.servlet.tags.form.AbstractFormTag.doStartTagInternal(AbstractFormTag.java:84)
at org.springframework.web.servlet.tags.RequestContextAwareTag.doStartTag(RequestContextAwareTag.java:80)
at org.apache.jsp.index_jsp._jspx_meth_form_005finput_005f0(index_jsp.java:228)
at org.apache.jsp.index_jsp._jspx_meth_form_005fform_005f0(index_jsp.java:180)
at org.apache.jsp.index_jsp._jspService(index_jsp.java:134)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:438)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:396)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:340)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:217)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:518)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1091)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:673)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1500)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1456)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
My project structure is as follows:
Web pages
META-INF
WEB-INF
jsp
test.jsp
dispatcher-servlet.xml
applicationContext.xml
web.xml
index.jsp(outside WEB-INF)
Source Packages
Beans.xml
SpringApp.Controllers
InsertController
SpringApp.DAO
People.java
PeopleDAO.java
test.jsp
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
Name: ${userForm.name} <br>
City: ${userForm.city}
</body>
</html>
java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'userForm' available as request attribute
As you can see from stacktrace index.jsp can't map model attribute to form parameters.
This happans because you have index.jsp in your <welcome-file-list>. So index.jsp is loaded before controller and don't have access to model values.
To solve this problem you have to:
move your index.jsp file to WEB-INF/jsp folder;
change <welcome-file-list> to this:
<welcome-file-list>
<welcome-file></welcome-file>
</welcome-file-list>
or delete this tag at all.
add "/" to #RequestMapping in InsertController class.
So, now your controller will process request, add value to model and pass it to index.jsp.
Below I posted full code.
InsertController
import SpringApp.DAO.People;
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 java.util.Map;
#Controller
#RequestMapping({"/", "/apptest.htm"})
/**
*
* #author ROHAN
*/
public class InsertController {
#RequestMapping(method = RequestMethod.GET)
public String viewRegistration(Map<String, Object> model) {
People userForm = new People();
model.put("userForm", userForm);
return "index";
}
#RequestMapping(method = RequestMethod.POST)
public String processRegistration(#ModelAttribute(value="userForm") People people,
Map<String, Object> model) {
model.put("name",people.getName());
model.put("city",people.getCity());
return "test";
}
}
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>Spring MVC</display-name>
<description>Spring MVC</description>
<!-- For web context -->
<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>/</url-pattern>
</servlet-mapping>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
WEB-INF/application-context.xml
</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!--<welcome-file-list>-->
<!--<welcome-file></welcome-file>-->
<!--</welcome-file-list>-->
</web-app>
it looks like your model attribute is not bind with request, make below change in your index.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<form:form action="apptest.htm" modelAttribute="userForm" method="POST">
Name:<form:input path="name" />
<br>
Age:<form:input path="age" />
<br>
City:<form:input path="city" />
<br>
<input type="submit" value="Submit">
<br>
</form:form>
</body>
</html>
Now be sure that you have a test.jsp having modelAttribute of People bean otherwise it will again cause of error.
I'm new to Spring.I have made an application named "BookWorkshop" using spring-3.1 by following MVC architecture.but as soon as I'm hitting the
url:http://localhost:8087/BookWorkshop I'm getting the error as follows:
org.springframework.beans.TypeMismatchException: Failed to convert property value of type 'java.lang.String' to required type 'java.lang.Class' for property 'commandClass'.
I'm attaching my code herewith::
Spring servlet class:bookdispatcher-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:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xs">
<bean name="/welcome_book.html" class="com.edifixio.controller.UserBookController"/>
<bean name="/new_book.html" class="com.edifixio.controller.StoreBookController">
<property name="commandClass" value="com.edifixio.model.UserBook"/>
<property name="formView" value="addnewbook"/>
<property name="successView" value="/welcome_book.html"/>
</bean>
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:viewClass="org.springframework.web.servlet.view.JstlView"
p:prefix="/WEB-INF/pages/"
p:suffix=".jsp"/>
</beans>
Form controller class:::StoreBookController.java as follows
public class StoreBookController extends SimpleFormController {
#Override
protected Object formBackingObject(HttpServletRequest request) throws Exception {
UserBook book = new UserBook(0,"Enter Book Name", null, 0);
return book;
}
#Override
protected Map referenceData(HttpServletRequest request) throws Exception {
Map<Object, Object> dataMap = new HashMap<Object, Object>();
PublisherManager manager = new PublisherManager();
dataMap.put("publishierList", manager.getPublishierList());
return dataMap;
}
#Override
protected void initBinder(HttpServletRequest request, ServletRequestDataBinder dataBinder) throws Exception {
dataBinder.setDisallowedFields(new String[]{"publishier"});
UserBook userBook = (UserBook) dataBinder.getTarget();
PublisherManager manager = new PublisherManager();
Long publishierid = null;
try {
publishierid = Long.parseLong(request.getParameter("publishier"));
} catch (Exception e) {
}
if (publishierid != null) {
userBook.setPublisher(manager.getPublishierById(publishierid));
}
}
#Override
public ModelAndView onSubmit(Object command) throws ServletException {
BookManager bookManager = new BookManager();
bookManager.createBook((UserBook) command);
return new ModelAndView(new RedirectView(getSuccessView()));
}
}
then my formView page named:::addnewbook.jsp as follows---
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%#taglib prefix="sp" uri="http://www.springframework.org/tags/form"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h1>ADD BOOK</h1>
<sp:form method="post">
Publisher:<sp:select path="publisher">
<sp:options items="${publisherList}" itemLabel="publishername" itemValue="publisherid"/>
</sp:select>
<br/><br/>
Book Name:<sp:input path="bookname"/>
<br/><br/>
Price:<sp:input path="price"/>
<br/><br/>
<input type="submit" value="SAVE"/>
</sp:form>
</body>
</html>
finally successView controller class named:UserBookController.java as follows
public class UserBookController implements Controller {
#Override
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
BookManager manager = new BookManager();
ModelAndView modelAndView = new ModelAndView("booklist");
modelAndView.addObject("allbook", manager.createBookCollection());
return modelAndView;
}
}
successView page named:booklist.jsp as follows:::
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h1>BOOK WORKSHOP APPLICATION</h1>
<table style="border:2;color:graytext" >
<th style="color: background;alignment-adjust: baseline">Book Name</th>
<th style="color: background">Price</th>
<th style="color: background">Publisher</th>
<c:forEach items="${allbook}" var="b">
<tr>
<td style="color:burlywood">${b.bookname}</td>
<td style="color:burlywood">${b.price}</td>
<td style="color:burlywood">${b.publisher.publishername}</td>
</tr>
</c:forEach>
</table>
</body>
</html>
finally web.xml file is here:::::::
<?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">
<welcome-file-list>
<welcome-file>/new_book.html</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>bookdispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>bookdispatcher</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
</web-app>
can anyone give any solution to this?????????????
Try this:
<property name="commandClass">
<value>
com.edifixio.model.UserBook
</value>
</property>
you can download a fully working spring mvc form based example from here . You can then modify that example in whatever way you want.
I am trying some samples in spring mvc.I have three classes Student.java and StudentController.java as follows
Student.java
package mvc1;
public class Student {
private Integer age;
private String name;
private Integer id;
public void setAge(Integer age) {
this.age = age;
}
public Integer getAge() {
return age;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getId() {
return id;
}
}
StudentController.java
package mvc1;
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 org.springframework.ui.ModelMap;
#Controller
#RequestMapping("login.do")
public class StudentController {
#RequestMapping(value = "/student", method = RequestMethod.GET)
public ModelAndView student() {
return new ModelAndView("student", "command", new Student());
}
#RequestMapping(value = "/addStudent", method = RequestMethod.POST)
public String addStudent(#ModelAttribute("SpringWeb")Student student,
ModelMap model) {
model.addAttribute("name", student.getName());
model.addAttribute("age", student.getAge());
model.addAttribute("id", student.getId());
return "result";
}
}
I have a servlet xml file as HelloWeb-Servlet.xml which is as follow
<?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">
<context:component-scan base-package="Servee" />
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
and the web.xml file as follows...
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/DispatcherServlet.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-
class>
</listener>
<servlet>
<servlet-name>HelloWeb</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>HelloWeb</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
and the student.jsp and result.jsp files are stored in mvc11 package
student.jsp
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h2>Student Information</h2>
<form:form method="POST" action="/Spring/mvc1/addStudent">
<table>
<tr>
<td><form:label path="name">Name</form:label></td>
<td><form:input path="name" /></td>
</tr>
<tr>
<td><form:label path="age">Age</form:label></td>
<td><form:input path="age" /></td>
</tr>
<tr>
<td><form:label path="id">id</form:label></td>
<td><form:input path="id" /></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="Submit"/>
</td>
</tr>
</table>
</form:form>
</body>
</html>
result.jsp
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h2>Submitted Student Information</h2>
<table>
<tr>
<td>Name</td>
<td>${name}</td>
</tr>
<tr>
<td>Age</td>
<td>${age}</td>
</tr>
<tr>
<td>ID</td>
<td>${id}</td>
</tr>
</table>
</body>
</html>
When running the spring program i am getting the warning message as follows
log4j:WARN No appenders could be found for logger (org.springframework.web.context.ContextLoader).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
and the error message as
The requested resource (/Spring/mvc11/student.jsp) is not available.
the HelloWeb-Servlet.xml is stored under WEB-INF.I have referred a lot of source but couldnt fix it.Can someone help me with it...
Looks like there are multiple problems
The package mvc1 is not added to component-scan.
solution: Add the following line to HelloWeb-Servlet.xml
#RequestMapping("login.do") annotation in StudentController does not make any sense, remove it
You have a mapping for the url /student, but is trying to access /Spring/mvc11/student.jsp, either change the RequestMapping or the requested url