How to retrieve "Grouped" items from HTML form using Servlet? - java

I am having an issue with retriving "grouped" data from HTML form to servlet. I will describve the scenario below.
In companies, they record the salary of the employees once a month.When they record it, they do not do it by visiting each an every employees personal "profile" (or whatever according to the system). Instead what they do is apply the salaries of all of them in one page.
To do the above thing they prefer excel like tabular sheets.
Now, I have a html form, where the form content is a table. One row is dedicated to a one employee.
Below is my form.
<%--
Document : index2
Created on : Mar 5, 2015, 10:04:45 AM
--%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h1>Hello World!</h1>
<form method="post" action="EmployeeSampleServlet">
<table border="1" style="width:100%">
<thead>
<th>Name</th>
<th>Position</th>
<th>Salary</th>
</thead>
<tbody name="tableBody" value="1">
<tr>
<td><input type="text" name="nameTxt" style="width:100%"/></td>
<td><input type="text" name="positionTxt" style="width:100%"/></td>
<td><input type="text" name="salaryTxt" style="width:100%"/></td>
</tr>
</tbody>
<tbody name="tableBody" value="2">
<tr>
<td><input type="text" name="nameTxt" style="width:100%"/></td>
<td><input type="text" name="positionTxt" style="width:100%"/></td>
<td><input type="text" name="salaryTxt" style="width:100%"/></td>
</tr>
</tbody>
<tbody name="tableBody" value="3">
<tr>
<td><input type="text" name="nameTxt" style="width:100%"/></td>
<td><input type="text" name="positionTxt" style="width:100%"/></td>
<td><input type="text" name="salaryTxt" style="width:100%"/></td>
</tr>
</tbody>
<tbody name="tableBody" value="4">
<tr>
<td><input type="text" name="nameTxt" style="width:100%"/></td>
<td><input type="text" name="positionTxt" style="width:100%"/></td>
<td><input type="text" name="salaryTxt" style="width:100%"/></td>
</tr>
</tbody>
<tbody name="tableBody" value="5">
<tr>
<td><input type="text" name="nameTxt" style="width:100%"/></td>
<td><input type="text" name="positionTxt" style="width:100%"/></td>
<td><input type="text" name="salaryTxt" style="width:100%"/></td>
</tr>
</tbody>
</table>
<br/>
<input type="submit" value="Submit">
</form>
</body>
</html>
As you can see, I have wrapped every row with a <tbody>. The value attribute of the <tbody> will contain the employee id.
Once the form is submitted, the below servlet will capture it.
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class EmployeeSampleServlet extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String[]empId = request.getParameterValues("tableBody");
for(int i=0;i<empId.length;i++)
{
out.println(empId[i]);
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* #return a String containing servlet description
*/
#Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
What I was trying is get the value attribute of <tbody> (so I can identify the id of the employee) and get the data inside that <tbody>. However this didn't work, because I ended up with NullpointerException because it failed to read the <tbody> value.
So, how can I pass the data from table to servlet where it can clearly understand that one row is representing data belong to a one employee? If this is not the way to do it, I am also open for other methods.

That is obviously not going to work as only the input field values are submitted to the server.
You will need to discriminate the names of each input field in some way as currently you cannot match these to individual employees:
I assume you generate the table from some kind of list of employees so you could do this something like below:
<tr>
<td><input type="text" name="nameTxt_${employee.employeeId}" style="width:100%"/></td>
<td><input type="text" name="positionTxt_${employee.employeeId}" style="width:100%"/></td>
<td><input type="text" name="salaryTxt_${employee.employeeId}" style="width:100%"/></td>
</tr>
Now instead of receiving a bunch of random parameters 'nameTxt' etc., you reeive 'nameText_21', 'salaryText_21' etc. and have a means to identify the input with an employee. How you do this will depend on whether you have the list of Employees available in the Servlet on form submission.
e.g.
//employees = load the same list originally loaded for edit
for(Employee e : employees){
e.setSalary(Double.parseDouble(request.getParameter("salaryTxt_" + e.getid())));
}
Otherwise you will need to iterate the parameters for some field and proceed that way.
for(String s: request.getParameterNames()){
if(s.startsWith("nameTxt")){
//extract suffix
//load the employee with corresponding ID
//get the other params with same id
}
}

Look the below HTML, this will get all the table row-wise value and convert that as a json array. Now you can pass this array to servlet via ajax.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Sample</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
</head>
<body>
<table border="1" id="mytable" border="1" >
<thead>
<th>Name</th>
<th>Position</th>
<th>Salary</th>
</thead>
<tbody>
<tr>
<td><input type="text" name="nameTxt" value="12" /></td>
<td><input type="text" name="positionTxt" value="13" /></td>
<td><input type="text" name="salaryTxt" value="14" /></td>
</tr>
<tr>
<td><input type="text" name="nameTxt" value="21" /></td>
<td><input type="text" name="positionTxt" value="22" /></td>
<td><input type="text" name="salaryTxt" value="23" /></td>
</tr>
<tr>
<td><input type="text" name="nameTxt" value="31" /></td>
<td><input type="text" name="positionTxt" value="32" /></td>
<td><input type="text" name="salaryTxt" value="33" /></td>
</tr>
<tr>
<td><input type="text" name="nameTxt" value="41" /></td>
<td><input type="text" name="positionTxt" value="42" /></td>
<td><input type="text" name="salaryTxt" value="43" /></td>
</tr>
<tr>
<td><input type="text" name="nameTxt" value="51" /></td>
<td><input type="text" name="positionTxt" value="52" /></td>
<td><input type="text" name="salaryTxt" value="53" /></td>
</tr>
</tbody>
</table>
<br/>
<input type="button" value="Submit" onclick="convertValuesToJson();">
</body>
</html>
And you script looks like,
<script>
function convertValuesToJson(){
var myStringArray = [];
// Iterate each row
$('#mytable tbody tr').each(function() {
var myObject = new Object();
myObject.name = $(this).find("input[name='nameTxt']").val();
myObject.position = $(this).find("input[name='positionTxt']").val();
myObject.salary = $(this).find("input[name='salaryTxt']").val();
myStringArray.push(JSON.stringify(myObject));
});
// function for ajax goes here...
jQuery.ajax({
url: "ServletURL",
type : 'POST',
dataType: "json",
data : {"myData" : myStringArray},
error : function(jqXHR, textStatus, errorThrown) {
alert("error occurred");
}
});
}
</script>
See my updated Demo

Related

how to set each row to pass its values to servlet - whatever input I click, I have always first row

Why I can only count value for first row, though Jsp displays every row with correct values.
It always pass first row of data to the Servlet. If I choose first row it works, but if I choose any other it takes values of first row and program collapse due to empty string.
#Override
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws
ServletException, IOException {
PrintWriter printWriter = response.getWriter();
String currency = request.getParameter("currency");
int id = Integer.parseInt(request.getParameter("id"));
float rates = Float.parseFloat(request.getParameter("rates"));
float amount =
Float.parseFloat(request.getParameter("amount"));;
float euro = amount * rates;
printWriter.append(String.valueOf(id)).append(" : ");
printWriter.append(currency).append(" - ");
printWriter.append("rate : ").append(String.valueOf(rates));
printWriter.append(" ---> You have got
").append(String.valueOf(euro)).append("
Euros");
}
<form action="/exchangeServlet" method="post">
<table border="1">
<tr>
<th>Currency</th>
<th>Rate</th>
<th>Amount</th>
<th>Action</th>
</tr>
<c:forEach var="tempValue" items="${kalkulatorList}"
varStatus="counter">
<tr>
<input type="hidden" name="id" value="${tempValue.id}">
<td><input type="hidden" name="currency"
value="${tempValue.currency}">${tempValue.currency}</td>
<td><input type="hidden" name="rates"
value="${tempValue.rates}">${tempValue.rates}</td>
<td><input type="number" name="amount" placeholder="enter
amount"/></td>
<td><input type="submit" value="Exchange"></td>
</tr>
</c:forEach>
</table>
</form>
JSP view after loaded data from a xml file:
<tr>
<td><input type="hidden" name="currency"
value="USD">USD</td>
<td><input type="hidden" name="rates"
value="1.0067">1.0067</td>
<td><input type="number" name="amount" value="0.0"
placeholder="enter amount"/></td>
<td><a href="/exchangeServlet?
command=Exchange&currencyId=2">Exchange</a></td>
</tr>
<tr>
<td><input type="hidden" name="currency"
value="JPY">JPY</td>
<td><input type="hidden" name="rates"
value="138.02">138.02</td>
<td><input type="number" name="amount" value="0.0"
placeholder="enter amount"/></td>
<td><a href="/exchangeServlet?
command=Exchange&currencyId=3">Exchange</a></td>
</tr>
<tr>
<td><input type="hidden" name="currency"
value="BGN">BGN</td>
<td><input type="hidden" name="rates"
value="1.9558">1.9558</td>
<td><input type="number" name="amount" value="0.0"
placeholder="enter amount"/></td>
<td><a href="/exchangeServlet?
command=Exchange&currencyId=4">Exchange</a></td>
</tr>

Error while calling servlet from html form getting class not found

I want save the user data to my database in my dynamic web application , Im using hibernate to save into db, i have the registration page(signup.html) with so many fields and in form action="rs" which is RegisterServlete, but i dont know why im getting this error
HTML :
signup.html
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h1 align="center">REGISTER</h1>
<form action="rs" method="post">
<table>
<!----- First Name ---------------------------------------------------------->
<tr>
<td>FIRST NAME</td>
<td><input type="text" name="First_Name" maxlength="30" /> (max
30 characters a-z and A-Z)</td>
</tr>
<!----- Last Name ---------------------------------------------------------->
<tr>
<td>LAST NAME</td>
<td><input type="text" name="Last_Name" maxlength="30" /> (max
30 characters a-z and A-Z)</td>
</tr>
<!----- Date Of Birth -------------------------------------------------------->
<tr>
<td>AGE</td>
<td><input type="number" name="age" maxlength="10" /></td>
</tr>
<!----- Email Id ---------------------------------------------------------->
<tr>
<td>EMAIL ID</td>
<td><input type="text" name="Email_Id" maxlength="100" /></td>
</tr>
<!----- Mobile Number ---------------------------------------------------------->
<tr>
<td>MOBILE NUMBER</td>
<td><input type="text" name="Mobile_Number" maxlength="10" />
(10 digit number)</td>
</tr>
<!----- Gender ----------------------------------------------------------->
<tr>
<td>GENDER</td>
<td>Male <input type="radio" name="Gender" value="Male" />
Female <input type="radio" name="Gender" value="Female" />
</td>
</tr>
<!----- Address ---------------------------------------------------------->
<!----- City ---------------------------------------------------------->
<tr>
<td>CITY</td>
<td><input type="text" name="City" maxlength="30" /> (max 30
characters a-z and A-Z)</td>
</tr>
<!----- Pin Code ---------------------------------------------------------->
<tr>
<td>PIN CODE</td>
<td><input type="text" name="Pin_Code" maxlength="6" /> (6
digit number)</td>
</tr>
<!----- State ---------------------------------------------------------->
<tr>
<td>STATE</td>
<td><input type="text" name="State" maxlength="30" /> (max 30
characters a-z and A-Z)</td>
</tr>
<!----- Country ---------------------------------------------------------->
<tr>
<td>COUNTRY</td>
<td><input type="text" name="Country" value="India"
readonly="readonly" /></td>
</tr>
<tr>
<td>PASSWORD</td>
<td><input type="password" name="Password" maxlength="30"
min="8" /></td>
</tr>
<tr>
<td>CONFIRM PASSWORD</td>
<td><input type="password" name="Con_password" maxlength="30"
min="8" /></td>
</tr>
<!----- Submit and Reset ------------------------------------------------->
<tr>
<td colspan="2" align="center"><input type="submit"
value="SIGN UP"></td>
</tr>
</table>
</form>
</body>
</html>
Java :
RegisterServlet.java
`package com.train.seat.exchange;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.train.seat.exchange.dao.UserDAO;
import com.train.seat.exchange.dto.UserDTO;
public class RegisterServlet extends HttpServlet {
public RegisterServlet() {
System.out.println("RegisterServlet started");
}
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
UserDTO user = new UserDTO();
user.setfName(req.getParameter("First_Name"));
user.setlName(req.getParameter("Last_Name"));
user.setAge(Integer.parseInt("age"));
user.setEmail(req.getParameter("Email_Id"));
user.setMobileNum(Long.parseLong("Mobile_Number"));
user.setGender(req.getParameter("Gender"));
user.setCity(req.getParameter("City"));
user.setState(req.getParameter("State"));
user.setPinCode(Integer.parseInt("Pin_Code"));
user.setCountry(req.getParameter("Country"));
user.setPassword(req.getParameter("Password"));
HttpSession session = req.getSession(true);
UserDAO userdao = new UserDAO();
userdao.registeruser(user);
resp.sendRedirect("login.html");
}
}`
web.xml :
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<display-name>TrainSeatExchange</display-name>
<welcome-file-list>
<welcome-file>signup.html</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>RegisterServlet</servlet-name>
<servlet-class>com.train.seat.exchange.RegisterServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>RegisterServlet</servlet-name>
<url-pattern>/rs</url-pattern>
</servlet-mapping>
</web-app>
here is my error :
here is project structure

Spring MVC/Hibernate/MySQL 400 Bad Request Error

I'm building a blog in Java using Spring and Hibernate. I can't seem to figure out what is going on but I keep running into a Bad Request error when I try to add (save) a post and I can't figure out where I am wrong in my mapping.
Error message:
Controller:
#Controller
#RequestMapping("/blog")
public class IndexController {
#Autowired
private PostService postService;
#RequestMapping("/list")
public String showPage (Model theModel) {
// get posts from DAO
List<Post> thePosts = postService.getAllPosts();
// add the posts to the model
theModel.addAttribute("allPosts", thePosts);
return "allPosts";
}
#GetMapping("/showFormForAdd")
public String showFormForAdd(Model theModel) {
//create model attribute to bind form data
Post thePost = new Post();
theModel.addAttribute("post", thePost);
return "postSuccess";
}
#PostMapping("/savePost")
public String savePost(#ModelAttribute("post") Post thePost) {
// save the post using our service
postService.savePost(thePost);
return "allPosts";
}
Form snippet:
<div class="table" id="container">
<form:form action="savePost" modelAttribute="post"
method="POST">
<table>
<tbody>
<tr>
<td><label>Title:</label></td>
<td><form:input path="title" /></td>
</tr>
<tr>
<td><label>Author:</label></td>
<td><form:input path="author" /></td>
</tr>
<tr>
<td><label>Date:</label></td>
<td><form:input path="date" /></td>
</tr>
<tr>
<td><label>Post:</label></td>
<td><form:input path="post" /></td>
</tr>
<tr>
<td><label></label></td>
<td><input type="submit" value="Save"></td>
</tr>
</tbody>
</table>
</form:form>
<div style="clear: both;"></div>
<p>
Back to Home Page
</p>
</div>
All other pages are working correctly so far, just can't add an actual blog post. Any help is greatly appreciated.
I figured this out and it is similar to another spring issue I had in the past.
I don't think this really follows a lot of conventional function/design theory, but I added some code into the controller and it now works. I can add a post easily.
First thing was, I removed the #ModelAttribute tag from my "savePost" method. Then I added #RequestParam to my method parameters. Added a little bit of logic and now it saves to the database and then appears on the blog. Good stuff.
Code:
#PostMapping("/savePost")
public String savePost(#RequestParam("author") String author,
#RequestParam("title") String title, #RequestParam("date") String date,
#RequestParam("post") String post) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date theDate = sdf.parse(date);
// save the customer using our service
Post thePost = new Post();
thePost.setAuthor(author);
thePost.setDate(theDate);
thePost.setTitle(title);
thePost.setPost(post);
postService.addPost(thePost);
System.out.println(thePost.toString()); //testing
return "success";
}
jsp:
<form:form action="savePost" modelAttribute="post" method="POST">
<table>
<tbody>
<tr>
<td><label>Title:</label></td>
<td><input id="title" type="text" name="title"></td>
</tr>
<tr>
<td><label>Author:</label></td>
<td><input id="author" type="text" name="author"></td>
</tr>
<tr>
<td><label>Date:</label></td>
<td><input id="date" type="text" name="date"></td>
</tr>
<tr>
<td><label>Post:</label></td>
<td><textarea id="post" type="text"
name="post"></textarea></td>
</tr>
<tr>
<td><label></label></td>
<td><input type="submit" value="Save"></td>
</tr>
</tbody>
</table>
</form:form>

Thymeleaf Map Form Binding

db.html
<div th:each="pr, stat: *{mergeMap}">
<tr>
<td><input type="text" name="key" th:value="${pr.key}" /></td>
<td><input type="text" name="value" th:value="${pr.value}" /></td>
</tr>
</div>
On submitting this input, i always get mergeMap to be empty at the Spring Controller. What should be done to get the value of mergeMap?
Controller.java
#RequestMapping(value = "/shot")
public String saveMergeProducts(#ModelAttribute(value="prod") MergedProductInfoDTO prod, BindingResult bindingResult,
Model model, HttpServletRequest request) {
System.out.println(prod.toString());
return "forward:/backoffice/db";
}
HTML
<form action="#" th:action="#{shot}" method="POST" th:object="${prod}">
<tr>
<td><span th:text="${index.index}"></span></td>
<td><input type="text" name="id" th:value="*{id}" th:readonly="readonly" /></td>
<td><input type="text" name="categoryName" th:value="*{categoryName}" th:readonly="readonly" /></td>
<td><input type="text" name="subCategoryName" th:value="*{subCategoryName}" th:readonly="readonly" /></td>
<td><input type="text" name="productBrand" th:value="*{productBrand}" /></td>
<td><input type="text" name="productSubBrand" th:value="*{productSubBrand}" /></td>
<td><input type="text" name="series" th:value="*{series}" /></td>
<td><input type="text" name="model" th:value="*{model}" /></td>
</tr>
<tr>
<td colspan="7">
<tr>
<th>KEY</th>
<th>VALUE</th>
</tr>
<div th:each="pr, stat: *{mergeMap}">
<tr>
<td><input type="text" name="mergeMapKey" th:value="${pr.key}" /></td>
<td><input type="text" name="mergeMapValue" th:value="${pr.value}" /></td>
</tr>
</div>
</table>
</td>
<td><input type="text" name="tags" th:value="*{tags}" /></td>
<td><input type="submit" value="Submit" /></td>
</tr>
To access the Map property of the form-backing bean, use the __${...}__ preprocessor
<div th:each="pr, stat: *{mergeMap}">
<tr>
<td><input type="text" name="value" th:value="${pr.key}" readonly="true"/></td>
<td><input type="text" name="value" th:field="*{mergeMap[__${pr.key}__]}"/></td>
</tr>
</div>
What it does it evaluates the inner expression first before evaluating the whole expression. Note that in this case, ${pr.key} should not be modified so that the update will be reflected to the map property of the bean bound to the form.
Reference : http://www.thymeleaf.org/doc/tutorials/2.1/thymeleafspring.html#dynamic-fields

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