JSP using Hibernate and Spring MVC - spring

Good day!
When i deploy war to tomcat it drop to me this exception:
May be someone can help solve that problem with #Transactional annotation, cannot solve that problem in above 2 weeks :(
n22-Feb-2018 14:52:54.125 SEVERE [http-nio-8080-exec-11] org.apache.catalina.core.StandardWrapperValve.invoke Servlet.service() for servlet [dispatcher] in context with path [/page] threw exception [Request processing failed; nested exception is java.lang.NullPointerException] with root cause
java.lang.NullPointerException
at com.mycompany.app.controller.TypeController.listAll(TypeController.java:24)
at sun.reflect.GeneratedMethodAccessor55.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:209)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:102)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:871)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:777)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:991)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:925)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:978)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:870)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:635)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:855)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:650)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:803)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:790)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1459)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:748)
web.xml
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/mvc-dispatcher-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
mvc-dispatcher-servlet.xml
<context:component-scan base-package="com.mycompany.app" />
<context:component-scan base-package="com.mycompany.app.controller" />
<context:component-scan base-package="com.mycompany.app.service" />
<mvc:annotation-driven />
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/views/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
TypeController.java
#Controller
public class TypeController {
private TypeServiceImpl typeService;
#RequestMapping(value = "/main")
public String listAll(Map<String, Object> map) {
map.put("type", new Type());
map.put("typeList", typeService.listAll());
return "index";
}
#RequestMapping("/")
public String home() {
return "redirect:/main";
}
#RequestMapping(value = "/add", method = RequestMethod.POST)
public String add(#ModelAttribute("type") Type type, BindingResult bindingResult) {
typeService.add(type);
return "redirect:/main";
}
#RequestMapping(value = "/delete/{id}")
public String deleteType(#PathVariable("id") Integer id) {
typeService.delete(id);
return "redirect:/main";
}
}
TypeServiceImpl.java
Dont using DAO
#Service
public class TypeServiceImpl implements TypeService {
private SessionFactory sessionFactory;
#Override
#Transactional
public void add(Type type) {
sessionFactory.getCurrentSession().save(type);
}
#Override
#Transactional
#SuppressWarnings("unchecked")
public List<Type> listAll() {
return sessionFactory.getCurrentSession().createQuery("from Type").list();
}
#Override
#Transactional
public void delete(Integer id) {
Type type = sessionFactory.getCurrentSession().load(Type.class, id);
if (type != null) {
sessionFactory.getCurrentSession().delete(type);
}
}
}
Type.java
#Entity
#Table(name = "type")
public class Type {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "id_type")
private Integer id_type;
#Column(name = "type_name")
private String type_name;
// Communication with Event
#OneToMany(fetch = FetchType.LAZY, mappedBy = "type")
private List<Event> event;
public Type() {
}
public Type(Integer id_type, String type_name) {
this.id_type = id_type;
this.type_name = type_name;
}
//Default getters and setters
}
index.jsp
<%#taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%#taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%#taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%# page contentType="text/html;charset=UTF-8" language="java"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Hello World Page</title>
</head>
<body>
<form:form method="post" action="add" modelAttribute="type">
<table>
<tr>
<td><form:label path=id_type>Type's ID</form:label></td>
<td><form:input path="id_type" /></td>
</tr>
<tr>
<td><form:label path=type_name>Type name</form:label></td>
<td><form:input path="type_name" /></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="Submit" /></td>
</tr>
</table>
</form:form>
<h3>Types</h3>
<c:if test="${!empty typeList}">
<table class="data">
<tr>
<th>Type ID</th>
<th>Type Name</th>
<th> </th>
</tr>
<c:forEach items="${typeList}" var="type">
<tr>
<td>${type.id_type}}</td>
<td>${type.type_name}</td>
<td>Delete</td>
</tr>
</c:forEach>
</table>
</c:if>
</body>
Thanks for watching!!!

I think you might be missing an #Autowired annotation for your service.
#Autowired
private TypeService typeService;
At the moment i can't see where your instantiating the service class.

Related

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 using Netbeans-Neither BindingResult nor plain target object for bean name Netbeans

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.

Unable to do form validation in spring

I am trying to do validation in spring mvc. I have added the hibernate-validator-4.0.2.GA. jar and validation-api-1.0.0GA.jar but i am getting exception
java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'contact' available as request attribute
org.springframework.web.servlet.support.BindStatus.<init>(BindStatus.java:141)
org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getBindStatus(AbstractDataBoundFormElementTag.java:174)
org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getPropertyPath(AbstractDataBoundFormElementTag.java:194)
org.springframework.web.servlet.tags.form.LabelTag.autogenerateFor(LabelTag.java:129)
org.springframework.web.servlet.tags.form.LabelTag.resolveFor(LabelTag.java:119)
org.springframework.web.servlet.tags.form.LabelTag.writeTagContent(LabelTag.java:89)
org.springframework.web.servlet.tags.form.AbstractFormTag.doStartTagInternal(AbstractFormTag.java:102)
org.springframework.web.servlet.tags.RequestContextAwareTag.doStartTag(RequestContextAwareTag.java:79)
org.apache.jsp.WEB_002dINF.jsp.contact_jsp._jspx_meth_form_005flabel_005f0(contact_jsp.java:250)
org.apache.jsp.WEB_002dINF.jsp.contact_jsp._jspService(contact_jsp.java:103)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:432)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
org.springframework.web.servlet.view.InternalResourceView.renderMergedOutputModel(InternalResourceView.java:238)
org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:250)
org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1060)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:798)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:716)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:647)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:552)
javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
org.apache.jasper.runtime.PageContextImpl.doForward(PageContextImpl.java:745)
org.apache.jasper.runtime.PageContextImpl.forward(PageContextImpl.java:716)
org.apache.jsp.index_jsp._jspService(index_jsp.java:71)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:432)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
Contact.jsp
<form:form method="get" action="addContact.html" modelAttribute="contact">
<table>
<tr>
<td><form:label path="firstname">First Name</form:label></td>
<td><form:input path="firstname" /></td>
<form:errors path="firstname"></form:errors>
</tr>
<tr>
<td><form:label path="lastname">Last Name</form:label></td>
<td><form:input path="lastname" /></td>
<form:errors path="lastname"></form:errors>
</tr>
<tr>
<td><form:label path="email">Email</form:label></td>
<td><form:input path="email" /></td>
<form:errors path="email"></form:errors>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="Add Contact"/>
</td>
</tr>
</table>
Contact.java
public class Contact {
#NotEmpty
private String firstname = null;
#NotEmpty
private String lastname = null;
#NotEmpty
private String email=null;
/*#NotEmpty
#Min(1)
#Max(110)
private int telephone*/;
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
ContactController.java
#Controller
#SessionAttributes
public class ContactController {
#RequestMapping(value = "/addContact", method = RequestMethod.GET)
public String addContact( #Valid #ModelAttribute("contact")
Contact contact, BindingResult
result,ModelMap model){
model.addAttribute("contact", new Contact());
if(result.hasErrors()) {
System.out.println("Hiii i am validator");
return "contact";
}
model.addAttribute("message", "Successfully saved person: " + contact.toString());
model.addAttribute("name",contact.getFirstname());
model.addAttribute("surname",contact.getLastname());
// model.addAttribute("age",contact.getTelephone());
model.addAttribute("email",contact.getEmail());
System.out.println("First Name:" + contact.getFirstname() +
"Last Name:" + contact.getLastname());
return "result";
}
#RequestMapping("/contacts")
public ModelAndView showContacts() {
return new ModelAndView("contact", "command", new Contact());
}
}
web.xml
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
spring-servlet.xml
<context:component-scan base-package="com.demo.Controller" />
<mvc:annotation-driven />
<context:annotation-config />
<bean id="viewResolver"
class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="/WEB-INF/messages" />
</bean>
I have also tried using commandName instead of modelattribute but still i get the same exception and also tried using both get and post methods.
1 - Create a new Contact instance before loading your Contact.jsp
#RequestMapping("/contacts")
public ModelAndView showContacts() {
ModelAndView m = new ModelAndView("contact");
m.add("contact", new Contact());
return m;
}
2 - Ensure you are invoking the right servlet path :
#RequestMapping(value = "/addContact", method = RequestMethod.GET)
and change it in you form's header:
<form:form method="get" action="addContact" modelAttribute="contact">
Some further information about this error here
I already had this error before and the problem was that I didn't put a simple domain object like your "Contact" in tha Model, while my Spring form was waiting a domain object.
Try to do something like :
model.addAttribute("contact", new contact());
And that should work.

Request processing failed; nested exception is java.lang.NullPointerException

i created a form and on post i want to save those values to the database and show the saved values on the page.
i am new to spring mvc and hence i am not understanding where i am going wrong.
Here is the StackTrace -
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.NullPointerException
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:894)
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:789)
javax.servlet.http.HttpServlet.service(HttpServlet.java:641)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
root cause
java.lang.NullPointerException
com.projects.data.HomeController.addCustomer(HomeController.java:36)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:601)
org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:176)
org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:436)
org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:424)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:923)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:852)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:882)
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:789)
javax.servlet.http.HttpServlet.service(HttpServlet.java:641)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
note The full stack trace of the root cause is available in the VMware vFabric tc Runtime 2.7.2.RELEASE/7.0.30.A.RELEASE logs.
Model class
package com.projects.model;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="customer")
public class Customer {
#Id
int custid;
String name;
int age;
public Customer()
{}
public Customer(int custid,String name,int age)
{
this.custid=custid;
this.name=name;
this.age=age;
}
//Getters And Setters
public int getCustid() {
return custid;
}
public void setCustid(int custid) {
this.custid = custid;
}
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;
}
}
Dao Class
package com.projects.model;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.projects.model.Customer;
#Repository
public class CustomerDao {
#Autowired
private SessionFactory sessionfactory;
public SessionFactory getSessionfactory() {
return sessionfactory;
}
public void setSessionfactory(SessionFactory sessionfactory) {
this.sessionfactory = sessionfactory;
}
public int save(Customer customer)
{
return (Integer) sessionfactory.getCurrentSession().save(customer);
}
}
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.projects.model" />
<beans:bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<beans:property name="driverClassName" value="com.mysql.jdbc.Driver" />
<beans:property name="url" value="jdbc:mysql://localhost:3306/customerdb" />
<beans:property name="username" value="root" />
<beans:property name="password" value="root" />
</beans:bean>
<beans:bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<beans:property name="dataSource" ref="dataSource" />
<beans:property name="packagesToScan" value="com.projects.model" />
<beans:property name="hibernateProperties">
<beans:props>
<beans:prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</beans:prop>
<beans:prop key="hibernate.show_sql">true</beans:prop>
</beans:props>
</beans:property>
</beans:bean>
<beans:bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<beans:property name="sessionFactory" ref="sessionFactory" />
</beans:bean>
</beans:beans>
Controller class
package com.projects.model;
import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
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;
import com.projects.model.CustomerDao;
import com.projects.model.Customer;
/**
* Handles requests for the application home page.
*/
#Controller
public class HomeController {
private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
/**
* Simply selects the home view to render by returning its name.
*/
private CustomerDao dao;
#RequestMapping(value = "/", method = RequestMethod.GET)
public String customer(Locale locale, Model model) {
logger.info("Welcome home! The client locale is {}.", locale);
Customer customer=new Customer();
model.addAttribute(customer);
return "home";
}
#RequestMapping(value = "/customer", method = RequestMethod.POST)
public String addCustomer(#ModelAttribute("customer") Customer customer, ModelMap model) {
model.addAttribute("custid", customer.getCustid());
model.addAttribute("name",customer.getName());
model.addAttribute("age", customer.getAge());
dao.save(customer);
return "customer/customer";
}
}
View Files
//home.jsp
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%# page session="false" %>
<html>
<head>
<title>Home</title>
</head>
<body>
<form:form action="${customer}" method="post" modelAttribute="customer">
<form:label path="custid">Id:</form:label>
<form:input path="custId"/> <br>
<form:label path="name">Name:</form:label>
<form:input path="name"/> <br>
<form:label path="age">Age:</form:label>
<form:input path="age"/> <br>
<input type="submit" value="Save"/>
//customer.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>Submitted Information</title>
</head>
<body>
<h2>Submitted Information</h2>
<table>
<tr>
<td>Cust id</td>
<td>${custid}</td>
</tr>
<tr>
<td>Name</td>
<td>${name}</td>
</tr>
<tr>
<td>Age</td>
<td>${age}</td>
</tr>
</table>
</body>
</html>
After i click the save button i get the above mentioned error.Please help me resolve this.
Seems to be a problem in your form. At least, the inputs must be given the name attributes:
<form method="post" action="<c:url value='/customer/'/>">
Cust_Id :
<input type="text" name="custid">
<br>
Name :
<input type="text" name="name">
<br>
Age :
<input type="text" name="age">
<input type="submit" value="Save">
</form>
But since you are using Spring, it is preferable to use the Spring forms (and spring url's also):
<spring:url var="customer" value="/customer"/>
<form:form action="${customer}" method="post" modelAttribute="customer">
<form:label path="custid">Id:</form:label>
<form:input path="custId"/> <br>
<form:label path="name">Name:</form:label>
<form:input path="name"/> <br>
<form:label path="age">Age:</form:label>
<form:input path="age"/> <br>
<input type="submit" value="Save"/>
</form:form>
Edit
And you should initialize dao!
#Autowired
private CustomerDao dao;
The attribute of your model has annotated with #ModelAttribute to be nulleable. This is so that when an exception occurs in times of bind there is something to return.
Note the difference between the model attribute and the model attribute parameter.
An exception during bind and validation times could be passing text in an integer field.
Exception:
org.springframework.web.util.NestedServletException:
Request processing failed; nested exception is java.lang.NullPointerException:
Parameter specified as non-null is null: method yourMethod, parameter yourParam
In Kotlin
Going from student: Student to student: Student? exception is avoided.
#RequestMapping("/processFormRegister")
fun processFormRegister(
#Valid #ModelAttribute("firstStudent") student: Student?,
validationResult: BindingResult
): String {
return if (validationResult.hasErrors()) {
"StudentFormRegister"
} else {
"ResultFormRegister"
}
}
And also to see the exception transformed into a validation you could use #Valid and Binding Result of Hibernate Validator obtaining:
failed to convert value of type java.lang.string[] to required type java.lang.integer; nested exception is java.lang.numberformatexception: for input string: "a"
GL

No appenders could be found for the logger

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

Resources