Implementing Forgot password in Spring giving garbage URL - spring

I am working on a Spring-MVC application. I want to implement the forgot password functionality. For that, I am using the secret question method. I have created a JSP page, where I recieve the values like username, secretanswer and then I check if the values exist and then save the new password which the user has given. I am having a problem wiht the JSP page, when I click submit, it shows me some garbage URL. I believe it is some tiny mistake, I am unable to see. Kindly let me know what is going wrong.
Apache tomcat error URL :
HTTP Status 404 - /id=0,%20username=null,%20password=null
Controller function for changing password :
#RequestMapping(value = "/forgotpassword")
public String forgotPassword(Model model){
model.addAttribute("person",new Person());
return "forgotpassword";
}
#RequestMapping(value = "/changepassword")
public String changepassword(#ModelAttribute("person") Person f,Model model){
System.out.println("Did we reach here on submit");
personService.checkAuthenticitiy(f.getUsername(), f.getSecretanswer(), f.getNewpassword());
model.addAttribute("person", new Person());
return "redirect:/forgotpassword";
}
JSP page :
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Forgot Passsword page</title>
</head>
<body>
<td><a href="<c:url value='/' />" >Go Home</a></td>
<h1>
Change password
</h1>
<c:url var="addAction" value="/changepassword" ></c:url>
<form:form action="${person}" commandName="person">
<table>
<tr>
<td>
<form:label path="username">
<spring:message text="username"/>
</form:label>
</td>
<td>
<form:input path="username" />
</td>
</tr>
<tr>
<td>
<form:label path="secretquestion" >
<spring:message text="secretquestion"/>
</form:label>
</td>
<td>
<form:input path="secretquestion"/>
</td>
</tr>
<tr>
<td>
<form:label path="secretanswer" >
<spring:message text="secretanswer"/>
</form:label>
</td>
<td>
<form:input path="secretanswer"/>
</td>
</tr>
<tr>
<td>
<form:label path="newpassword" >
<spring:message text="newpassword"/>
</form:label>
</td>
<td>
<form:input path="newpassword"/>
</td>
</tr>
<tr>
<td>
<input name="submit" type="submit" value="Submit" />
</td>
</tr>
</table>
</form:form>
</body>
</html>
Person model :
#Entity
#Table(name="person")
public class Person implements UserDetails{
#Column(name = "username")
private String username;
#Column(name = "password")
private String password;
#Column(name = "secretquestion")
private String secretquestion;
#Column(name = "secretanswer")
private String secretanswer;
#Transient
private String newpassword;
//Getters and setters for all.
}

<c:url var="addAction" value="/changepassword" ></c:url>
<form:form action="${person}" commandName="person">
should be
<c:url var="addAction" value="/changepassword" ></c:url>
<form:form action="${addAction}" commandName="person">
person is not your action

Related

Bad request error 400 when submitting a form

I am getting Error Response 400 when submitting the form. I have a form which was working fine before i added a drop down list which displays gender to the user from DB. The Drop down is displaying the data correctly but when i am submitting the form i am getting an error. This only happened when i added the drop down list.
RegistrationController.java :-
#Controller
public class RegistrationController {
final static Logger logger = Logger.getLogger(RegistrationController.class);
private StaffService staffService;
#Autowired
private GenderDao genderDao;
#Autowired
public RegistrationController(StaffService staffService) {
this.staffService = staffService;
}
#RequestMapping(method = RequestMethod.GET, value = "/register")
public String registerStaffPage(Model model) {
List<Gender> genders = genderDao.findAll();
Iterator<Gender> genderIterators = genders.iterator();
Map<Gender, String> genderMap = new LinkedHashMap<Gender, String>();
while (genderIterators.hasNext()) {
Gender gender = genderIterators.next();
genderMap.put(gender, gender.getGender());
}
model.addAttribute("gendersMap",genderMap);
model.addAttribute("staffRegistrationBean", new StaffRegistrationBean());
return "register";
}
#RequestMapping(method = RequestMethod.POST, value = "/registerStaff")
public String registerStaff(#ModelAttribute("staffRegistrationBean") StaffRegistrationBean staffRegistrationBean,
#Valid StaffRegistrationBean staffRegistrationBeans, Errors errors, Model model) {
// if (errors.hasErrors())
// return "register";
staffService.createStaff(staffRegistrationBean);
return "RegistrationDone";
}
#PostConstruct
public void init() {
logger.debug("RegistrationController Bean has been Initialized.");
}
#PreDestroy
public void destroy() {
logger.debug("RegistrationController Bean has been Destroyed.");
}
}
StaffRegistrationBean.java
public class StaffRegistrationBean {
private String userName;
private String password;
private String firstName;
private String lastName;
private String email;
private String Organization;
private String phoneNo;
private Gender gender;
// getter and setter follows
}
regsiter.jsp
<%# 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 prefix="spring" uri="http://www.springframework.org/tags"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%# page isELIgnored="false"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Registration</title>
</head>
<body>
<h1>Registration Form</h1>
<form:form id="regForm" modelAttribute="staffRegistrationBean"
action="registerStaff" method="post">
<table>
<tr>
<td><form:label path="userName" cssErrorClass="error">
<spring:message code="userName" /> :
</form:label> <form:input path="userName" name="username" id="username"
cssErrorClass="error" /></td>
</tr>
<tr>
<td>Gender: <form:select path="gender">
<form:options items="${gendersMap}" />
</form:select>
</td>
</tr>
<tr>
<td><form:label path="organization" cssErrorClass="error">
<spring:message code="organizationName" /> :
</form:label> <form:input path="organization" name="username" id="organization"
cssErrorClass="error" /></td>
</tr>
<tr>
<td><form:label path="password" cssErrorClass="error">
<spring:message code="password" /> :
</form:label> <form:input path="password" name="password" id="password"
cssErrorClass="error" /></td>
</tr>
<tr>
<td><form:label path="firstName" cssErrorClass="error">
<spring:message code="firstName" /> :
</form:label> <form:input path="firstName" name="firstname" id="firstname"
cssErrorClass="error" /></td>
</tr>
<tr>
<td><form:label path="lastName" cssErrorClass="error">
<spring:message code="lastName" /> :
</form:label> <form:input path="lastName" name="lastname" id="lastname"
cssErrorClass="error" /></td>
</tr>
<%-- <tr>
<td><form:label path="gender">
<spring:message code="gender" /> : </form:label>
<td><form:select path="${gender}">
<form:options items="${genderList}" id="id" itemValue="gender">
</form:options>
</form:select></td>
</tr> --%>
<tr>
<td><form:label path="email" cssErrorClass="error">
<spring:message code="email" /> :
</form:label> <form:input path="email" name="email" id="email"
cssErrorClass="error" /></td>
</tr>
<tr>
<td><form:label path="phoneNo" cssErrorClass="error">
<spring:message code="phoneNo" /> :
</form:label> <form:input path="phoneNo" name="phoneNo" id="phoneNo"
cssErrorClass="error" /></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="register"></td>
</tr>
</table>
</form:form>
</body>
</html>
**
Error :-
**
HTTP Status 400 – Bad Request
Type Status Report
Description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing).
GenderMap is a map that has the model to display on the screen. The key is Gender class and value is the gender description. The user will select a gender which will be referring to an id in the gender table.
The Entire code is available at - https://github.com/iftekharkhan09/ExpenseCalculator_Nex_Gen/tree/DevBranch
Go to the URL - localhost:8080/ExpenseCalculator/register
Any help will be highly appreciated.
As Razmin said, spring is trying to populate your ModelAttribute (which is of type StaffRegistrationBean) from the body of the POST request (automatically filled by the HTML form).
If you look at the POST request body you will see something like gender: 1. Spring cannot map this Integer to a Gender (even if this Integer simply refers to the id of your Gender..).
You will have to retrieve manually the Gender from your DB, and set it to your Model.
It happens when spring can't populate the ModelAttribute from HTML form.
staffRegistrationBean ModelAttribute can't convert Html's Gender attribute to your Gender object
It worked when enabled "Host" headers in postman

Spring MVC - Submit Form 400 Error

I'm just begin writing an application using Spring MVC. I have 2 entities, District & City. A City has many districts, and each district belongs to a city.
In district.jsp I declare a form, allowing user input of the district name and a selection box to choose the City it belongs to.
The District entity looks like this:
<form:form action="${aAction}" commandName="district">
<table>
<c:if test="${!empty district.districtName}">
<tr>
<td>
<form:label path="id">
<spring:message text="ID"/>
</form:label>
</td>
<td>
<form:input path="id" readonly="true" size="8" disabled="true" />
<form:hidden path="id" />
</td>
</tr>
</c:if>
<tr>
<td>
<form:label path="districtName">
<spring:message text="District Name"/>
</form:label>
</td>
<td>
<form:input path="districtName" />
</td>
</tr>
<tr>
<td>
<form:label path="belongToCity">
<spring:message text="Belong to City"/>
</form:label>
</td>
<td>
<c:if test="${!empty listCities}">
<form:select path="belongToCity" items="${listCities}" itemLabel="cityName" itemValue="id"></form:select>
</c:if>
</td>
</tr>
<tr>
<td colspan="2">
<c:if test="${!empty district.districtName}">
<input type="submit"
value="<spring:message text="Edit District"/>" />
</c:if>
<c:if test="${empty district.districtName}">
<input type="submit"
value="<spring:message text="Add District"/>" />
</c:if>
</td>
</tr>
</table>
</form:form>
In my district controller I declare add action.
#RequestMapping(value = {"/district/add"}, method = RequestMethod.POST)
public String addDistrict(#ModelAttribute("district") District p,Model model, BindingResult result) {
if(result.hasErrors()) {
return "district";
}
this.districtService.addDistrict(p);
return "district";
}
When I run my project, however, it shows a 400 error and the error message: "The request sent by the client was syntactically incorrect."
I suspect my form is wrong somewhere, maybe it is not able to post to controller processing. Could someone help me identify the issue?
Your BindingResult parameter should be adjacent to modelAttribute. Below should be method signature.
#RequestMapping(value = {"/district/add"}, method = RequestMethod.POST)
public String addDistrict(#ModelAttribute("district") District p, BindingResult result, Model model) {
if(result.hasErrors()) {
return "district";
}
this.districtService.addDistrict(p);
return "district";
}

Spring:Using Controller actions in one JSP file

I am working on a Spring-MVc project. I have a single JSP page, with two forms. Both these forms are handled by 2 different controllers, and they have separate database tables, seperate service methods. But I would like to individually select information(notes) which the user is adding and save them. I am posting both of my controller, JSP file, and the error message. Kindly let me know what might be going wrong. Thank you for your time.
PersonController :
#Controller
public class PersonController {
private PersonService personService;
#Autowired(required=true)
#Qualifier(value="personService")
public void setPersonService(PersonService ps){
this.personService = ps;
}
#RequestMapping(value = "/", method = RequestMethod.GET)
public String listPersons(Model model) {
model.addAttribute("person", new Person());
model.addAttribute("listPersons", this.personService.listPersons());
return "person";
}
//For add and update person both
#RequestMapping(value= "/person/add", method = RequestMethod.POST)
public String addPerson(#ModelAttribute("person") Person p){
//new person, add it
this.personService.addPerson(p);
return "redirect:/";
}
#RequestMapping("/remove/{id}")
public String removePerson(#PathVariable("id") String id){
this.personService.removePerson(id);
return "redirect:/persons";
}
#RequestMapping("/edit/{id}")
public String editPerson(#PathVariable("id") String id, Model model){
model.addAttribute("person", this.personService.getPersonById(id));
model.addAttribute("listPersons", this.personService.listPersons());
return "person";
}
}
keyactivitiesController.java
#Controller
public class KeyActivitiesController {
private KeyActivitiesService keyActivitiesService;
#Qualifier(value="keyActivitiesService")
public void setKeyActivitiesService(KeyActivitiesService keyActivitiesService){this.keyActivitiesService = keyActivitiesService;}
#RequestMapping(value = "/keynotice", method = RequestMethod.GET)
public String listNotices(Model model) {
model.addAttribute("keyactivities", new KeyActivities());
model.addAttribute("listNotices", this.keyActivitiesService.listNotices());
return "keyactivities";
}
//For add and update person both
#RequestMapping(value= "/keynotice/add", method = RequestMethod.POST)
public String addPerson(#ModelAttribute("keyactivities") KeyActivities p){
//new person, add it
this.keyActivitiesService.addKeyNotice(p);
return "redirect:/";
}
#RequestMapping("/removeNotice/{id}")
public String removePerson(#PathVariable("id") String id){
this.keyActivitiesService.removeNotice(id);
return "redirect:/";
}
#RequestMapping("/editNotice/{id}")
public String editPerson(#PathVariable("id") String id, Model model){
model.addAttribute("keyactivities", this.keyActivitiesService.getNoticenById(id));
model.addAttribute("keyactivities", this.keyActivitiesService.listNotices());
return "keyactivities";
}
}
person.jsp
<c:url var="addAction" value="/person/add" ></c:url>
<form:form action="${addAction}" commandName="person">
<table>
<c:if test="${!empty person.name}">
<tr>
<td>
<form:label path="id">
<spring:message text="ID"/>
</form:label>
</td>
<td>
<form:input path="id" readonly="true" size="8" disabled="true" />
<form:hidden path="id" />
</td>
</tr>
</c:if>
<tr>
<td>
<form:label path="name">
<spring:message text="Name"/>
</form:label>
</td>
<td>
<form:input path="name" />
</td>
</tr>
<tr>
<td colspan="1">
<c:if test="${!empty person.name}">
<input type="submit"
value="<spring:message text="Edit Notice"/>" />
</c:if>
<c:if test="${empty person.name}">
<input type="submit"
value="<spring:message text="Add Notice"/>" />
</c:if>
</td>
</tr>
</table>
</form:form>
<br>
<c:url var="addAction" value="/keynotice/add" ></c:url>
<form:form action="${addAction}" commandName="keyactivities">
<table>
<c:if test="${!empty keyactivities.keynotice}">
<tr>
<td>
<form:label path="id">
<spring:message text="ID"/>
</form:label>
</td>
<td>
<form:input path="id" readonly="true" size="8" disabled="true" />
<form:hidden path="id" />
</td>
</tr>
</c:if>
<tr>
<td>
<form:label path="keynotice">
<spring:message text="Keynotice"/>
</form:label>
</td>
<td>
<form:input path="keynotice" />
</td>
</tr>
<tr>
<td colspan="1">
<c:if test="${!empty keyactivities.keynotice}">
<input type="submit"
value="<spring:message text="Edit Notice"/>" />
</c:if>
<c:if test="${empty keyactivities.keynotice}">
<input type="submit"
value="<spring:message text="Add Notice"/>" />
</c:if>
</td>
</tr>
</table>
</form:form>
</body>
</html>
Error :
java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'keyactivities' available as request attribute
org.springframework.web.servlet.support.BindStatus.<init>(BindStatus.java:144)
org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getBindStatus(AbstractDataBoundFormElementTag.java:168)
org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getPropertyPath(AbstractDataBoundFormElementTag.java:188)
org.springframework.web.servlet.tags.form.LabelTag.autogenerateFor(LabelTag.java:130)
org.springframework.web.servlet.tags.form.LabelTag.resolveFor(LabelTag.java:120)
Stacktrace:
org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:568)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:465)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
org.springframework.web.servlet.view.InternalResourceView.renderMergedOutputModel(InternalResourceView.java:209)
org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:267)
org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1221)
org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:1005)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:952)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:870)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:852)
javax.servlet.http.HttpServlet.service(HttpServlet.java:620)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
refactor this method:
#RequestMapping(value = "/", method = RequestMethod.GET)
public String listPersons(Model model) {
model.addAttribute("person", new Person());
model.addAttribute("keyactivities", new KeyActivities());
model.addAttribute("listPersons", this.personService.listPersons());
return "person";
}
The error is that after post either form, you will not have keyactivities in the model

Spring MVC HTTP Status 400 - The request sent by the client was syntactically incorrect

My Item Object
public class Item extends MyBaseObject {
private String name;
private Category category;
private ItemType itemType;
private String description;
private Long reorderLevel;
private Long freezeLevel;
private Set<Inventory> inventories = new TreeSet<>();
private long totalCount;
private long currentlyIssued;
private long availableStock;
... getter and setters
}
itemAdd.jsp
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%# taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%# taglib prefix="sec" uri="http://www.springframework.org/security/tags" %>
<%# taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<jsp:include page="/WEB-INF/views/common/head.jsp" />
<h2 class="demoHeaders">Item (Add New)</h2>
<form:form id="frmItemAdd" method="post" modelAttribute="item">
<table class="vsform">
<tbody>
<tr>
<td>
<form:label path="name"><spring:message code="item.name"></spring:message></form:label>
</td>
<td>
<form:input path="name" class="inputlarge required"/>
<form:errors path="name" class="errorMsg"/>
</td>
</tr>
<tr>
<td>
<form:label path="description"><spring:message code="item.description"></spring:message></form:label>
</td>
<td>
<form:textarea path="description" rows="5" cols="50" class="inputlarge"/>
<form:errors path="description" class="errorMsg"/>
</td>
</tr>
<tr>
<td>
<form:label path="category"><spring:message code="item.category"></spring:message></form:label>
</td>
<td>
<form:select path="category" class="myform inputlarge">
<form:options items="${listCategory}" itemLabel="name" itemValue="id"/>
</form:select>
<form:errors path="category" class="errorMsg"/>
</td>
</tr>
<tr>
<td>
<form:label path="itemType"><spring:message code="item.itemType"></spring:message></form:label>
</td>
<td>
<form:select path="itemType" class="myform inputlarge">
<form:options items="${listItemType}" itemLabel="name" itemValue="id"/>
</form:select>
<form:errors path="itemType" class="errorMsg"/>
</td>
</tr>
<tr>
<td>
<form:label path="reorderLevel"><spring:message code="item.reorderLevel"></spring:message></form:label>
</td>
<td>
<form:input path="reorderLevel" class="inputsmall required"/>
<form:errors path="reorderLevel" class="errorMsg"/>
</td>
</tr>
<tr>
<td>
<form:label path="freezeLevel"><spring:message code="item.freezeLevel"></spring:message></form:label>
</td>
<td>
<form:input path="freezeLevel" class="inputsmall required"/>
<form:errors path="freezeLevel" class="errorMsg"/>
</td>
</tr>
<tr>
<td colspan="2">
<button id="buttonReset" type="reset">Reset</button> <button id="buttonSubmit">Submit</button>
</td>
</tr>
</tbody>
</table>
</form:form>
<jsp:include page="/WEB-INF/views/common/foot.jsp" />
My controller ItemAddController
#Controller
#RequestMapping("/ims/item/addNew")
public class ItemAddController extends InventoryBaseController {
#Autowired
private InventoryService inventoryService;
#Autowired
private ItemAddValidator itemAddValidator;
#ModelAttribute("listCategory")
public List<Category> getListCategory(){
return inventoryService.listCategory();
}
#ModelAttribute("listItemType")
public List<ItemType> getListItemType(){
return inventoryService.listItemType();
}
#RequestMapping(method=RequestMethod.GET)
public String itemAdd(Model model, RedirectAttributes reat, Principal principal){
Item item = new Item();
model.addAttribute("item", item);
return "manager/item/itemAdd";
}
#RequestMapping(method=RequestMethod.POST)
public String itemAdd(#ModelAttribute Item item, Model model, BindingResult result, RedirectAttributes reat, Principal principal){
this.itemAddValidator.validate(item, result);
if (result.hasErrors()){
return "manager/item/itemAdd";
}
item.setAddDefaults(principal.getName());
if (this.inventoryService.addItem(item)){
reat.addFlashAttribute("message", "Item record added successfully.");
} else {
reat.addFlashAttribute("message", "Item record not added.");
}
return "redirect:/ims/item/addNew";
}
}
The crux of the problem is that when I am feeding the correct values for each field the form submission works properly. But when I am giving 'a' or any text value for form field reorderLevel (which is defined as Long) the browser throws this error : The request sent by the client was syntactically incorrect.
I have already defined the following in messages.properties file:
typeMismatch=Could not convert to the required type.
typeMismatch.java.util.Calendar=Please enter date in the dd-MM-yyyy format.
typeMismatch.java.math.BigDecimal=Please enter value in correct format 0.00
typeMismatch.java.lang.Long=Must specify an integer value.
Please help... Thanks

How are Spring MVC Controllers being bound to JSP pages?

Hi I am new to spring and I am trying to develop a simple portlet that accepts users first and last name and saves it to db using hibernate.
Basically I cannot figure out how the jsps and controllers communicate; I am missing some chunk here.
This is my first controller that needs to be called (where do I mention so?)
package codes.controller;
import javax.portlet.RenderResponse;
import codes.base.User;
import codes.service.UserService;
#Controller(value="SimpleUserController")
#RequestMapping(value = "VIEW")
public class SimpleUserController {
// -- auto-wiring of service dependency
#Autowired
#Qualifier("userService")
private UserService userService;
// --maps the incoming portlet request to this method
#RenderMapping
public String showUsers(RenderResponse response) {
return "home";
}
#ExceptionHandler({ Exception.class })
public String handleException() {
return "errorPage";
}
// -- #ModelAttribute here works as the referenceData method
#ModelAttribute(value="user")
public User getCommandObject() {
return new User();
}
}
Initially I am displaying a home.jsp that will display the form with two input boxes and a submit button.
<%#include file="include.jsp" %>
<portlet:actionURL var="addUserActionUrl">
<portlet:param name="myaction" value="addUser" />
</portlet:actionURL>
<form:form name="home" commandName="user" method="post"
action="${addUserActionUrl}">
<table>
<tr>
<td>First Name:<font style="color: #C11B17;">*</font></td>
<td><form:input path="firstname" /></td>
</tr>
<tr>
<td>Last Name:<font style="color: #C11B17;">*</font></td>
<td><form:input path="lastname" /></td>
</tr>
<table align="right">
<tr>
<td> </td>
<td><input type="submit" value="SUBMIT" /></td>
</tr>
</table>
</table>
</form:form>
This JSP should call the action method in the AddUserController.java:
package codes.controller;
import javax.portlet.ActionResponse;
import javax.portlet.RenderResponse;
import codes.base.User;
import codes.service.UserService;
#Controller(value = "AddUserController")
#RequestMapping(value = "VIEW")
public class AddUserController {
#Autowired
#Qualifier("userService")
private UserService userService;
#RenderMapping(params = "myaction=addUser")
public String showRegisterPage(Model model) {
model.addAttribute("user", new User());
model.addAttribute("users", getUsers());
return "addUser";
}
public List<User> getUsers() {
return userService.getAllUsers();
}
#ActionMapping(params = "myaction=addUser")
public void addBook(#ModelAttribute(value = "user") User user,
BindingResult bindingResult, ActionResponse response,
SessionStatus sessionStatus) {
if (!bindingResult.hasErrors()) {
userService.addUser(user);
response.setRenderParameter("myaction", "users");
sessionStatus.setComplete();
} else {
response.setRenderParameter("myaction", "addUser");
}
}
}
This time this firstname+last name should be saved in the db AND the screen should refresh to show a new form that will have a dropdown with the current users' names in the database and another first name and last name form fields. If you select a username from the dropdown the form fields are populated and you can edit these values and click on UPdate button to save the values in DB. Otherwise you can add a new user to the database using submit button.
addUser.jsp:
<%#include file="include.jsp" %>
<portlet:actionURL var="addUserActionUrl">
<portlet:param name="myaction" value="addUser" />
</portlet:actionURL>
<portlet:renderURL var="homeUrl">
<portlet:param name="myaction" value="Users" />
</portlet:renderURL>
<script type="text/javascript" src="js/userRelated.js"></script>
<form:form name="addUser" commandName="user" method="post"
action="${addUserActionUrl}">
<form:select path="model">
<form:option value="NONE" label="--- Select ---" id="userList" onchange="showHide()"/>
<form:options items="${users}" />
</form:select>
<table>
<tr>
<td>First Name:<font style="color: #C11B17;">*</font></td>
<td><form:input path="firstname" /></td>
</tr>
<tr>
<td>Last Name:<font style="color: #C11B17;">*</font></td>
<td><form:input path="lastname" /></td>
</tr>
<table align="right">
<tr>
<td> </td>
<td><input type="submit" id="submit" value="SUBMIT" />SUBMIT</td>
</tr>
<tr>
<td> </td>
<td><input type="submit" id="update" value="SUBMIT" />UPDATE</td>
</tr>
</table>
</table>
</form:form>
I am hiding and unhiding the SUBMIT/UPDATE button using onchange of dropdown. How do I call different functions in the addUsercontroller depending on the button available?
by updating the action attribute of form element with javascript

Resources