Again Neither BindingResult nor plain target object for bean name - java

Hi I am getiing the above exception : java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'Projet' available as request attribute. Please find my jsp and controller class.
The code I have is like below.
Controller code:
#Controller
#RequestMapping(value="/directeur")
public class AdminController {
#Autowired
private IAdmin directeur;
#RequestMapping(value="/index")
public String index(Model model)
{
model.addAttribute("Projet",new Projet());
model.addAttribute("Projets",directeur.getAllProjet());
return "Projets";
}
#RequestMapping(value="/saveProjet",method = RequestMethod.POST)
public String saveProjet(Projet p,BindingResult result,Model model) throws IOException
{
if(result.hasErrors())
{
model.addAttribute("Projets",directeur.getAllProjet());
return "Projets";
}
directeur.ajouterProjet(p);
model.addAttribute("Projet",new Projet());
model.addAttribute("Projets",directeur.getAllProjet());
return "Projets";
}
}
Jsp Code:
<%#taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%#taglib uri="http://www.springframework.org/tags/form" prefix="f"%>
<div id="formProjet">
<f:form modelAttribute="Projet" action="saveProjet" method="POST"
enctype="multipart/form-data">
<table>
<tr>
<td>ID Projet</td>
<td><f:input path="idProjet" /></td>
<td><f:errors path="idProjet" cssClass="errors"/></td>
</tr>
<tr>
<td>Nom</td>
<td><f:textarea path="nomProjet" /></td>
<td><f:errors path="nomProjet" cssClass="errors"/></td>
</tr>
<tr>
<td>Description du Projet</td>
<td><f:textarea path="description" /></td>
<td><f:errors path="description" cssClass="errors"/></td>
<tr><td><input type="submit" value="enregistrer"/></td></tr>
</table>
</f:form>
</div>
<div id="">
<table>
<tr>
<th>ID</th>
<th>Nom</th>
<th>Description</th>
<th>Photo</th>
</tr>
<c:forEach items="${Projets }" var="proj">
<tr>
<td>${proj.idProjet }</td>
<td>${proj.nomProjet }</td>
<td>${proj.description }</td>
<td></td>
</tr>
</c:forEach>
</table>
</div>

Related

Spring MVC Add and Modification doesn't work properly as I want

Currently in my project, addEmployee.jsp show properly when "Add Employee" or "Edit" is clicked, but when I try to hit submit button in "Add Employee" page, page return "Http status 500 Request processing failed; nested exception is java.lang.NullPointerException", or when I try to hit submit button in "Add Employee" page for update employee info, I will get "HTTP Status 405 - Request method 'POST' not supported"
The way I want is when I add a new employee or update the existing employee info, I will still using addEmployee.jsp page. If it is add a new one, all the field will be empty, otherwise, all the field will contain the existing information for update.
Here is the code for employee.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Employee List</title>
</head>
<body>
<div align="center">
<h1 style="background-color: lightgreen; color: darkgreen">Employee
Page</h1>
<table align="center" width="80%" cellspacing="0" cellpadding="5">
<tr>
<td align="center">
<table cellspacing="0" cellpadding="6" border="0" width="100%">
<tr bgcolor="lightblue">
<td align="left"><a
href="${pageContext.request.contextPath}/employee/addEmployee"
style="background-color: lightblue;"> Add Employee </a></td>
</table>
</td>
</tr>
<tr>
<td>
<table cellspacing="0" cellpadding="6" border="1" width="100%">
<tr>
<td colspan="8"
style="background-color: lightblue; color: darkgreen; font-size: 16pt"
align="center">Employee List</td>
</tr>
<tr bgcolor="grey" style="color: white">
<th>No</th>
<th>First Name</th>
<th>Last Name</th>
<th>Job Title</th>
<th>Department</th>
<th>Salary</th>
<th>Edit</th>
<th>Delete</th>
</tr>
<c:forEach var="employee" items="${employeesList}"
varStatus="status">
<tr bgcolor="lightyellow">
<td><b>${status.index + 1}</b></td>
<td>${employee.firstName}</td>
<td>${employee.lastName}</td>
<td>${employee.jobTitle}</td>
<td>${employee.department}</td>
<td>${employee.salary}</td>
<td>Edit</td>
<td>Delete</td>
</tr>
</c:forEach>
</table>
</td>
</tr>
</table>
</div>
</body>
</html>
And Here is the code for addEmployee.jsp page
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%# taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%#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>Add Employee</title>
</head>
<body>
<div align="center">
<h1 style="background-color: lightgreen; color: darkgreen">Add
New Employee Page</h1>
<table width="80%" align="center">
<tr bgcolor="lightblue">
<td align="left"><a href="listEmployees"
style="background-color: lightblue;">List Employee</a></td>
</table>
</div>
<br />
<div align="center">
<table cellspacing="0" cellpadding="6" border="1" width="80%">
<tr>
<td colspan="8"
style="background-color: lightblue; color: darkgreen; font-size: 16pt"
align="center">Employee Information</td>
</tr>
<tr>
<td><form:form method="POST" action="updateEmployee">
<table width="100%">
<tr>
<td><form:label path="firstName">First Name</form:label></td>
<td align="left" width="70%"><form:input path="firstName" /></td>
</tr>
<tr>
<td><form:label path="lastName">Last Name</form:label></td>
<td align="left" width="70%"><form:input path="lastName" /></td>
</tr>
<tr>
<td><form:label path="jobTitle">Job Title</form:label></td>
<td align="left" width="70%"><form:input path="jobTitle" /></td>
</tr>
<tr>
<td><form:label path="department">Department</form:label></td>
<td align="left" width="70%"><form:input path="department" /></td>
</tr>
<tr>
<td><form:label path="salary">Salary</form:label></td>
<td align="left" width="70%"><form:input path="salary" /></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="Submit" /></td>
</tr>
</table>
</form:form></td>
</tr>
</table>
</div>
</body>
</html>
Here is the code for EmployeeController.java
package com.vincent.springmvc.controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
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.servlet.ModelAndView;
import com.vincent.springmvc.model.Employee;
import com.vincent.springmvc.service.EmployeeService;
#Controller
#RequestMapping("/employee")
public class EmployeeController {
//Logger file
private static Logger logger = LoggerFactory.getLogger(EmployeeController.class);
#Autowired
private EmployeeService employeeService;
#RequestMapping(method = RequestMethod.GET)
public String welcomeEmployee(ModelMap model){
model.addAttribute("name", "Hello World!");
model.addAttribute("greetings", "Welcome to Spring MVC");
return "hello";
}
#RequestMapping(value = "/listEmployees", method = RequestMethod.GET)
public String listEmployees(ModelMap model){
model.addAttribute("employeesList", this.employeeService.listEmployee());
return "employee";
}
#RequestMapping(value = "/addEmployee", method = RequestMethod.GET)
public ModelAndView addEmployee(ModelMap model){
return new ModelAndView("addEmployee", "command", new Employee());
}
#RequestMapping(value = "/updateEmployee", method = RequestMethod.POST)
public String updateEmployee(#ModelAttribute("employee") Employee employee, ModelMap model){
if(employee.getId() == 0)
this.employeeService.insertEmployee(employee);
else
this.employeeService.updateEmployee(employee);
model.addAttribute("employeesList", this.employeeService.listEmployee());
return "employee";
}
#RequestMapping(value = "/delete/{empId}", method = RequestMethod.GET)
public String deleteEmployee(#PathVariable("empId") Integer empId, ModelMap model){
this.employeeService.deleteEmployee(empId);
model.addAttribute("employeesList", this.employeeService.listEmployee());
return "employee";
}
#RequestMapping(value = "/edit/{empId}", method=RequestMethod.GET)
public ModelAndView editEmployee(#PathVariable("empId") int id, ModelMap model){
return new ModelAndView("addEmployee", "command", this.employeeService.getEmployeeById(id));
}
}
Here is the project structure
Project Structure
and the rest of the code you can find in https://github.com/zhengye1/SpringMVC
Thank you for the help
Kind of resolve for now.... but seems like not a very good idea, it is time to looking for good advice..
The way I fix is, in my controller class, I change the annotation in updateEmployee with following annotation #RequestMapping(value = {"/updateEmployee", "/edit/updateEmployee"}, method = RequestMethod.POST). This because when I tracing the log, I realize somehow the server try to mapping the page called edit/updateEmployee, originally is not exists, that is why it raising the 504 error for update.
For adding issue is causing by the form, since the form return the null id, therefore when I try to compare the null object with 0, it raise the null pointer exception. The way I fix is, change that line to if (employee.getId() == null), and also in addEmployee.jsp page, I add the this line to my form, <form:hidden path="id" />. That is resolve the issue.

Struts2 actionError not displaying on jsp when action implemented ModelDriven

I have my Struts2 Action class as below and I am expecting the actionerror message should be displayed in my JSP page using the tag: <s:actionerror />
However the message did not show up, and I've found that if I change in the getModel() method return form; to return null;, the error message could be displayed again! How can I show the error message at the same time returning the form object in getModel() method?
public class StartSearchApplicationAction
extends ActionSupport
implements ModelDriven, SessionAware {
protected Map<String, Object> session;
private Formbean form;
public String execute() {
addActionError("Testing Error Message");
session.put("form", form);
return "success";
}
public Formbean getModel() {
form = (Formbean) session.get("form");
if (form == null) {
form = new Formbean();
}
return form;
}
public void setSession(Map<String, Object> session){
this.session = session;
}
}
Updated on 20-Oct-2015 - My JSP (it is the tiles template page)
Note that even I change the statement <s:if test='%{#session.hasError == "Y"}'> to <s:if test="hasActionErrors()">, the result is the same
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<%# page language="java" %>
<%# page contentType="text/html; charset=UTF-8" %>
<%# page errorPage="/jsp/error.jsp" %>
<%# taglib prefix="s" uri="/struts-tags"%>
<%# taglib uri="http://tiles.apache.org/tags-tiles" prefix="tiles"%>
<html>
<head>
<title><s:text name="global.heading.title"/></title>
</head>
<body>
<table class="main" border="0" cellspacing="0" cellpadding="0">
<tr>
<td>
<table border="0" cellspacing="0" cellpadding="0">
<tr>
<td width="860" valign="top" bgcolor="#FFFFFF">
<table border="0" valign="top" align="left">
<s:if test='%{#session.hasError == "Y"}'>
<tr>
<table width="500" border="0" cellspacing="0" cellpadding="2" align="center" bgcolor="#006600">
<tr>
<td width="16" class="ErrorMessageBoxTitle"><img src="/<s:text name="global.system.root"/>/images/smessage.gif" width="16" height="14" align="absmiddle" alt="System Errors"></td>
</tr>
<tr>
<td colspan="2" class="FixTdSize">
<table width="496" border="0" cellspacing="0" cellpadding="0" bgcolor="#FFFFFF">
<tr>
<td align="center" class="FixTdSize">
<table border="0" cellspacing="12" cellpadding="0" width="480">
<tr>
<td width="35" class="ErrorMessageTitle"><img src="/<s:text name="global.system.root"/>/images/messager.gif" width="31" height="31" alt="System Errors"></td>
<td class="ErrorMessageTitle" width="409">&nbsp</td>
</tr>
<tr>
<td width="35" class="ErrorMessageBody"> </td>
<td class="label" width="409"><font color=red><s:actionerror/></font></td>
</tr>
</table>
</td>
</tr>
</table>
</td>
</tr>
</table>
</tr>
<tr><td> </td></tr>
</s:if>
<tr>
<td height="30"><tiles:insertAttribute name="searchpanel"/></td>
</tr>
<tr>
<td><img src="/<s:text name="global.system.root"/>/images/line.gif" width="100%" height="2"></td>
</tr>
<tr>
<td><tiles:insertAttribute name="message"/></td>
</tr>
<tr>
<td><tiles:insertAttribute name="body"/></td>
</tr>
</table>
</td>
</tr>
</table>
</td>
</tr>
</table>
</table>
<tiles:insertAttribute name="menu"/>
</body>
</html>
after investigation I finally did it with referencing to this question:
Passing parameters to action through ModelDriven in Struts 2
I think the reason is Modeldriven interceptor pushes the model on top of the value stack (i.e. 0-index) and thus the jsp could not access the actionError (the original 0-index was the action class).
Instead of using <s:actionerror/>, the page could able to display the actionError using <s:property value="[1].actionErrors[0]"/>, I am not sure whether this is a good approach but it serve the purpose.

Spring Mvc submit/delete checked (selected) records from table

I'm trying to submit selected items from a table and moake some modifications on them but I couldn't get it work.
MyObject.java
public class MyObject{
boolean checkControl = true; //default true
private String name;
private String code;
//getters & setters
}
MyObjectForm.java
public class MyObjectForm {
private List<MyObject> myList;
public List<MyObject> getMyList() {
return myList;
}
public void setMyList(List<MyObject> myList) {
this.myList= myList;
}
}
list-myObjects.jsp
<form:form action="submitList" method="post" modelAttribute="myObjectForm">
<table>
<tbody>
<c:forEach items="${myObjectForm.myList}" var="row" varStatus="status">
<tr>
<td>
<spring:bind path="myList[${status.index}].checkControl">
<input type="checkbox" value="<c:out value="${status.value}"/>" name="isChecked" <c:if test="${row.checkControl}"> checked="checked" </c:if> />
</spring:bind>
</td>
<td>${row.name}</td>
<td>${row.code}</td>
</tr>
</c:forEach>
</tbody>
</table>
<button type="submit">Submit</button>
</form:form>
And the controller
#RequestMapping(value = "/submitList", method = RequestMethod.POST)
public String save(#ModelAttribute("myObjectForm") MyObjectForm myObjectForm, Model model) {
List<MyObject> selectedtList = myObjectForm.getMyList(); //returns null
if (selectedtList == null) {
System.out.println("no objects selected");
}
else {
//Make some computation
}
model.addAttribute("resultArray", selectedtList);
return "display-items";
}
Some users asked me to explain this in more detail by email. So I decided to submit it here, Hope this helps.
I'm using spring annotations, to do the job. here is what I did to process selected checkboxes,
I have a java entity class which includes a boolean value for the checkbox, for example a Person class
// Person.java
class Person {
private Long id;
private String name;
private boolean check;
//here goes getters and setters
}
than I have a form object in java, which contains a list of Person
//PersonForm.java
class PersonForm {
private List<Person> personList;
//getters and setters here
}
in my case, there are two jsp pages, the first one lists items, with checkboxes, and the second one lists selected items.
the first jsp file is list.jsp
//list.jsp
<%# taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%# taglib prefix="datatables" uri="http://github.com/dandelion/datatables"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
....
<body>
<form:form action="sent-list" method="post" modelAttribute="personForm">
<table id="item-list" class="table table-striped table-bordered">
<thead class="dataTableHeader">
<tr>
<th width="10%" style="text-align:center">
CheckBox
</th>
<th>id</th>
<th>name</th>
</tr>
</thead>
<tbody>
<c:forEach items="${personForm.personList}" var="listItem" varStatus="status">
<tr>
<td style="text-align:center">
<form:checkbox path="listItem[${status.index}].check"/>
</td>
<td>${listItem.id} <form:hidden path="listItem[${status.index}].id"/></td>
<td>${listItem.name} <form:hidden path="listItem[${status.index}].name"/></td>
</tr>
</c:forEach>
</tbody>
</table>
<button class="btn btn-large btn-success pull-right" type="submit">POST</button>
</form:form>
</body>
</html>
the second jsp file is as follows
//sent-list.jsp
<%# taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%# taglib prefix="datatables" uri="http://github.com/dandelion/datatables"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
.....
<body>
<form:form action="#" method="post" modelAttribute="personForm">
<table id="item-list" class="table table-striped table-bordered">
<thead class="dataTableHeader">
<tr>
<th>id</th>
<th>name</th>
</tr>
</thead>
<tbody>
<c:forEach items="${resultList}" var="personItem" varStatus="status">
<tr>
<td>${personItem.id}</td>
<td>${personItem.name}</td>
</tr>
</c:forEach>
</tbody>
</table>
</form:form>
</body>
</html>
and finally there is a controller, which makes the computation
//PersonController.java
#Controller
class PersonController {
#RequestMapping(value = "/sent-list", method = RequestMethod.POST)
public String save(#ModelAttribute("personForm") PersonForm personForm, Model model){
for(Person personItem : personForm.getPersonList){
//make some computation here
}
}
}
I hope this helps.
Sounds like a binding issue. Have you tried using Spring's <form:checkbox> tag rather than <spring:bind>? It will automatically generate the checkbox attributes as well as adding a hidden field that Spring uses to determine whether the checkbox is 'on' or 'off'.
<form:form action="submitList" method="post" modelAttribute="myObjectForm">
<table>
<tbody>
<c:forEach items="${myObjectForm.myList}" var="row" varStatus="status">
<tr>
<td>
<form:checkbox path="myList[${status.index}].checkControl"/>
</td>
<td>${row.name}</td>
<td>${row.code}</td>
</tr>
</c:forEach>
</tbody>
</table>
<button type="submit">Submit</button>
</form:form>

Spring MVC project with hibernate can' understand how to use in jsp

I am studying Spring MVC, and I have a problem with understanding how to use my classes in jsp, here is my controller:
#Controller
public class BusinessController {
#Autowired
private BusinessService businessService;
#RequestMapping("/index")
public String listContacts(Map<String, Object> map) {
map.put("business", new Business());
map.put("businessList", businessService.listBusiness());
return "business";
}
#RequestMapping("/find/{businessDate}")
public String listContactsByDate(#PathVariable("businessDate") Map<String, Object> map, String businessDate) {
map.put("businessByDate", new Business());
map.put("businessByDateList", businessService.listBusinessByDate(businessDate));
return "businessByDate";
}
#RequestMapping("/")
public String home() {
return "redirect:/index";
}
#RequestMapping(value = "/add", method = RequestMethod.POST)
public String addBusiness(#ModelAttribute("business") Business business, BindingResult result) {
businessService.addBusiness(business);
return "redirect:/index";
}
#RequestMapping("/delete/{businessId}")
public String deleteBusiness(#PathVariable("businessId") Integer businessId) {
businessService.removeBusiness(businessId);
return "redirect:/index";
}
}
And here is my jsp:
<!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=utf8">
<title><spring:message code="label.title" /></title>
</head>
<body>
<h2>
<spring:message code="label.title" />
</h2>
<form:form method="post" action="add" commandName="business">
<table>
<tr>
<td><form:label path="businessDate">
<spring:message code="label.date" />
</form:label></td>
<td><form:input path="businessDate" /></td>
</tr>
<tr>
<td><form:label path="description">
<spring:message code="label.description" />
</form:label></td>
<td><form:input path="description" /></td>
</tr>
<tr>
<td colspan="2"><input type="submit"
value="<spring:message code="label.addbusiness"/>" /></td>
</tr>
</table>
</form:form>
<form:form method="post" action="/find/{$businessDate}"
commandName="businessByDate">
<table>
<tr>
<td><form:label path="businessDate">
<spring:message code="label.date" />
</form:label></td>
<td><form:input path="businessDate" /></td>
</tr>
</table>
<c:if test="${!empty businessByDateList}">
<table class="data">
<tr>
<th><spring:message code="label.date" /></th>
<th><spring:message code="label.description" /></th>
<th> </th>
</tr>
<c:forEach items="${businessByDate}" var="business">
<tr>
<td>${businessByDate.businessDate}</td>
<td>${businessByDate.description}</td>
<td><a href="delete/${businessByDate.id}"><spring:message
code="label.delete" /></a></td>
</tr>
</c:forEach>
</table>
</c:if>
</form:form>
<h3>
<spring:message code="label.businesses" />
</h3>
<c:if test="${!empty businessList}">
<table class="data">
<tr>
<th><spring:message code="label.date" /></th>
<th><spring:message code="label.description" /></th>
<th> </th>
</tr>
<c:forEach items="${businessList}" var="business">
<tr>
<td>${business.businessDate}</td>
<td>${business.description}</td>
<td><a href="delete/${business.id}"><spring:message
code="label.delete" /></a></td>
</tr>
</c:forEach>
</table>
</c:if>
</body>
</html>
And, here is my service implementation class:
#Repository
public class BusinessDAOImpl implements BusinessDAO{
#Autowired
private SessionFactory sessionFactory;
public void addBusiness(Business business){
sessionFactory.getCurrentSession().save(business);
}
#SuppressWarnings("unchecked")
public List<Business> listBusinessByDate(String businessDate){
String hql = "from Business B where B.date = :business_date";
Query query = sessionFactory.getCurrentSession().createQuery(hql);
query.setParameter("business_date", businessDate);
return query.list();
}
#SuppressWarnings("unchecked")
public List<Business> listBusiness(){
return sessionFactory.getCurrentSession().createQuery("from Business").list();
}
public void removeBusiness(Integer id){
Business business = (Business) sessionFactory.getCurrentSession().load(
Business.class, id);
if (null != business) {
sessionFactory.getCurrentSession().delete(business);
}
}
}
Without the part of jsp, where I try to list businesses for date everything works fine, I can add a business and it will be immediately listed in a table below, but if I add a part with businessByDate I'll get
Neither BindingResult nor plain target object for bean name 'businessByDate' available as request attribute
How can I solve that? Thank you
enter code here
That's coming out of this form tag:
<form:form method="post" action="/find/{$businessDate}"
commandName="businessByDate">
It looks like you only do:
map.put("businessByDate", new Business());
In the method that is this form's action. You need to add that object to the map in the method that actually loads the page!

Working with commandName in spring view: IllegalStateException: Neither BindingResult nor plain target object

I was working with spring and read about the use of commandName in view(jsp). I have a little trouble working with it can anyone help me how to effectively use it?
i get this error when i use in my jsp page.
SEVERE: Servlet.service() for servlet [dispatcher] in context with path
[/hibernateAnnotaionWithSpring] threw exception [An exception occurred processing JSP
page /WEB-INF/jsp/userForm.jsp at line 17
14: <table>
15: <tr>
16: <td>User Name :</td>
17: <td><form:input path="name" /></td>
18: </tr>
19: <tr>
20: <td>Password :</td>
Stacktrace:] with root cause
java.lang.IllegalStateException: Neither BindingResult nor plain target object for
bean name 'user' available as request attribute
at org.springframework.web.servlet.support.BindStatus.<init>(BindStatus.java:141)
my code is as follows:-
when i click on submit button it should take me to userForm page
<form action="login.htm">
<table class="hundredPercent headerBackground" cellspacing="0">
<tr>
<td class="textLabel sevenPer">
Email
</td>
<td class="textField sevenPer">
<input type="text" value="" name="username">
</td>
<td class="textLabel sevenPer">
Password
</td>
<td class="textField sevenPer">
<input type="password" value="" name="password">
</td>
<td class="textField">
<input type="submit" value="Enter" name="submit" class="buttonSubmit">
</td>
<td>
</td>
<td class="textLabel">
<a href="list.htm" >Register</a>
</td>
</tr>
</table>
</form>
my controller class
#RequestMapping("/login.htm")
public String login(HttpServletRequest request,
HttpServletResponse response,ModelMap model) throws Exception {
String userName= request.getParameter("username");
String password= request.getParameter("password");
System.out.println("name===="+userName);
return "userForm";
}
finally my resultant jsp page
<%# 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"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Registration Page</title>
</head>
<body>
<form:form action="add.htm" commandName="user" method="POST">
<table>
<tr>
<td>User Name :</td>
<td><form:input path="name" /></td>
</tr>
<tr>
<td>Password :</td>
<td><form:password path="password" /></td>
</tr>
<tr>
<td>Gender :</td>
<td><form:radiobutton path="gender" value="M" label="M" />
<form:radiobutton
path="gender" value="F" label="F" /></td>
</tr>
<tr>
<td>Country :</td>
<td><form:select path="country">
<form:option value="0" label="Select" />
<form:option value="India" label="India" />
<form:option value="USA" label="USA" />
<form:option value="UK" label="UK" />
</form:select></td>
</tr>
<tr>
<td>About you :</td>
<td><form:textarea path="aboutYou" /></td>
</tr>
<tr>
<td>Community :</td>
<td><form:checkbox path="community" value="Spring"
label="Spring" /> <form:checkbox path="community"
value="Hibernate"
label="Hibernate" /> <form:checkbox path="community"
value="Struts"
label="Struts" /></td>
</tr>
<tr>
<td></td>
<td><form:checkbox path="mailingList"
label="Would you like to join our mailinglist?" /></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="Register"></td>
</tr>
</table>
</form:form>
</body>
</html>
Can anyone please help on this?
Thanks in advance
You need to add an empty user to the model.
#RequestMapping("/login.htm")
public String login(HttpServletRequest request,
HttpServletResponse response, ModelMap model) throws Exception {
String userName= request.getParameter("username");
String password= request.getParameter("password");
System.out.println("name===="+userName);
model.addAttribute("user", new User(...)):
return "userForm";
}
in addition you have to write:
<form:form action="add.htm" modelAttribute="user" method="POST">
(modelAttribute instead of commandName)
Anyway your controller is a bit uncommon. Try This:
#RequestMapping(value="/login.htm" method = RequestMethod.GET)
public String loginForm(ModelMap model) throws Exception {
model.addAttribute("user", new User("", "")):
return "userForm";
}
#RequestMapping(value="/login.htm" method = RequestMethod.POST)
public String login(User user) throws Exception {
String userName= user.getUsername();
String password= user.getPassword();
...
}
/** The command class */
public class User{
private String username;
private String password:
Getter and Setter
}

Categories

Resources