Form validation with form:options - java

Form:Options working pretty well, but if I submit wrong data in Form, form:options in newContact.jsp shows the first element of departmentList as selected.
ContactController:
#RequestMapping(value="/saveContact", method=RequestMethod.GET)
public ModelAndView newuserForm(){
ModelAndView mav = new ModelAndView("newContact");
// Contact contact = new Contact();
// Department department = new Department();
User user = (User)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
String name = user.getUsername();
mav.addObject("username", name);
mav.addObject("newContact", new Contact());
// mav.addObject("department", department);
mav.addObject("departmentList", departmentService.listDepartment());
//mav.getModelMap().put("newContact", contact);
return mav;
}
#RequestMapping(value="/saveContact", method=RequestMethod.POST)
public String create(#ModelAttribute("newContact")Contact contact, BindingResult result, SessionStatus status,Map<String, Object> map)
{
User user = (User)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
String name = user.getUsername();
map.put("departmentList", departmentService.listDepartment());
map.put("username", name);
contactFormvalidator.validate(contact, result);
if (result.hasErrors())
{
return "newContact";
}
contactService.addContact(contact);
status.setComplete();
//return "redirect:/showContacts.do";
return "newContactSuccess";
}
newContact.jsp:
<%#include file="header.jsp"%>
<div id="menu">
<div id="subMenu"></div>
</div>
<div id="main">
<h2>Contact Manager</h2>
<form:form method="post" action="saveContact.do" commandName="newContact" >
<table>
<tr>
<td><form:label path="firstname">
<spring:message code="label.firstname" />
</form:label></td>
<td><form:input path="firstname" /></td>
<td><form:errors path="firstname" cssStyle="color:red"></form:errors> </td>
</tr>
<tr>
<td><form:label path="lastname">
<spring:message code="label.lastname" />
</form:label></td>
<td><form:input path="lastname" /></td>
<td><form:errors path="lastname" cssStyle="color:red"></form:errors> </td>
</tr>
<tr>
<td><form:label path="email">
<spring:message code="label.email" />
</form:label></td>
<td><form:input path="email" /></td>
<td><form:errors path="email" cssStyle="color:red"></form:errors> </td>
</tr>
<tr>
<td><form:label path="telephone">
<spring:message code="label.telephone" />
</form:label></td>
<td><form:input path="telephone" /></td>
<td><form:errors path="telephone" cssStyle="color:red"></form:errors> </td>
</tr>
<tr>
<td><form:label path="department">
<spring:message code="label.department" />
</form:label></td>
<td><form:select path="department" >
<form:option label="**SELECT**" value="0"></form:option>
<form:options items="${departmentList}" itemValue="id" itemLabel="name"></form:options>
</form:select> </td>
<td><form:errors path="department" cssStyle="color:red"></form:errors> </td>
</tr>
<tr>
<td colspan="2"><input type="submit"
value="<spring:message code="label.addcontact"/>" /></td>
</tr>
</table>
</form:form>
</div>
<%# include file="footer.jsp"%>
ContactFormValidator:
package pl.ivmx.contact.validator;
import java.util.regex.*;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;
import pl.ivmx.contact.form.Contact;;
//#Component("contactFormValidator")
public class ContactFormValidator implements Validator{
#Override
public boolean supports(Class clazz) {
return Contact.class.isAssignableFrom(clazz);
}
#SuppressWarnings("unchecked")
#Override
public void validate(Object obj, Errors errors) {
Contact contact = (Contact) obj;
Pattern p = Pattern.compile("[a-zA-Z]*[0-9]*#[a-zA-Z]*.[a-zA-Z]*");
Matcher m = p.matcher(contact.getEmail());
boolean b = m.matches();
if (b != true) {
errors.rejectValue("email", "error.is.not.valid",
"Email does not Valid ");
}
if (contact.getFirstname() == null || contact.getFirstname().length() < 3) {
errors.rejectValue("firstname", "error.empty.field",
"Please Enter First Name");
}
if (contact.getLastname() == null || contact.getLastname().length() < 4) {
errors.rejectValue("lastname", "error.empty.field",
"Please Enter Last Name");
}
if (contact.getTelephone() == 0 || String.valueOf(contact.getTelephone()).trim().length() < 2 ||
String.valueOf(contact.getTelephone()).trim().length() > 9) {
errors.rejectValue("telephone", "error.empty.field",
"Please Enter Telephone");
}
if (contact.getDepartment() == null) {
errors.rejectValue("department", "error.empty.field",
"Please select department");
}
}
}

Instead of returning String in your submit method return ModelAndView ...
#RequestMapping(value="/saveContact", method=RequestMethod.POST)
public ModelAndView create(#ModelAttribute("newContact")Contact contact, BindingResult result, SessionStatus status,ModelMap map)
{
User user = (User)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
String name = user.getUsername();
map.addAttribute("departmentList", departmentService.listDepartment());
map.addAttribute("username", name);
contactFormvalidator.validate(contact, result);
if (result.hasErrors())
{
return new ModelAndView("newContact",map);
}
contactService.addContact(contact);
status.setComplete();
//return new ModelAndView("redirect:/showContacts.do");
return new ModelAndView("newContactSuccess");
}

Related

Invalid target for Validator - Spring MVC

I'm having problems with validating in Spring. I'm getting the following error after opening the form:
java.lang.IllegalStateException: Invalid target for Validator [com.example.validator.UserValidator#6ac0a8f4]: com.example.web.forms.UserDTO#4d3b2379
My Validator for the time being, wanted to check if anything works first:
#Component
public class UserValidator implements Validator {
#Autowired
ServiceUser serviceUser;
#Override
public boolean supports(Class<?> clazz) {
return User.class.equals(clazz);
}
#Override
public void validate(Object target, Errors errors) {
User user = (User) target;
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "name", "NotEmpty.userForm.name");
}
}
Controller:
#Controller
public class UserController {
#Autowired
UserValidator userValidator;
#InitBinder
public void initBinder(WebDataBinder binder) {
CustomDateEditor editor = new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), true, 10);
binder.registerCustomEditor(Date.class, editor);
binder.setValidator(userValidator);
// binder.addValidators(userValidator);
}
final static Logger logger = Logger.getLogger(UserController.class);
#Autowired
protected ServiceUserImpl service;
#RequestMapping("/lista")
public String showIndex(Model model) {
User contest = new User();
model.addAttribute("element", contest);
model.addAttribute("collection", service.findAll());
return "lista";
}
#RequestMapping("/dodaj")
public String showFormPublication(HttpServletRequest request, #ModelAttribute("userDto") #Valid UserDTO userDTO, BindingResult result) {
if (request.getMethod().equalsIgnoreCase("post") && !result.hasErrors()) {
if (result.hasErrors()) {
return "forms/contest";
} else {
User user = new User();
user.setId(userDTO.getId());
user.setName(userDTO.getName());
user.setSurname(userDTO.getSurname());
user.setDateOfBirth(userDTO.getDateOfBirth());
user.setIndexNumber(userDTO.getIndexNumber());
user.setEmail(userDTO.getEmail());
service.save(user);
return "redirect:/lista";
}
}
return "dodaj";
}
}
Form in .jsp:
<form:form action="dodaj" method="POST" modelAttribute="userDto">
<table border="1">
<tbody>
<tr>
<th>ImiÄ™</th>
<td>
<form:input type="text" path="name" />
<c:if test="${pageContext.request.method=='POST'}"><form:errors path="name" /></c:if>
</td>
</tr>
<tr>
<th>Nazwisko</th>
<td>
<form:input type="text" path="surname" />
<c:if test="${pageContext.request.method=='POST'}"><form:errors path="surname" /></c:if>
</td>
</tr>
<tr>
<th>DataUrodzenia</th>
<td>
<form:input type="date" path="dateOfBirth" />
<c:if test="${pageContext.request.method=='POST'}"><form:errors path="dateOfBirth" /></c:if>
</td>
</tr>
<tr>
<th>NumerIndeksu</th>
<td>
<form:input type="number" path="indexNumber" />
<c:if test="${pageContext.request.method=='POST'}"><form:errors path="indexNumber" /></c:if>
</td>
</tr>
<tr>
<th>Email</th>
<td>
<form:input type="text" path="email" />
<c:if test="${pageContext.request.method=='POST'}"><form:errors path="email" /></c:if>
</td>
</tr>
<tr>
<td colspan="2" align="right"><input type="submit" value="Dodaj!" /></td>
</tr>
</tbody>
</table>
</form:form>
I tried adding ("userDto") next to #InitBinder, it didn't help unfortunately. Haven't found much more in terms of applicable solutions. If there's anything else I should post here let me know. I can also provide a link to repository should anyone be eager enough to try to run it.
I think you need to change the supports method in UserValidator to UserDTO class:
public boolean supports(Class<?> clazz) {
return UserDTO.class.equals(clazz);
}

Bean value not being filled in on JSP page

I am new to Java... I made this application, but the problem is that when I run the project I am getting the text which i have written in h tag's value attribute instead of the value from the bean. I have searched a lot but the problem is still there. The code and the screenshot tells the rest of the story. Here is my login.jsp:
</head>
<body>
<f:view>
<div class="login_container">
<h:messages errorClass="errorMsg"/>
<div class="login_box">
<table width="100%" border="0" cellpadding="0" cellspacing="0">
<tr>
<td>
<div class="login_wrap">
<div class="login_logo">
<img src="images/login_logo.gif" width="116" height="141" />
</div>
<h:form id="login_form">
<div class="login_form">
<table width="100%" border="0" cellpadding="0" cellspacing="0">
<tr>
<td>
<div style="float: left;">
<h2 class="orange">
Please Login
</h2>
</div>
<div class="login_icon">
<img src="images/icn_lock.png" width="16" height="16" />
</div>
</td>
</tr>
<tr>
<td>
<label>
Username
</label>
</td>
</tr>
<tr>
<td><h:inputText id="username" value="#{loginBean.username}" /></td>
</tr>
<tr>
<td>
<label>
Password
</label>
</td>
</tr>
<tr>
<td><h:inputText id="password" value="#{loginBean.password}"/>
</td>
</tr>
<tr>
<td>
</td>
</tr>
<tr>
<td align="left" valign="middle">
<h:commandButton image="images/btn_login.gif" id="loginButton" action="#{loginBean.login}"
style="width:81px; height:29px" />
</td>
</tr>
</table>
</div>
</h:form>
</div>
</td>
</tr>
<tr>
<td>
<div class="login_box_bt">
</div>
</td>
</tr>
</table>
</div>
<div class="login_footer_box">
<div class="login_footer">
<div class="login_footer_text">
<p>
<span class="text_orange">Phone:</span> (+92-51) 5120684
<br />
<span class="text_orange">E-mail:</span> support#noeticworld.com
<br />
<span class="text_orange">Web:</span> http://www.noeticworld.com.pk
</p></div>
<div class="login_footer1_text">
<p>
<span class="text_orange">Leading VAS Solution Provider
</span>
<% /**<span class="text_orange">Fax:</span> (+92-51) 260 9263*/ %>
<br />
</p></div>
</div>
</div>
<div class="login_box_bt">
</div>
</f:view>
</body>
</html>
here is my backingbeans :
public class LoginBackingBean
{
private String username;
private String password;
private Boolean rememberMe;
public String getUsername()
{
return username;
}
public void setUsername(String username)
{
this.username = username;
}
public String getPassword()
{
return password;
}
public void setPassword(String password)
{
this.password = password;
}
public Boolean getRememberMe()
{
return rememberMe;
}
public void setRememberMe(Boolean rememberMe)
{
this.rememberMe = rememberMe;
}
public String login()
{
boolean isValidUser = true;
String message = "";
Employee employee = null;
try
{
employee = getCurrentEmployee();
if (employee == null)
{
isValidUser = false;
message = "Sorry, the username or password is incorrect. Please try again";
}
}
catch (SQLException e)
{
isValidUser = false;
message = e.getMessage();
e.printStackTrace();
}
if (!isValidUser)
{
FacesMessage facesMessage = new FacesMessage();
facesMessage.setSeverity(FacesMessage.SEVERITY_ERROR);
facesMessage.setSummary(message);
FacesContext.getCurrentInstance().addMessage("login_form", facesMessage);
return "failure";
}
EmployeeBackingBean employeeBackingBean = EmployeeBackingBean.getEmployeeBackingBean(employee);
List<Integer> recursiveSubordinatesIds;
try
{
recursiveSubordinatesIds = new EmployeeDAOImpl(DigiDeskDAO.getSqlMapper()).selectIdsOfRecursiveSubordinates(employeeBackingBean.getEmployeeId());
employeeBackingBean.setRecursiveSubordinatesIds(recursiveSubordinatesIds);
}
catch (SQLException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
SessionManager.setEmployeeInSession(employeeBackingBean);
return "success";
}
/**
* This function finds the employee with the provided username and password
*
* #return - Employee object if validation succeeds, null if no matching user is found
* #throws SQLException
*/
private Employee getCurrentEmployee() throws SQLException
{
EmployeeDAOImpl employeeDAOImpl = new EmployeeDAOImpl(DigiDeskDAO.getSqlMapper());
EmployeeExample employeeExample = new EmployeeExample();
EmployeeExample.Criteria criteria = employeeExample.createCriteria();
criteria.andUsernameEqualTo(username);
criteria.andPasswordEqualTo(password);
List<Employee> employeesList = employeeDAOImpl.selectByExampleWithBLOBs(employeeExample);
if (employeesList.isEmpty())
{
return null;
}
Employee employee = employeesList.get(0);
return employee;
}
}
This is the problem, username and password shows the text:
Try to replace #{~~} with ${~~}

How to pass nested list element to the controller in spring mvc

In my jsp page there have a table with nested list value, i want to send that table value to the container, The outer table value were sent but the inner table value not sent to the container, I am new here please let me know how to over come this situation,
My jsp
<script>
function rowAdded(rowElement) {
//clear the imput fields for the row
$(rowElement).find("input").val('');
//may want to reset <select> options etc
//in fact you may want to submit the form
saveNeeded();
}
function rowRemoved(rowElement) {
saveNeeded();
}
function saveNeeded() {
$('#submit').css('color','red');
$('#submit').css('font-weight','bold');
if( $('#submit').val().indexOf('!') != 0 ) {
$('#submit').val( '!' + $('#submit').val() );
}
}
function beforeSubmit() {
alert('script Working');
return true;
}
$(document).ready( function() {
var config = {
rowClass : 'rule',
addRowId : 'addRule',
removeRowClass : 'removeRule',
formId : 'ruleListForm',
rowContainerId : 'ruleListContainer',
indexedPropertyName : 'ruleList',
indexedPropertyMemberNames : 'id,ruleName,parameterName,overwriteValue',
rowAddedListener : rowAdded,
rowRemovedListener : rowRemoved,
beforeSubmit : beforeSubmit
};
new DynamicListHelper(config);
});
</script>
<html>
<form:form action="/update" method="post" id="ruleListForm" modelAttribute="ruleListContainer">
<table border="1">
<thead>
<h3 align="center">Selected Rule</h3>
<tr>
<th data-field="id" width="25">ID </th>
<th data-field="details" width="20">RuleName </th>
<th data-field="parameter" width="240">Parameter </th>
</tr>
</thead>
<tbody id="ruleListContainer">
<c:forEach items="${List2}" var="as">
<tr class="rule">
<td><input type="hidden" name="ruleList[].id" value="${as.rule.id}" /> ${as.rule.id}</td>
<td><input type="hidden" name="ruleList[].ruleName" value="${as.rule.ruleName}" /> ${as.rule.ruleName}</td>
<td> <input id="one" class="datepicker" type="text" name="ruleList[].startDate" size="11" height="0.10"></td>
<td> <input id="two" class="datepicker" type="text" name="ruleList[].endDate" size="11" height="0.10"></td>
<td>
<table border="1">
<c:forEach items="${as.ruleAssignmentParameter}" var="asss">
<tr>
<td><input type="hidden" name="ruleList[].parameterName"value="${asss.parameterName}" > ${asss.parameterName}</td>
<td><input type="hidden" name="ruleList[].overwriteValue" value="${asss.overwriteValue}" /> ${asss.overwriteValue}</td>
</tr>
</c:forEach>
</table>
</td>
</tr>
</c:forEach>
</tbody>
</table>
<br>
<input type="submit" value="Update">
</form:form>
</html>
Here is my model class
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import com.demo.app.model.RuleAssignmentParameter;
public class RuleAssUI {
private int id;
private String ruleName;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getRuleName() {
return ruleName;
}
public void setRuleName(String ruleName) {
this.ruleName = ruleName;
}
private List<RuleAssignmentParameter> ruleAssignmentParameter = new LinkedList<RuleAssignmentParameter>();
public List<RuleAssignmentParameter> getRuleAssignmentParameter() {
return ruleAssignmentParameter;
}
public void setRuleAssignmentParameter(List<RuleAssignmentParameter> ruleAssignmentParameter) {
this.ruleAssignmentParameter = ruleAssignmentParameter;
}
public RuleAssUI(){
}
public RuleAssUI(int id,String ruleName){
this.id=id;
this.ruleName=ruleName;
}
}
My container where i store the list value
import java.util.LinkedList;
import java.util.List;
public class RuleListContainer {
private List<RuleAssUI> ruleList = new LinkedList<RuleAssUI>();
public RuleListContainer() {
}
public RuleListContainer(List<RuleAssUI> ruleList) {
this.ruleList = ruleList;
}
public List<RuleAssUI> getRuleList() {
return ruleList;
}
public void setRuleList(List<RuleAssUI> ruleList) {
this.ruleList = ruleList;
}
Controller
#RequestMapping(value = "/update", method = RequestMethod.POST)
public String update(#ModelAttribute("SpringWeb") RuleListContainer ruleListContainer, HttpSession session, ModelMap model) {
ruleListContainer.getRuleList().size();
for (RuleAssUI rul1 : ruleListContainer.getRuleList()) {
System.out.println("Id: " + rul1.getId());
System.out.println("RuleName: " + rul1.getRuleName());
for (RuleAssignmentParameter rul2 : rul1.getRuleAssignmentParameter()) {
System.out.println("ParameterName: " + rul2.getParameterName());
System.out.println("ParameterValue: " + rul2.getOverwriteValue());
}
}
session.setAttribute("ruleListContainer", ruleListContainer);
return "hello";
}
I am trying so many time but unable to fixed the issue, And browse also but did't get any proper help, so please help to do items
I NEED HELP PLEASE SOME BODY HELP ME...!
Thank you in advance
I think the problem is in your jsp file.
You need to set the index of each list element.
<c:forEach items="${List2}" var="as" varStatus="vs">
<tr class="rule">
<td><input type="hidden" name="ruleList[${vs.index}].id" value="${as.rule.id}" /> ${as.rule.id}</td>
<td><input type="hidden" name="ruleList[${vs.index}].ruleName" value="${as.rule.ruleName}" /> ${as.rule.ruleName}</td>
<td> <input id="one" class="datepicker" type="text" name="ruleList[${vs.index}].startDate" size="11" height="0.10"></td>
<td> <input id="two" class="datepicker" type="text" name="ruleList[${vs.index}].endDate" size="11" height="0.10"></td>
<td>
<table border="1">
<c:forEach items="${as.ruleAssignmentParameter}" var="asss" varStatus="assignments">
<tr>
<td><input type="hidden" name="ruleList[${vs.index}].ruleAssignmentParameter[${assignments.index}].parameterName" value="${asss.parameterName}" > ${asss.parameterName}</td>
<td><input type="hidden" name="ruleList[${vs.index}].ruleAssignmentParameter[${assignments.index}].overwriteValue" value="${asss.overwriteValue}" /> ${asss.overwriteValue}</td>
</tr>
</c:forEach>
</table>
</td>
</tr>
</c:forEach>
Also in your controller (POST method) you are trying to get the object identified by "SpringWeb" but should be "ruleListContainer", same name you have in your form tag
The problem was you had a list into RuleAssUI and you was not accesing correctly, you need 2 loops and indexes, one for each list.
Here is the key:
ruleList[${vs.index}].ruleAssignmentParameter[${assignments.index}].parameterName

After submitting a form go back to previous page (Spring/Hibernate)

I have a restaurant edit page located "/restaurant/edit/{id}". From that page I can (among other things) add tables to the restaurant by pressing an "Add tables" button. That button takes me to another page located "/restaurant/edit/{id}/table". The question is, after I have added the table - how do I get back to the previous page by pressing a button? Right now my contoller is returning "editRestaurant.jsp" which is the right value, but I don't know how to pass that same restaurant id as well. I hope you understand what I mean.
My RestaurantTableController.java:
#Controller
public class RestaurantTableController {
#Autowired
private RestaurantService restaurantService;
#Autowired
private RestaurantTableService restaurantTableService;
#RequestMapping(value="restaurant/{id}/table", method = RequestMethod.GET)
public String addRestaurantTable(Model model, #PathVariable Long id) {
model.addAttribute("table", new RestaurantTable());
return "newTable";
}
#RequestMapping(value = "restaurant/{id}/table", method = RequestMethod.POST)
public String addRestaurantTableAction(#PathVariable Long id, #ModelAttribute ("table") RestaurantTable table, BindingResult result) {
RestaurantTableFormValidator restaurantTableFormValidator = new RestaurantTableFormValidator();
restaurantTableFormValidator.validate(table, result);
if (result.hasErrors()) {
return "newTable";
}
restaurantService.mergeRestaurant(id, table);
return "editRestaurant";
}
}
My "newTable.jsp":
<body>
<jsp:include page="../fragments/menu.jsp"/>
<div id="body">
<section class="content-wrapper main-content clear-fix">
<h2>Add New Table</h2>
<form:form method="POST" modelAttribute="table">
<table>
<tr>
<td>Table size:</td>
<td><form:input path="tableSize" /></td>
<td><form:errors path="tableSize" cssClass="error"/></td>
</tr>
<tr>
<td>Table number:</td>
<td><form:input path="tableNumber" /></td>
<td><form:errors path="tableNumber" cssClass="error"/></td>
</tr>
<tr>
<td colspan="3"><input type="submit" onclick="goback()"/>
</td>
</tr>
</table>
</form:form>
</section>
</div>
<jsp:include page="../fragments/footer.jsp"/>
</body>
Relevant methods in RestaurantController.java:
#RequestMapping(value = "restaurant/edit/{id}", method = RequestMethod.GET)
public String editRestaurant(#PathVariable Long id, Model model) {
Restaurant restaurant = restaurantService.getRestaurant(id);
model.addAttribute("restaurant", restaurant);
return "editRestaurant";
}
#RequestMapping(value = "restaurant/edit/{id}", method = RequestMethod.POST, params="submit")
public String editRestaurant(#ModelAttribute ("restaurant") Restaurant restaurant, BindingResult result) {
RestaurantFormValidator restaurantFormValidator = new RestaurantFormValidator();
restaurantFormValidator.validate(restaurant, result);
if (result.hasErrors()) {
return "editRestaurant";
}
restaurantService.updateRestaurant(restaurant);
return "redirect:/bookings";
}
"editRestaurant.jsp":
<div id="body">
<section class="content-wrapper main-content clear-fix">
<h2>Edit</h2>
<form:form method="POST" modelAttribute="restaurant" >
<table>
<tr>
<td>Restaurant:</td>
<td><form:input path="restaurantName" /></td>
<td><form:errors path="restaurantName" cssClass="error"/></td>
</tr>
<tr>
<td>Address:</td>
<td><form:input path="address" /></td>
<td><form:errors path="address" cssClass="error"/></td>
</tr>
<tr>
<td colspan="3"><input type="submit" value="Submit" name="submit"/>
</td>
</tr>
<tr>
<c:forEach items="${restaurant.table}" var="item">
<td>${item.toString()}</td>
</c:forEach>
</tr>
<tr>
<td>Add Table</td>
</tr>
</table>
</form:form>
<div>
Back to List
</div>
</section>
</div>
After successful POST you should do a redirect.
Something like this:
return "redirect:/restaurant/edit/" + restaurant.getId();
or
return new RedirectView("/restaurant/edit/" + restaurant.getId(), false);
There is a different method you can use to return the model that will include the parameter. I believe this may solve your problem.
#RequestMapping(value = "restaurant/edit/{id}", method = RequestMethod.GET)
public String editRestaurant(#PathVariable Long id, Model model) {
Restaurant restaurant = restaurantService.getRestaurant(id);
return new ModelAndView("editRestaurant", "restaurant", restaurant);
}

How can i receive a url parameter again after do validation method

I want to take get a url parameter again after I've done another method. I tried adding the line new ModelAndView (updatealbum.htm?albumId=${album.albumId}"); but failed.
My path when I click the edit link is:
http://localhost:8089/MusicStore/admin/updatealbum.htm?albumId=13
My path after press submit button:
http://localhost:8089/MusicStore/admin/submitupdatealbum.htm?albumId=13
But when I click submit again:
http://localhost:8089/MusicStore/admin/submitupdatealbum.htm?albumId=
AlbumController.java
#RequestMapping(value = "*/updatealbum.htm", method = RequestMethod.GET)
public ModelAndView updatealbum(
#RequestParam(value = "albumId") int albumId, ModelMap model,
#ModelAttribute("album") Album album) {
Album theAlbum = albumService.findAlbum(albumId);
List<Category> listCategory = albumService.getListCategory();
System.out.println(theAlbum.getName());
model.addAttribute("listCategory", listCategory);
model.addAttribute("theAlbum", theAlbum);
return new ModelAndView("updatealbum", "command", new Album());
}
#RequestMapping(value = "*/submitupdatealbum.htm", method = RequestMethod.POST)
public ModelAndView submitUpdateAlbum(
#Valid #ModelAttribute("album") Album album, BindingResult result,
#RequestParam(value = "albumId") int albumId,
ModelMap model) {
if (result.hasErrors()) {
System.out.println(result);
ModelAndView model1 = new ModelAndView("updatealbum");
model.addAttribute("albumId",albumId);
System.out.println(albumId);
return model1;
}
Album newAlbum = albumService.findAlbum(albumId);
album.parseDateToString();
newAlbum.setReleaseDate(album.getReleaseDate());
newAlbum.setAuthor(album.getAuthor());
newAlbum.setDiscount(album.getDiscount());
newAlbum.setName(album.getName());
newAlbum.setPicture(album.getPicture());
newAlbum.setReleaseDate(album.getReleaseDate());
newAlbum.setSinger(album.getSinger());
newAlbum.setCategory(album.getCategory());
albumService.editAlbum(newAlbum);
model.addAttribute("succsessMgs", "Form successfully submitted");
return new ModelAndView(setupForm1(model));
}
updatealbum.jsp
<div class="content">
<c:if test="${not empty succsessMgs}">
<div class="mgs">${succsessMgs}</div>
</c:if>
<div align="center">
<form:form action="submitupdatealbum.htm?albumId=${theAlbum.albumId} "
method='POST' commandName="album">
<table>
<tr height="40" align="left">
<td>Album Name:</td>
<td><form:input path="name" value="${theAlbum.name}"/></td>
<td><form:errors path="name" cssStyle="color: #ff0000;"/></td>
</tr>
<tr height="40" align="left">
<td>Singer:</td>
<td><form:input path="author" value="${theAlbum.author}"/></td>
<td><form:errors path="author" cssStyle="color: #ff0000;"/></td>
</tr>
<tr height="40" align="left">
<td>Release Date:</td>
<td><form:input path="releaseDate" value="${theAlbum.releaseDate}"/></td>
<td><form:errors path="releaseDate" cssStyle="color: #ff0000;"/></td>
</tr>
<tr height="40" align="left">
<td>Discount:</td>
<td><form:input path="discount" value="${theAlbum.discount}"/></td>
<td><form:errors path="discount" cssStyle="color: #ff0000;"/></td>
</tr>
<tr height="40" align="left">
<td>Author:</td>
<td><form:input path="author" value="${theAlbum.author}" /></td>
<td><form:errors path="author" cssStyle="color: #ff0000;"/></td>
</tr>
<%-- <tr height="40" align="left">
<td>Picture:</td>
<td><form:form enctype="multipart/form-data"
modelAttribute="album">
<input type="file" name='picture'>
</form:form></td>
</tr> --%>
<tr height="40" align="left">
<td>Image URL:</td>
<td><form:input path="picture" value="${theAlbum.picture}" /></td>
<td><form:errors path="picture" cssStyle="color: #ff0000;"/></td>
</tr>
<tr height="40" align="left">
<td>Category:</td>
<td><form:form modelAttribute="album">
<form:select path="category.categoryId">
<form:option value="" label="Choose category" />
<form:options items="${listCategory}" itemValue="categoryId"
itemLabel="categoryName" />
</form:select>
</form:form></td>
<td><springForm:errors path="category.categoryId" cssClass="error" /></td>
</tr>
<tr>
<td><input name="submit" type="submit" value="Submit" /></td>
</tr>
</table>
</form:form>
</div>
</div>
Use it
#RequestMapping(value = "*/submitupdatealbum.htm", method = RequestMethod.POST)
public ModelAndView submitUpdateAlbum(
#Valid #ModelAttribute("album") Album album, BindingResult result,
#RequestParam(value = "albumId") int albumId, ModelMap model) {
System.out.println("ssssssssssssssssss:" + result);
if (result.hasErrors()) {
System.out.println("result:" + result);
System.out.println("asdasdasd");
ModelAndView model1 = new ModelAndView(
"redirect:updatealbum.htm?albumId=" + album.getAlbumId());
return model1;
}
But it can't show the <td><form:errors path="name" cssStyle="color: #ff0000;"/></td>

Categories