Pre-populate the Form field by formBackingObject method using standard html code in spring web - spring

I just trying to pre-populate the form field in user form by formBackingObject.
I am using simple html code not spring tags to create the field.
Actually I'v tried with spring tag but spring tags for input filed is not working so I moved to simple html code but spring tags works for <form:form action=**> but not for <form:input path="name" />
I'v check taglib import segment but its fine and I don't understand if <form:form />
is working then why <form:input path="name" /> is not working.
I'm describing this because somewhere and someone from StackOverflow said that for getting benefit of formBackingObject, I'v to use spring tags for input field but in my case its not working.
Here I'm considering of formBackingObject only for pre-populating form field that what my question title suggest. Anyhow I'v to do it soon.
I'v gone through about 30-40 page link for finding of this solution but .....
I need a very simple example of it where jsp field getting value of object that is return by formBackingObject
I'm not familiar with annotation
Here is my tried and failed example
contact_form.jsp
<form:form action="edit.htm" commandName="contact" method="POST">
Name:<input type="text" name="name" value=${contact.name} /><br>
Address:<input type="text" name="address" value=${contact.address}/><br>
<input type="submit" value="Submit"/><br>
EditController
public class EditController extends SimpleFormController {
private static Contact cont = new Contact();
static {
cont.setAddress("aaa");
cont.setName("bbb");
}
#Override
protected void doSubmitAction(Object command) throws Exception {
System.out.println("In do submit method");
}
#Override
protected Object formBackingObject(HttpServletRequest request)
throws Exception {
System.out.println("In FormBackingObject");
return cont;
}
spring-servlet.xml
<bean id="/edit.htm" class="tryPack7.EditController">
<property name="CommandClass" value="tryPack7.Contact" />
<property name="commandName" value="contact" />
<property name="formView" value="contact_form" />
<property name="successView" value="success" />
</bean>
Thanks in advance

Assuming you have specified handler mapping in your confog xml file:
Make sure you have jsp on similar lines as below:
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<html>
<head>
<title>Sample Page</title>
</head>
<body>
<form:form commandName="contact" method="POST">
<table>
<tr >
<td>Name:<form:input path="name"/></td>
</tr>
<tr >
<td>Address:<form:input path="address"/></td>
</tr>
<tr>
<td colspan="3"><input type="submit"/></td>
</tr>
</table>
</form:form>
</body>
</html>
Also, rather than using static way, I would suggest to initialize contact form in formBackingObject as shown below:
public class EditController extends SimpleFormController {
public ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
Contact contact=(Contact)formBackingObject(request);
return new ModelAndView("contact_form","contact",contact);
}
public Object formBackingObject(HttpServletRequest req)
{
Contact contact = new Contact();
contact.setAddress("aaa");
contact.setName("bbb");
return contact;
}
}

Related

Why do am I getting error "java.lang.IllegalStateException" after putting <form:form> tag in jsp file of spring?

I have 2 tables, city and hotel_details in my database. I am trying to fetch the data from these tables and populating inside a form for registering the customer. But I am getting "java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'command' available as request attribute" as error.
JSP file
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<head>
<title>Search Hotels</title>
</head>
<body>
<h4>Search Hotels</h4>
<form:form action="search">
<table>
<tr>
<td>City:</td>
<td>
<form:select path="cities">
<form:options items="${cities}" />
</form:select>
</td>
</tr>
<tr>
<td>Hotel:</td>
<td>
<form:select path="hotels">
<form:options items="${hotels}" />
</form:select>
</td>
</tr>
<tr>
<td>Date:</td>
<td>
<input type="date" id="date" name="date">
</td>
</tr>
<tr>
<td colspan="3">
<input type="submit" value="Check Availability">
</td>
</tr>
</table>
</form:form>
Controller
#Controller
public class HomeController {
//need a controller method to show the initial HTML form
#Autowired(required=true)
private CityDAO cityDAO;
#Autowired(required=true)
private HotelDetailsDAO hotelDetailsDAO;
#RequestMapping("/")
public String showCheckAvailablityForm(Model theModel) {
// get customers from the dao
//List<City> theCities = cityDAO.getCities();
List<String> theCities = cityDAO.getCities();
Set<String> theHotels = hotelDetailsDAO.getHotels();
// add the customers to the model
theModel.addAttribute("cities", theCities);
theModel.addAttribute("hotels", theHotels);
//printing the data fetched
System.out.println("In HomeController showCheckAvailability method where city name is being fetched from city table");
theCities.forEach((n) -> System.out.println(n));
System.out.println("printing hotels");
for (String temp : theHotels) {
System.out.print(temp + " ");
}
return "checkAvailability-form";
}
#RequestMapping("/search")
public String searchResult(#RequestParam("cityName") String theCityName, #RequestParam("hotelName") String theHotelName,Model model) {
System.out.println("processed successfully");
return null;
}
}
When you use <form:form> attribute, it requires you to specify model object that should be bound to form tag. If you don't specify any model attribute default name is used as command.
Following is the description of form:form tag from spring-form.tld -
<attribute>
<description>Name of the model attribute under which the form object is exposed.
Defaults to 'command'.</description>
<name>modelAttribute</name>
<required>false</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
<attribute>
<description>Name of the model attribute under which the form object is exposed.
Defaults to 'command'.</description>
<name>commandName</name>
<required>false</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
As you don't have any model object bound to form, try removing form:form tag and use HTML form tag and also make sure you match input parameter names with method parameter names. i.e -
<form action="search">
...
</form>

Spring MVC: Url path appending when posting the form

i am new to spring mvc. i created a simple login application. but in my case the first time the for posting url and calling controller method correctly. in second time it's appending path with one more time of controller. first time post:
//localhost:8090/springmvc/account/login secong time in same page: //localhost:8090/springmvc/account/account/login. how do i fix this redirecting problem?
this my controller page:
#Controller
#RequestMapping("account")
public class AccountController {
AccountService service = new AccountService();
#RequestMapping(value = "account/default", method = RequestMethod.GET)
public ModelAndView RegisterUser() {
return new ModelAndView("/Account/Index","command",new User());
}
#RequestMapping(value = "/registeruser", method = RequestMethod.POST)
public ModelAndView RegisterUser(User user) {
user.setMessage(service.Register(user));
return new ModelAndView("/Account/Index", "command", user);
}
#RequestMapping(value = "/register", method = RequestMethod.POST)
public ModelAndView RegisterUer(User user) {
user.setMessage(service.Register(user));
return new ModelAndView("/Account/create", "command", user);
}
#RequestMapping(value = "/login", method = RequestMethod.POST)
public ModelAndView LoginUser(User user, ModelMap model) {
String msg = service.isAuthendicated(user) ? "Logged in" : "Failed";
user.setMessage(msg);
return new ModelAndView("/Account/Index", "command", user);
}
}
this my jsp page:
<%#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"%>
<%#taglib prefix="t" tagdir="/WEB-INF/tags"%>
<t:genericpage>
<jsp:body>
<h2>Login</h2>
<div>
${command.message} </div>
Register
<form:form action="account/login" method="post">
<div>
<form:input path="username" />
</div>
<div>
<form:input path="password" />
</div>
<input type="submit" value="Login">
</form:form>
</jsp:body>
</t:genericpage>
i used the tag library for common page:
<%#tag description="Master Page" pageEncoding="UTF-8"%>
<html>
<body>
<div id="pageheader">
<h2>WElcome</h2>
</div>
<div id="body">
<jsp:doBody />
</div>
<div id="pagefooter">
<p id="copyright">Copyright</p>
</div>
</body>
</html>
Depending on which version of Spring you're using, here are some options:
Spring 3.1 and lower OR Spring 3.2.3 and higher
You should have your urls/actions root-relative specific to your context path.
<form:form action="${pageContext.request.contextPath}/account/login" method="post">
Note: Spring 3.2.3 introduced servletRelativeAction but I've never used it.
Spring 3.2
Don't do anything, context path is prepended - this was actually a breaking change and eventually rolled back.
<form:form action="/account/login" method="post">
//will produce action="/springmvc/account/login"
Start your form action with a /.
<form:form action="/account/login" method="post">
By not doing it, you're telling the browser to append the action to the already existing URL on the address bar.
And where you have such links directly in HTML (by not using Spring's form:form), try to use c:url to properly construct the URL including the context path etc. This takes a lot of pain away from building proper relative URLs.
Register
Use ../ to get URL of your current context root:
<form:form action="../account/login" method="post">
from here
I tried with the spring tag bysetting only the relative path, it appends automatically the context path like:
<!DOCTYPE html>
<%# taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<html lang="en">
<head>
<!-- ... -->
<spring:url value="/account/login" var="loginUrl" />
<form:form action="${loginUrl}" method="post">
The context path is set in application.properties as bellow:
server.servlet.contextPath=/MyApp
In the jsp page, it produces:
<a class="nav-link" href="/MyApp/account/login"> <i class="fas fa-play"></i> <span>Click here</span></a>

The request sent by the client was syntactically incorrect, Spring with Hibernate Annotations

I searched everywhere for this error and looked through every single thread here with the same title, changed a lot in my code but still, the error is there.
it says:
HTTP Status 400 -
type Status report
message
description The request sent by the client was syntactically incorrect.
Apache Tomcat/7.0.35
My Controller code is:
#RequestMapping(value = "/manageInventory.htm", method = RequestMethod.GET)
public ModelAndView manageInventory(HttpSession session) {
ArrayList<Product> products = new ArrayList<Product>();
Manufacturer manufacturer = (Manufacturer) manufacturerDAO
.getByUsername(((UserAccount) session.getAttribute("user"))
.getUsername());
products = productDAO.getProductListByManufacturer(manufacturer
.getManufacturerName());
System.out.print(products.get(0).getProductName());
ModelAndView view = new ModelAndView("manageInventory");
view.addObject("products", products);
InventoryItem inventoryItem = new InventoryItem();
view.addObject("inventoryItem", inventoryItem);
return view;
}
#RequestMapping(value = "/manufacture.htm", method = RequestMethod.POST)
public ModelAndView manufactureProduct(HttpSession session, BindingResult result,
#ModelAttribute("inventoryItem") #Valid InventoryItem inventoryItem) {
System.out.print(result.getErrorCount()+" "+result.getAllErrors());
ModelAndView view = null;
if(!result.hasErrors())
{
Manufacturer manufacturer = manufacturerDAO
.getByUsername(((UserAccount) (session.getAttribute("user")))
.getUsername());
inventoryItem.setAvailability(true);
inventoryItem.setManufacturer(manufacturer);
manufacturer.getInventory().add(inventoryItem);
manufacturerDAO.update(manufacturer);
view = new ModelAndView("done");
}
else
{
view = new ModelAndView("manageInventory");
}
return view;
}
The first method adds inventoryItem into the model and I am fetching that for validations afterwards.
I am using tiles so,My tile for this is:
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<body>
<h2>Add Inventory</h2>
<br />
<form:form modelAttribute="inventoryItem" action="manufacture.htm" method="post">
<table>
<tr>
<td>Select Product:</td>
<td><form:select path="product">
<c:forEach var="product" items="${products}">
<form:option value="${product}">${product.productName}</form:option>
</c:forEach>
</form:select></td>
<td>Select Quantity:</td>
<td>
<form:input path="quantity" placeholder="Quantity"/><br />
<font color="red"><form:errors path="quantity"/> </font>
</td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="Manufacture">
</td>
</tr>
</table>
</form:form>
</body>
My POJO has the following validation:
#NotNull
private int quantity;
Please help. Thanks in advance.
I forgot to add HttpServletRequest request to the method input parameters.
I added it and it stared working. strange, but worked. :)

How to reject a field from bean for validation when binding?

I have three fields department_Id,department_Name,department_location in departmentForm act as a model object in this model form.
I have use annotation to validate the fields. Now, I want to only use two fields in different jsp page say create.jsp and one field in different jsp page say getDepartmentById.
When I press submit button of create.jsp, validation is happening but after providing correct information its not submitted cause in this page.
I haven't give one field department_Id which is auto generated by my DAO layer. So, please help me, how to reject this value to execute my create.jsp page for successfully creating department in database.
When I printed the BindingResult object, it shown as follow:
Field error in object 'departmentForm' on field 'departmentId': rejected value [null];
codes [NotEmpty.departmentForm.departmentId,NotEmpty.departmentId,NotEmpty.java.lang.String,NotEmpty];
arguments [org.springframework.context.support.DefaultMessageSourceResolvable:
codes [departmentForm.departmentId,departmentId]; arguments [];
default message [departmentId],org.hibernate.validator.constraints.NotEmpty.message},
[Ljava.lang.Class;#4fc4a198,[Ljava.lang.Class;#764d2b11];
default message [may not be empty]`
This is how I coded in controller:
#RequestMapping(value = "/createDepartment", method = RequestMethod.POST)
public String createEmployee(#Valid DepartmentForm departmentForm,
BindingResult bindingResult, Map<String, DepartmentForm> model)
throws Exception {
if (bindingResult.hasErrors()) {
System.out.println(bindingResult);
bindingResult.reject(departmentForm.getDepartmentId());
return "departmentForm";
}
System.out.println("mr ankur jadiy");
model.put("departmentForm", departmentForm);
departmentForm.setUpdateStatus('A');
if (departmentForm.getUpdateStatus() == 'A') {
departmentServiceImpl
.actionDecider(convertDeptFormToDeptBO(departmentForm));
}
return "Success";
}
my DepartmentForm code is as follow:
package com.nousinfo.tutorial.model;
import javax.validation.constraints.Size;
import org.hibernate.validator.constraints.NotEmpty;
public class DepartmentForm {
#NotEmpty
#Size(min = 1, max = 20,message="")
private String departmentId;
#NotEmpty
private String departmentName;
private String departmentLocation;
private Character updateStatus;
public String getDepartmentId() {
return departmentId;
}
public void setDepartmentId(String departmentId) {
this.departmentId = departmentId;
}
public String getDepartmentName() {
return departmentName;
}
public void setDepartmentName(String departmentName) {
this.departmentName = departmentName;
}
public String getDepartmentLocation() {
return departmentLocation;
}
public void setDepartmentLocation(String departmentLocation) {
this.departmentLocation = departmentLocation;
}
public Character getUpdateStatus() {
return updateStatus;
}
public void setUpdateStatus(Character updateStatus) {
this.updateStatus = updateStatus;
}
}
and my create.jsp is
<%# page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%# taglib uri="http://jakarta.apache.org/taglibs/input-1.0" prefix="input"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%# taglib uri="http://www.springframework.org/tags" prefix="s"%>
<%# 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>Create Department</title>
<link rel="stylesheet" href="css/style.css" type="text/css"></link>
</head>
<body>
<table width="1254" height="74" border="0" align="center">
<tr>
<td width="300" height="68" align="center" bgcolor="#99CCFF"><h2>
<span class="style1">Employee Details </span>
</h2></td>
<td width="100" height="68" align="center" bgcolor="#FFFFFF"><img
src="./image/emps.jpg" width="190" height="92" /></td>
</tr>
</table>
<p>
<br />
</p>
<hr size="1" width="786">
<form:form id="form" method="post" action="/EmployeeWebSpring/departmentController/createDepartment"
modelAttribute="departmentForm">
<table>
<tr>
<form:hidden path="updateStatus" />
</tr>
<tr>
<td>
Department_Name:
<font color="red"><form:errors path="departmentName" /></font>
</td>
</tr>
<tr>
<td><form:input path="departmentName" /></td>
</tr>
<tr>
<td>
Department_Location:
<font color="red"><form:errors path="departmentLocation" /></font>
</td>
</tr>
<tr>
<td><form:input path="departmentLocation" /></td>
</tr>
</table>
<br>
<br />
<p> </p>
<br>
<tr>
<td><input type="submit" name="method" value="save" /></td>
<td><input type="submit" name="method" value="cancel" /></td>
</tr>
<hr size="1" width="786">
<p> </p>
</form:form>
</body>
</html>
What the error says is that you're missing value for departmentId, which is not surprising since you defined it as
#NotEmpty
#Size(min = 1, max = 20,message="")
You don't really need to validate departmentId if it's autogenerated by your code. You probably should remove it from the DepartmentForm, especially since it's not in the form, or at least make it optional.
You can make it mandatory in your business object, but the form backing object should reflect what's in the form.
update
If departmentId is a database-generated id, you should set it as disallowed in your controller's InitBinder:
#InitBinder
public void initBinder(WebDataBinder binder) {
binder.setDisallowedFields(new String[] { "departmentId" });
}

Unable load dropdown list when the page was loading in spring mvc

I trying to populate the dropdown list when page was loaded.But it is not loaded in UserPage.jsp from Controller.on submit method and also wrote referencedata method.
Controller:-
public ModelAndView onSubmit(HttpServletRequest request,
HttpServletResponse response, Object command, BindException errors)
throws Exception {
log.info("onSubmit handleRequest method"
+ request.getParameter("username"));
System.out.println("onSubmit handleRequest method"
+ request.getParameter("username"));
String username = "", password = "";
username = request.getParameter("username");
password = request.getParameter("password");
UserBean ubean = null;
System.out.println("After shownform method called");
HttpSession session = request.getSession(true);
try {
ubean = userservice.chkUsername(username, password);
System.out.println("Information" + ubean.getUsername());
} catch (DataException ex) {
ex.printStackTrace();
// throw ex;
}
session.setAttribute("User", ubean);
EmpPersonalBean personalBean = new EmpPersonalBean();
return new ModelAndView("jsp/UserPage", "EmpPersonalBean", personalBean);
}
protected Map referenceData(HttpServletRequest request) throws Exception {
log.info("UserDBBoardController======================referenceData");
Map referenceData = new HashMap();
List deparementList = new ArrayList();
deparementList = userservice.getDeparmentList();
referenceData.put("deparmentList", deparementList);
return referenceData;
}
UserPage.jsp
<%# page language="java" import="com.aims.bean.*,java.util.HashMap" contentType="text/html;charset=utf-8" pageEncoding="UTF-8"%>
<%#taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<%#taglib uri="http://www.springframework.org/tags" prefix="spring" %>
<%#taglib uri="/WEB-INF/tld/c.tld" prefix="c" %>
<html>
<head>
<title>AAI</title>
</head>
<body>
<form:form method="post" modelAttribute="EmpPersonalBean" action="userpage.htm">
<table>
<tr>
<td>Welcome <%=((UserBean)session.getAttribute("User")).getUsername()%></td>
</tr>
<tr>
<td>Department</td>
<td><form:select path="deparment">
<form:option value="NONE" label="--- Select ---" />
<form:options items="${deparmentList}" />
</form:select>
</td>
</tr>
</tr>
</table>
</form:form>
</body>
</html>
public class DepartmentBean {
private String deptcode,deptname;
public String getDeptcode() {
return deptcode;
}
public void setDeptcode(String deptcode) {
this.deptcode = deptcode;
}
public String getDeptname() {
return deptname;
}
public void setDeptname(String deptname) {
this.deptname = deptname;
}
}
And also attached displaying dropdown list in the userpage.sjp
Please help me.How to resolve the issue.
You also need to specify itemLabel and itemValue attributes in <form:options/> tag.
UPDATE
Replace this line in your jsp page. I think it should resolve your problem.
<form:options items="${deparmentList}" itemLabel="deptname" itemValue="deptcode" />
Hope this helps you. Cheers.
<td>Department</td>
<td><form:select path="deparment">
<form:option value="NONE" label="--- Select ---" />
<c:forEach var="department" items="${deparmentList}">
<form:option value="${department}" label="${department}" />
</c:forEach>
</form:select>
</td>
ModelAndView mav = new ModelAndView("viewName");
mav.addObject("deparmentList", deparementList);
return mav;
return modelAndView object.

Resources