I am using Spring-MVC and I would like to do validation tests in backend. Currently I am able to perform the tests, redirect properly to the link. But I am only unable to add custom error messages incase there is a problem, Example : "Firstname is empty". I tried using the ValidationMessages_en_EN.properties file in WEB-INF, but that also didn't help. I am posting my code, kindly let me know where I am going wrong :
COntroller :
#Controller
public class PersonController {
#RequestMapping(value = "/", method = RequestMethod.GET)
public String listPersons(Model model) {
Person person = personService.getCurrentlyAuthenticatedUser();
if(!(person==null)){
return "redirect:/canvas/list";
} else {
model.addAttribute("person", new Person());
// model.addAttribute("listPersons", this.personService.listPersons());
model.addAttribute("notices",new Notes());
model.addAttribute("canvases",new Canvas());
return "person";
}
}
#RequestMapping(value= "/person/add", method = RequestMethod.POST)
public String addPerson(#Valid Person person,BindingResult bindingResult,#ModelAttribute("person") Person p,Model model){
if(bindingResult.hasErrors()){
return "redirect:/";
}
this.personService.addPerson(p);
return "redirect:/";
}
Entity :
#Entity
#Table(name="person")
public class Person implements UserDetails{
private static final GrantedAuthority USER_AUTH = new SimpleGrantedAuthority("ROLE_USER");
#Id
#Column(name="id")
#GeneratedValue(strategy = GenerationType.SEQUENCE,generator = "person_seq_gen")
#SequenceGenerator(name = "person_seq_gen",sequenceName = "person_seq")
private int id;
#Valid
#NotEmpty #Email(message = "username.empty")
#Column(name = "username")
private String username;
#NotEmpty
#Column(name = "password")
private String password;
#Valid
#Size(min = 2,max = 30,message = "firstName.empty")
#Column(name = "firstname")
private String firstName;
#Valid
#Size(min = 2,max = 50)
#Column(name = "secretquestion")
private String secretquestion;
#Valid
#Size(min = 2,max = 500,message = "secretanswer.empty")
#Column(name = "secretanswer")
private String secretanswer;
Servlet-Context.xml
<beans:bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<beans:property name="basename" value="ValidatorMessages_en_EN.properties"/>
</beans:bean>
JSP/HTML :
<c:url var="addAction" value="/person/add" ></c:url>
<form:form action="${addAction}" commandName="person" method="post">
<table>
<c:if test="${!empty person.username}">
<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="firstName">
<spring:message text="FirstName"/>
</form:label>
</td>
<td>
<form:input path="firstName" />
</td>
<td><form:errors path="firstName"/>
</tr>
<tr>
<td>
<form:label path="username">
<spring:message text="Email"/>
</form:label>
</td>
<td>
<form:input path="username" />
</td>
<td><form:errors path="username"/>
</tr>
<tr>
<td>
<form:label path="password">
<spring:message text="Password"/>
</form:label>
</td>
<td>
<form:input path="password" />
</td>
<td><form:errors path="Password"/>
</tr>
<tr>
<td>
<form:label path="secretquestion">
<spring:message text="secretquestion"/>
</form:label>
</td>
<td>
<form:input path="secretquestion" />
</td>
<td><form:errors path="secretquestion"/>
</tr>
<tr>
<td>
<form:label path="secretanswer">
<spring:message text="secretanswer"/>
</form:label>
</td>
<td>
<form:input path="secretanswer" />
</td>
<td><form:errors path="secretanswer"/>
</tr>
POM.xml :
<!-- Validation -->
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>1.0.0.GA</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>4.3.1.Final</version>
</dependency>
Messages.properties :
firstName=firstName
Email=Email
Password=password
secretquestion=secretquestion
secretanswer=secretanswer
NotEmpty.person.firstName=firstName is required!
NotEmpty.person.username=Email is required!
NotEmpty.person.password=Password is required!
NotEmpty.person.secretquestion=SecretQuestion is required!
NotEmpty.person.secretanswer=SecretAnswer is required!
Messages_en_US.properties
firstName=firstName
Email=Email
Password=password
secretquestion=secretquestion
secretanswer=secretanswer
NotEmpty.person.firstName=firstName is required!
NotEmpty.person.username=Email is required!
NotEmpty.person.password=Password is required!
NotEmpty.person.secretquestion=SecretQuestion is required!
NotEmpty.person.secretanswer=SecretAnswer is required!
<spring:message text="FirstName"/> Should be like <spring:message code="FirstName"/> try to replace text to code in your <spring:message /> tag
and change basename value to ValidatorMessages and en_US Spring will append for you
<beans:bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<beans:property name="basename" value="ValidatorMessages"/>
</beans:bean>
sava your file as ValidatorMessages_en_US.properties in your resource folder
#ExceptionHandler(Exception.class)
#ResponseBody
#ResponseStatus(value = HttpStatus.BAD_REQUEST)
public Response handleException(Exception e) {
Response response = new Response();
if(e instanceof MethodArgumentNotValidException ){
MethodArgumentNotValidException methodException = (MethodArgumentNotValidException)e;
BindingResult bindingResult =methodException.getBindingResult();
if(bindingResult!=null && bindingResult.hasErrors()){
List<FieldError> fieldErrorList= bindingResult.getFieldErrors();
for(FieldError fieldError: fieldErrorList ){
response.adderror(fieldError.getDefaultMessage());
}
}
}
return response;
}
Related
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
When I run this it will create a new book if valid however upon error it will not post back to the page and I get a 400:
This application has no explicit mapping for /error, so you are seeing this as a fallback.
There was an unexpected error (type=Bad Request, status=400).
Validation failed for object='book'. Error count: 4
I tested with system outs, it never gets to the submit if it has errors, I think maybe #Valid is wrong or ???
This is my controller... please tell me what's missing ?
#Controller
#RequestMapping("/")
public class BookController{
#RequestMapping(method=RequestMethod.GET)
public String home(Model model) {
refData = new ReferenceData();
model.addAttribute("refData", refData);
model.addAttribute("book", new Book());
List<Book> books = BookRepo.findAll();
model.addAttribute("books", books);
return "home";
}
#RequestMapping(method=RequestMethod.POST)
public String submit(#Valid Book book,Model model, BindingResult bindingResult) {
refData = new ReferenceData();
model.addAttribute("refData", refData);
if (bindingResult.hasErrors()) {
return "home";
}
BookRepo.save(book);
return "redirect:/";
}
My form looks like this...
<form name="addForm" action="#" th:action="#{/}" th:object="${book}" method="post">
<table>
<tr>
<td><label for="*{title}">Book:</label></td>
<td><input type="text" th:field="*{title}" /></td>
<td th:if="${#fields.hasErrors('title')}" th:errors="*{title}">Name
Error</td>
</tr>
<tr>
<td><label for="*{author}">Author:</label></td>
<td><input type="text" th:field="*{author}" /></td>
<td th:if="${#fields.hasErrors('author')}" th:errors="*{author}">Author
Error</td>
</tr>
<tr>
<td><label for="*{genre}">Genre:</label></td>
<td><input type="text" th:field="*{genre}" /></td>
<td th:if="${#fields.hasErrors('genre')}" th:errors="*{genre}">genre
Error</td>
</tr>
<tr>
<td><label for="*{pages}">Pages:</label></td>
<td><input type="text" th:field="*{pages}" /></td>
<td th:if="${#fields.hasErrors('pages')}" th:errors="*{pages}">pages
Error</td>
</tr>
<tr>
<td><label th:for="*{year}">Year:</label></td>
<td>
<select th:field="*{year}" ng-model="bookData.year">
<option th:each="selectItem: ${refData.years}"
th:value="${selectItem.value}" th:text="${selectItem.label}">year</option>
</select>
</td>
<td th:if="${#fields.hasErrors('year')}" th:errors="*{year}">year
Error</td>
</tr>
<tr>
<td><label th:for="*{rating}">Rating:</label></td>
<td><select th:field="*{rating}" ng-model="bookData.rating">
<option th:each="selectItem: ${refData.rating}"
th:value="${selectItem.value}" th:text="${selectItem.label}">rating</option>
</select></td>
<td th:if="${#fields.hasErrors('rating')}" th:errors="*{rating}">rating
Error</td>
</tr>
<tr>
<td><button type="submit">Submit</button></td>
</tr>
</table>
</form>
my entity...
#Entity
public final class Book
{
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
#NotNull
#Pattern(regexp="^[a-zA-Z0-9_]+$")
private String title;
#NotNull
#Pattern(regexp="^[a-zA-Z0-9_]+$")
private String author;
#NotNull
#Pattern(regexp="^[a-zA-Z0-9_]+$")
private String genre;
#NotNull
#Digits(message="message here", integer=32767, fraction = 0)
private Integer pages;
private String year;
private String rating;
I found I had to place the bindingResult directly after the #Valid Book entity thus...
#RequestMapping(method=RequestMethod.POST)
public String submit(#Valid Book book,**BindingResult bindingResult**, Model model ) {
refData = new ReferenceData();
model.addAttribute("refData", refData);
if (bindingResult.hasErrors()) {
return "home";
}
BookRepo.save(book);
return "redirect:/";
}
Wow what a minor=major mistake !!
Johnny O.
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
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
I am facing a problem with Spring form validation.
It works for #NotNull annotation but some how not working for #Size. I am attaching some code below. Thanks in advance.
package com.doctor;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
public class Doctor
{
#NotNull(message="Cannot be Null")
private String uname;
#Size(min=1,max=8,message="Min 1 and Max 8")
private String password;
private String doctor_fname,doctor_lname,address,dept_id,experience,email,phone,resume,image;
public String getUname() {
return uname;
}
public void setUname(String uname) {
this.uname = uname;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
....................
...................
DoctorController
package com.doctor;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.ui.Model;
import javax.validation.Valid;
#Controller
public class DoctorController {
#RequestMapping(value="/registerDoctor", method=RequestMethod.GET)
public String showRegisterForm(Model model)
{
System.out.println("test");
model.addAttribute(new Doctor());
//return "register1";
return "doctor/edit";
}
#RequestMapping(value="/registerDoctor", method=RequestMethod.POST)
public String addDoctorformForm(#Valid Doctor doctor,BindingResult bindingresult)
{
if(bindingresult.hasErrors())
{
return "doctor/edit";
}
else
{
return "doctor/added";
}
}
}
Display page
<%# taglib prefix="sf" uri="http://www.springframework.org/tags/form"%>
<h2>Create a Doctor account</h2>
<sf:form method="POST" modelAttribute="doctor"
enctype="multipart/form-data">
<fieldset>
<table>
<tr>
<td><sf:label path="uname">User Name:</sf:label></td>
<td><sf:input path="uname" /><br /> <sf:errors
path="uname" /> </td>
</tr>
<tr>
<td><sf:label path="password">Password:</sf:label></td>
<td><sf:password path="password" showPassword="true" />
<br /> <sf:errors
path="password" /></td>
</tr>
<tr>
<td><sf:label path="doctor_fname">First Name:</sf:label></td>
<td><sf:input path="doctor_fname" size="15" /><br /> </td>
</tr>
<tr>
<td><sf:label path="doctor_lname">Last Name:</sf:label></td>
<td><sf:input path="doctor_lname" size="15" /><br /></td>
</tr>
<tr>
<td><sf:label path="address">Address:</sf:label></td>
<td><sf:input path="address" size="15" /><br /></td>
</tr>
<tr>
<td><sf:label path="dept_id">Department:</sf:label></td>
<td><sf:input path="dept_id" size="15" /><br /></td>
</tr>
<tr>
<td><sf:label path="experience">Experience:</sf:label></td>
<td><sf:input path="experience" size="15" /><br /></td>
</tr>
<tr>
<td><sf:label path="email">Email Address:</sf:label></td>
<td><sf:input path="email" size="30" /> <small>In case
you forget something</small><br /> </td>
</tr>
<tr>
<td><sf:label path="phone">Phone:</sf:label></td>
<td><sf:input path="phone" size="30" /> <small>In case
you forget something</small><br /> </td>
</tr>
<tr>
<td><label for="resume">Resume:</label></td>
<td><input name="resume" type="file" />
</tr>
<tr>
<td><label for="image">Profile image:</label></td>
<td><input name="image" type="file" />
</tr>
<tr>
<th></th>
<td><input name="commit" type="submit">
</tr>
</table>
</fieldset>
</sf:form>
I don't understand why #Size for password is not working.
Help will be highly appreciated.
It is because null is a valid value from #Sizes point of view.
You need both annotations:
#Size(min=1,max=8,message="Min 1 and Max 8")
#NotNull
private String password;
BTW: Your form is a simple form with no file upload, so there is no need to have `enctype="multipart/form-data" - I would remove it
The issue it seems is you are using multipart form but I dont think I see a mention about multipartResolver. If needed here is how you can add it
<bean id="multipartResolver class="org.springframework.web.multipart.commons.CommonsMultipartResolver">