I created simple add entity form called addContact.jsp
<%#taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<html>
<body>
<h2>Contact information</h2>
<form:form method="POST" action="contacts/add" modelAttribute="contact">
<table>
<tr>
<td><form:label path="name">Name</form:label></td>
<td><form:input path="name" /></td>
</tr>
<tr>
<td><form:label path="surname">Surname</form:label></td>
<td><form:input path="surname" /></td>
</tr>
<tr>
<td><form:label path="phonenumber">Phonenumber</form:label></td>
<td><form:input path="phonenumber" /></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="Submit" /></td>
</tr>
</table>
</form:form>
</body>
</html>
Here is rest-handler-servlet.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"
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="facade.rest" />
<mvc:annotation-driven />
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
Here is servlet-mapping from web.xml
<servlet-mapping>
<servlet-name>rest-handler</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
And, finally a controller:
package facade.rest;
import java.util.List;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import domain.ContactDO;
import service.IContactService;
#Controller
public class ContactController {
private IContactService contactService;
#Required
public void setContactService(IContactService contactService) {
this.contactService = contactService;
}
#RequestMapping(value = "/contacts", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public #ResponseBody ResponseEntity<List<ContactDO>> getContacts() {
List<ContactDO> contacts = contactService.load();
if(contacts != null) {
return new ResponseEntity<>(contacts, HttpStatus.OK);
}
else
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
#RequestMapping(value = "/contacts/{id:.*}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public #ResponseBody ResponseEntity<ContactDO> getContact(#PathVariable Integer id) {
ContactDO contact = contactService.loadContact(id);
if(contact != null) {
return new ResponseEntity<>(contact, HttpStatus.OK);
}
else
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
#RequestMapping(value = "/contacts/add", method = RequestMethod.POST)
public String addContact(#ModelAttribute("contact") ContactDO contact, ModelMap model) {
model.addAttribute("name", contact.getName());
model.addAttribute("surname", contact.getSurname());
model.addAttribute("phonenumber", contact.getPhonenumber());
//contact.setId(2);
contactService.store(contact);
return "contacts";
}
}
When I am trying to access from at http://localhost:8080/pb/contacts/add (pb is a name of war) I get HTTP 400. Logs tell that I'm trying to do a get request.
When I am trying to access from at
http://localhost:8080/pb/contacts/add (pb is a name of war) I get HTTP
400. Logs tell that I'm trying to do a get request.
That is right !! you are trying /contacts/add using a GET request and the Request Handler can not map your request because /contacts/add is only accessible through a POST request. Look at your method definition:
#RequestMapping(value = "/contacts/add", method = RequestMethod.POST)
public String addContact(#ModelAttribute("contact") ContactDO contact, ModelMap model) {
}
you need a POST request to reach your method.
EDIT: I suppose you want to edit a contact with your /contacts/add method. If this is the case, then please first call /contacts/{id:.*} with id being the id of you contact. and then there you can make your edit and send your post by submitting your edit. That is how you reach you /contacts/add page.
If you don't know any id, then call first http://localhost:8080/pb/contacts
for your contacts. there your will (hopefully) find your contact to edit.
EDIT**: On your rest client, have you tried changing the type of request the to POST?
Related
index.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%#taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<body>
<div align="center" style="margin-top:100px;">
<font face="verdana" size="2">
${welcomeMessage} <BR><BR>
${result}
<form:form action="${pageContext.request.contextPath}/login.html" method="POST" modelAttribute="loginForm">
<table>
<tr>
<td colspan="2" align="center">Spring MVC Form Demo - Login</td>
</tr>
<tr>
<td>User Name</td>
<td><form:input path="username" /> <form:errors path="username"></form:errors></td>
</tr>
<tr>
<td>Password</td>
<td><form:password path="password" /> <form:errors path="password"></form:errors></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="Login" style="background-color:white;" /></td>
</tr>
</table>
</form:form>
Register if not already registered
</font>
</div>
</body>
</html>
HelloController.java
package java4s;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.context.annotation.Scope;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
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 java4s.model.Login;
#Controller
public class LoginSuccessController {
#Autowired
EmployeeService emp_service;
#RequestMapping(value = "/login", method=RequestMethod.POST)
public ModelAndView loginvalidateForm(ModelMap model, #ModelAttribute("loginForm") Login login, BindingResult result, HttpSession session) {
if(result.hasErrors()){
model.addAttribute("result", "All Fields are neccessary");
return new ModelAndView("index",model);
}
if(emp_service.validateLogin(login.getUsername(), login.getPassword()))
{
List<Employee> user_info = emp_service.getUserinfo(login.getUsername());
session.setAttribute("session_username", login.getUsername()); //Add value to session variable
model.addAttribute("result", "Login Success");
model.addAttribute("user_info", user_info);
return new ModelAndView("LoginSuccess",model);
}
else
{
model.addAttribute("result", "Login Failure");
return new ModelAndView("index",model);
}
}
}
Login.java
package java4s.model;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
public class Login {
#NotNull
#Size(min = 3, max = 20)
private String username;
#NotNull
#Size(min = 3, max = 20)
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;
}
}
I am trying to put validation on the login fields when they are empty, but errors are not showing on the index page the the login fields are empty. What is the problem in the code?
You have to add the annotation #Valid ( see the spring doc for more details) :
public ModelAndView loginvalidateForm(ModelMap model, #Valid #ModelAttribute("loginForm") Login login, BindingResult result, HttpSession session) {
....
}
Don't forget to enable “mvc:annotation-driven” to make Spring MVC supports #Valid annotation.
Add the following tag to your application context XML file.
<mvc:annotation-driven />
I am trying to run a project in Spring MVC. Here is the code
index.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#taglib prefix="form" uri="http://www.springframework.org/tags/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=UTF-8">
<title>Welcome to Spring Web MVC project</title>
</head>
<body>
<h1>Spring 3 Register!</h1>
click
<form:form action="${pageContext.request.contextPath}/register" method="POST" modelAttribute="userForm">
<table>
<tr>
<td colspan="2" align="center">Spring MVC Form Demo - Registration</td>
</tr>
<tr>
<td>User Name</td>
<td><form:input path="username" /></td>
</tr>
<tr>
<td>Password</td>
<td><form:password path="password" /></td>
</tr>
<tr>
<td>Email</td>
<td><form:input path="email" /></td>
</tr>
<tr>
<td>BirthDate (mm/dd/yyyy)</td>
<td><form:input path="birthDate" /></td>
</tr>
<tr>
<td>Profession</td>
<td><form:select path="profession" items="${professionList}" /></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="Register" /></td>
</tr>
</table>
</form:form>
</body>
</html>
RegistrationController.java
package RegisterInfo;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
*
* #author Harshit Shrivastava
*/
import RegisterInfo.model.User;
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.ui.Model;
#Controller
#RequestMapping(value = "/register")
public class RegistrationController {
#RequestMapping(method = RequestMethod.GET)
public String viewRegistration(Model model)
{
User userForm = new User();
model.addAttribute("userForm", new User());
List<String> professionList = new ArrayList();
professionList.add("Developer");
professionList.add("Designer");
professionList.add("IT Manager");
model.put("professionList", professionList);
return "index";
}
#RequestMapping(method = RequestMethod.POST)
public String processRegistration(#ModelAttribute("userForm") User user, Map<String, Object> model)
{
System.out.println("Username : " + user.getUserName());
model.put("userForm", new User());
return "index";
}
}
User.java
package RegisterInfo.model;
/**
*
* #author Harshit Shrivastava
*/
import java.util.Date;
public class User {
private String username;
private String password;
private String email;
private Date birthDate;
private String profession;
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;
}
public String getEmail()
{
return email;
}
public void setEmail(String email)
{
this.email = email;
}
public Date getBirthDate()
{
return birthDate;
}
public void setBirthDate(Date birthDate)
{
this.birthDate = birthDate;
}
public String getProfession()
{
return profession;
}
public void setProfession(String profession)
{
this.profession = profession;
}
}
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:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
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-3.1.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd ">
<bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping"/>
<context:component-scan base-package="RegisterInfo" />
<mvc:annotation-driven />
<!--
Most controllers will use the ControllerClassNameHandlerMapping above, but
for the index controller we are using ParameterizableViewController, so we must
define an explicit mapping for it.
-->
<bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<prop key="index.htm">indexController</prop>
</props>
</property>
</bean>
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/WEB-INF/jsp/"
p:suffix=".jsp" />
<!--
The index controller.
-->
<bean name="indexController"
class="org.springframework.web.servlet.mvc.ParameterizableViewController"
p:viewName="index" />
</beans>
In the above program, Whenever I go to submit the form, I always gets this error
Error:
HTTP Status 400 - Bad Request
The request sent by the client was syntactically incorrect
What is wrong with the code?
You must bind the Date when you submit a HTTP POST. Spring does not know that this is a Date, it sees it as a String.
Add this:
#InitBinder
public void initBinder(WebDataBinder binder) {
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
sdf.setLenient(true);
binder.registerCustomEditor(Date.class, new CustomDateEditor(sdf, true));
}
To your controller.
According to your code you are using
<prop key="index.htm">indexController</prop>
click
in above code spelling is not correct (htm instead of HTML).
<prop key="index.html">indexController</prop>
click
New to spring (and HTML/forms etc for that matter) and been stuck on this problem for long time.
So I want to have a front page where you enter a username. Then click submit, and takes you to a dashboard (ultimately, there will be a page with a list of connected users, a load of submit buttons to send predefined messages out - using qpid jms).
The front page is fine, but I click submit and I get an error (java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'dashboardModel' available as request attribute)
This only happens if I have a form:form in dashboard.jsp. I literally have no idea how to fix this and have tried everything I can find. My code is simple, and is just modified from a tutorial, so here it is:
login.jsp
<%#taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<html>
<head>
<title>Spring MVC Form Handling</title>
</head>
<body>
<h2>Login Page:</h2>
<form:form modelAttribute="loginModel" method="POST"
action="/HelloWeb/dashboard">
<table>
<tr>
<td><form:label path="username">Name</form:label></td>
<td><form:input path="username" /></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="Submit" /></td>
</tr>
</table>
</form:form>
</body>
</html>
Login.java
package com.tutorialspoint;
public class Login {
private String username;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
}
LoginController.java
package com.tutorialspoint;
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
public class LoginController {
#RequestMapping(value = "/login", method = RequestMethod.GET)
public ModelAndView login() {
return new ModelAndView("login", "loginModel", new Login());
}
#RequestMapping(value = "/loggedIn", method = RequestMethod.POST) //never actually used
public String loggedIn(#ModelAttribute("Login") Login login, ModelMap model) {
model.addAttribute("username", login.getUsername());
return "dashboard";
}
}
dashboard.jsp
<%#taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<html>
<head>
<title>DASHBOARD</title>
</head>
<body>
<table>
<tr>
<td>Dashboard</td>
<td>DASHBOARD</td>
</tr>
<tr>
<td>Username</td>
<td>${username}</td>
</tr>
<tr>
<td>variable</td>
<td>${variable}</td>
</tr>
</table>
<form:form modelAttribute="dashboardModel" method="POST"
action="/HelloWeb/dashboard">
<table>
<tr>
<td><form:label path="variable">Name</form:label></td>
<td><form:input path="variable" /></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="Submit" /></td>
</tr>
</table>
</form:form>
</body>
</html>
Dashboard.java
package com.tutorialspoint;
public class Dashboard {
private String variable;
public String getVariable() {
return variable;
}
public void setVariable(String variable) {
this.variable = variable;
}
}
DashboardController.java
package com.tutorialspoint;
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
public class DashboardController {
#RequestMapping(value = "/dashboard", method = RequestMethod.GET)
public ModelAndView dashboard() {
return new ModelAndView("dashboard", "dashboardModel", new Dashboard());
}
#RequestMapping(value = "/dashboard", method = RequestMethod.POST)
public String addVariable(#ModelAttribute("SpringWeb") Dashboard dashboard,
ModelMap model) {
model.addAttribute("variable", dashboard.getVariable());
return "dashboard";
}
}
Thanks for your time.
I think the problem is here:
<form:form modelAttribute="loginModel" method="POST" action="/HelloWeb/dashboard">
^^^^^^^^^^
and here:
#RequestMapping(value = "/loggedIn", method = RequestMethod.POST) //never actually used
public String loggedIn(#ModelAttribute("Login") Login login, ModelMap model) {
^^^^^
The modelAttribute value on form:form element and the #ModelAttribute argument should be the same.
I mean:
#RequestMapping(value = "/loggedIn", method = RequestMethod.POST) //never actually used
public String loggedIn(#ModelAttribute("loginModel") Login login, ModelMap model) {
^^^^^^^^^^
Edit:
Also, the form part should be like this:
<form:form modelAttribute="dashboardModel" method="POST" action="/loggedIn.htm">
<table>
<tr>
<td>Name</td>
<td><form:input path="username" /></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="Submit" /></td>
</tr>
</table>
</form:form>
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
This is a addBook.jsp when click on edit, it throws null pointer exception
<%# page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%#taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!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>Add booK Data</h2>
<form:form method="POST" action="/sdnext/save.html">
<table>
<tr>
<td><form:label path="bookCode">Book Code:</form:label></td>
<td><form:input path="bookCode" value="${book.bookCode}" readonly="true"/></td>
</tr>
<tr>
<td><form:label path="bookName">Book Name:</form:label></td>
<td><form:input path="bookName" value="${book.bookName}" /></td>
</tr>
<tr>
<td><form:label path="author">Book Author Name:</form:label></td>
<td><form:input path="author" value="${book.author}"/></td>
</tr>
<tr>
<td><form:label path="dateOfArrival">Date Of Arrival:</form:label></td>
<td><form:input path="dateOfArrival" value="${book.dateOfArrival}"/></td>
</tr>
<tr>
<td><form:label path="price">Price Of Book:</form:label></td>
<td><form:input path="price" value="${book.price}"/></td>
</tr>
<tr>
<td><form:label path="rackId">Book Rack Id:</form:label></td>
<td><form:input path="rackId" value="${book.rackId}"/></td>
</tr>
<tr>
<td><form:label path="numberOfBooks">Number of Books:</form:label></td>
<td><form:input path="numberOfBooks" value="${book.numberOfBooks}"/></td>
</tr>
<tr>
<td><form:label path="subjectCode">Book Subject Code:</form:label></td>
<td><form:input path="subjectCode" value="${book.subjectCode}"/></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="Submit"/></td>
</tr>
</table>
</form:form>
<c:if test="${!empty books}">
<h2>List Books</h2>
<table align="left" border="1">
<tr>
<th>NameOfBook</th>
<th>BookCode</th>
<th>AuthorName</th>
<th>DateOfArrival</th>
<th>PriceOfBook</th>
<th>BookRackId</th>
<th>NumberofBooks</th>
<th>BookSubjectCode</th>
<th>Actions on Row</th>
</tr>
<c:forEach items="${books}" var="book">
<tr>
<td><c:out value="${book.bookName}"/></td>
<td><c:out value="${book.bookCode}"/></td>
<td><c:out value="${book.author}"/></td>
<td><c:out value="${book.dateOfArrival}"/></td>
<td><c:out value="${book.price}"/></td>
<td><c:out value="${book.rackId}"/></td>
<td><c:out value="${book.numberOfBooks}"/></td>
<td><c:out value="${book.subjectCode}"/></td>
<td align="center">Edit | Delete</td>
</tr>
</c:forEach>
</table>
</c:if>
</body>
</html>
after submition exception thrown. because in controller the value of bookCode field is not recieve in bean class object.
type Exception report
message Request processing failed; nested exception is java.lang.NullPointerException
description The server encountered an internal error (Request processing failed; nested exception is java.lang.NullPointerException) that prevented it from fulfilling this request.
exception
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.NullPointerException
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:659)
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)
root cause
java.lang.NullPointerException
com.tcs.controller.BookController.editBook(BookController.java:76)
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.doInvokeMethod(HandlerMethodInvoker.java:710)
org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:167)
org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:414)
org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:402)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:771)
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)
note The full stack trace of the root cause is available in the Apache Tomcat/7.0.29 logs.
This is my Controller class where i gets the value of bookCode field in edit mehod and get method is null;
package com.tcs.controller;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import com.tcs.bean.BookBean;
import com.tcs.model.Book;
import com.tcs.service.BookService;
#Controller
public class BookController {
#Autowired
private BookService bookService;
#RequestMapping(method=RequestMethod.POST, value = "/save")
public ModelAndView saveBook(#ModelAttribute("command") BookBean bookBean, BindingResult result) {
Book book = prepareModel(bookBean);
bookService.addBook(book);
return new ModelAndView("redirect:/add.html");
}
#RequestMapping(value="/books", method = RequestMethod.GET)
public ModelAndView listBooks() {
Map<String, Object> model = new HashMap<String, Object>();
model.put("books", prepareListofBean(bookService.listBooks()));
return new ModelAndView("booksList", model);
}
#RequestMapping(value = "/add", method = RequestMethod.GET)
public ModelAndView addBook(#ModelAttribute("command") BookBean booksBean, BindingResult result) {
Map<String, Object> model = new HashMap<String, Object>();
model.put("books", prepareListofBean(bookService.listBooks()));
return new ModelAndView("addBook", model);
}
#RequestMapping(value = "/index", method = RequestMethod.GET)
public ModelAndView welcome() {
return new ModelAndView("index");
}
#RequestMapping(value = "/delete", method = RequestMethod.GET)
public ModelAndView deleteBook(#ModelAttribute("command") BookBean bookBean, BindingResult result) {
System.out.println(bookBean.getBookCode());
bookService.deleteBook(prepareModel(bookBean));
Map<String, Object> model = new HashMap<String, Object>();
model.put("book", null);
model.put("books", prepareListofBean(bookService.listBooks()));
return new ModelAndView("addBook", model);
}
#RequestMapping(value = "/edit" , method=RequestMethod.GET)
public ModelAndView editBook(#ModelAttribute("command") BookBean bookBean, BindingResult result) {
Map<String, Object> model = new HashMap<String, Object>();
System.out.println(bookBean.getBookCode());
model.put("book", prepareBooksBean(bookService.getBook(bookBean.getBookCode())));
model.put("books", prepareListofBean(bookService.listBooks()));
return new ModelAndView("addBook", model);
}
private Book prepareModel(BookBean bookBean){
Book book = new Book();
book.setBookName(bookBean.getBookName());
book.setBookCode(bookBean.getBookCode());
book.setAuthor(bookBean.getAuthor());
book.setDateOfArrival(bookBean.getDateOfArrival());
book.setPrice(bookBean.getPrice());
book.setRackId(bookBean.getRackId());
book.setNumberOfBooks(bookBean.getNumberOfBooks());
book.setSubjectCode(bookBean.getSubjectCode());
return book;
}
private List<BookBean> prepareListofBean(List<Book> books){
List<BookBean> beans = null;
if(books != null && !books.isEmpty()) {
beans = new ArrayList<BookBean>();
BookBean bean = null;
for(Book book : books){
bean = new BookBean();
bean.setBookName(book.getBookName());
bean.setBookCode(book.getBookCode());
bean.setAuthor(book.getAuthor());
bean.setDateOfArrival(book.getDateOfArrival());
bean.setPrice(book.getPrice());
bean.setRackId(book.getRackId());
bean.setNumberOfBooks(book.getNumberOfBooks());
bean.setSubjectCode(book.getSubjectCode());
beans.add(bean);
}
}
return beans;
}
private BookBean prepareBooksBean(Book book){
BookBean bean = new BookBean();
bean.setBookName(book.getBookName());
bean.setBookCode(book.getBookCode());
bean.setAuthor(book.getAuthor());
bean.setDateOfArrival(book.getDateOfArrival());
bean.setPrice(book.getPrice());
bean.setRackId(book.getRackId());
bean.setNumberOfBooks(book.getNumberOfBooks());
bean.setSubjectCode(book.getSubjectCode());
return bean;
}
}
this is a service class of my controller
package com.tcs.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import com.tcs.dao.BookDao;
import com.tcs.model.Book;
#Service("bookService")
#Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
public class BookServiceImpl implements BookService {
#Autowired
private BookDao bookDao;
#Transactional(propagation = Propagation.REQUIRED, readOnly = false)
public void addBook(Book book) {
bookDao.addBook(book);
}
public List<Book> listBooks() {
return bookDao.listBooks();
}
public Book getBook(int bookCode) {
return bookDao.getBook(bookCode);
}
public void deleteBook(Book book) {
bookDao.deleteBook(book);
}
}
this is a setting of 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:tx="http://www.springframework.org/schema/tx"
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
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
<context:property-placeholder location="classpath:resources/database.properties" />
<context:component-scan base-package="com.tcs" />
<tx:annotation-driven transaction-manager="hibernateTransactionManager"/>
<bean id="jspViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${database.driver}" />
<property name="url" value="${database.url}" />
<property name="username" value="${database.user}" />
<property name="password" value="${database.password}" />
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="annotatedClasses">
<list>
<value>com.tcs.model.Book</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
<prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
</props>
</property>
</bean>
<bean id="hibernateTransactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
</beans>
this is a web.xml file
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<servlet>
<servlet-name>sdnext</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/config/sdnext-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>sdnext</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>
You edit method
#RequestMapping(value = "/edit" , method=RequestMethod.GET)
public ModelAndView editBook(#ModelAttribute("command") BookBean bookBean,
BindingResult result) {
Map<String, Object> model = new HashMap<String, Object>();
System.out.println(bookBean.getBookCode()); // bookbean is null
model.put("book", prepareBooksBean(bookService.getBook(bookBean.getBookCode())));
model.put("books", prepareListofBean(bookService.listBooks()));
return new ModelAndView("addBook", model);
}
accepts a BookBean instance. For spring to create this bean for you, it needs to have request parameters that map to the fields of the object. You're making your request through an <a href> anchor.
Edit
The only parameter in the request is id, which doesn't even match the bookCode field name. Spring won't be able to create a bean and will therefore pass null. You can read more about the process here.
We can assume something similar occurs for deleteBook.
This may have been asked many times but I have not been able to find a concrete answer over last two days. Using Spring 3.2.
I have two methods. One is for form creation and the other is for the form to post. Form creation works fine. But when I try to post/submit the form, I don't see the log statement getting executed in the login() method and I get a 404 error HTTP Status 404 - /sample/login.
I think the problem is the form cannot submit to URL but I don`t know how to fix the mapping to make it work.
If there are any other files that are needed please let me know. BTW following example from sprin/mvc-basic and spring/petclinic
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
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 example.domain.User;
import example.service.UserValidator;
#Controller
#RequestMapping(value="/login")
public class LoginFormController {
protected final Log logger = LogFactory.getLog(getClass());
#RequestMapping(method=RequestMethod.GET)
public String loadForm(Model model) {
logger.info("LoginFormController login");
model.addAttribute("user", User.getUserInstance());
return "login";
}
#RequestMapping(method=RequestMethod.POST)
public String login(#ModelAttribute User user, BindingResult result) {
logger.info("post");
new UserValidator().validate(user, result);
if (result.hasErrors()) {
return "login";
} else {
logger.info("Email Id: " + user.getEmailId());
//this.clinic.storeOwner(owner);
//status.setComplete();
return "redirect:/landing/" + user.getEmailId();
}
}
}
login.jsp
<%# include file="/WEB-INF/jsp/include.jsp"%>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<html>
<head>
<title><fmt:message key="title" /></title>
<style>
.error {
color: red;
}
</style>
</head>
<body>
<h1>
<fmt:message key="login.heading" />
</h1>
<form:form method="post" modelAttribute="user" action="login">
<table width="95%" bgcolor="f8f8ff" border="0" cellspacing="0" cellpadding="5">
<tr>
<td align="right" width="20%"><form:label for="emailId" path="emailId" cssErrorClass="error">Email ID:</form:label></td>
<td width="20%"><form:input path="emailId" /></td>
<td width="60%"><form:errors path="emailId" cssClass="error" /></td>
</tr>
<tr>
<td align="right" width="20%"><form:label for="password" path="password" cssErrorClass="error">Password:</form:label></td>
<td width="20%"><form:input path="password" /></td>
<td width="60%"><form:errors path="password" cssClass="error" /></td>
</tr>
</table>
<br>
<input type="submit" align="center" value="Login">
</form:form>
Signup
</body>
</html>
name-servlet.xml
<bean....>
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"></property>
<property name="prefix" value="/WEB-INF/jsp/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
</bean>
Your help appreciated.
Seems you have mapped *.htm URL to DispatcherServlet (Guessing from /signup.htm). Change the action in your form tag to login.htm instead of login:
<form:form method="post" modelAttribute="user" action="login.htm">