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.
Related
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.
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.
}
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.
I'm trying to create a simple Spring 3 application and have the following files. Please tell me the reason for this error
Below is my 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_3_0.xsd"
id="WebApp_ID" version="3.0">
<display-name>Spring2</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>0</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
Below is my index.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%# taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<!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>
Index Page<br/>
<form:form commandName="loginBean" method="POST" action="login">
<form:input path="userName" id="userName"/><br/>
<form:input path="password" id="password"/><br/>
<input type="submit" value="submit"/>
</form:form>
Go to Registration Page
</body>
</html>
Below is my dispatcher-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/" />
<property name="suffix" value=".jsp" />
</bean>
<bean name="/login" class="com.infy.controller.LoginController"/>
</beans>
This is the LoginController.java
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;
#Controller
public class LoginController {
#RequestMapping(value="/login", method=RequestMethod.POST)
public ModelAndView loginAction(#ModelAttribute("loginBean")LoginBean bean){
return new ModelAndView("success", "success", "Successful Login");
}
}
And finally my LoginBean
public class LoginBean {
private String userName;
private String password;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
You'll have to have a ContextLoaderListener in your web.xml - It loads your configuration files.
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
You need to understand the difference between Web application context and root application context .
In the web MVC framework, each DispatcherServlet has its own WebApplicationContext, which
inherits all the beans already defined in the root WebApplicationContext. These inherited
beans defined can be overridden in the servlet-specific scope, and new scope-specific
beans can be defined local to a given servlet instance.
The dispatcher servlet's application context is a web application context which is only applicable for the Web classes . You cannot use these for your middle tier layers . These need a global app context using ContextLoaderListener .
Read the spring reference here for spring mvc .
And if you would like to use an existing context, rather than a new context which would be loaded from xml configuration by org.springframework.web.context.ContextLoaderListener,
then see -> https://stackoverflow.com/a/40694787/3004747