I'm trying to achieve the JSR 303 bean validation in Spring 3.0 by using a simple login use case. The problem is if I submit the form without any value the validation is not happening (i.e the BindingResult method hasErrors() always returning 'false' and printing I'm cool !. Following is the code snippet:
#Controller
public class AnnotatedController {
#RequestMapping(value = "login")
public String validateLogin(#Valid LoginForm loginForm, BindingResult result, HttpServletRequest request) {
if(result.hasErrors())
System.out.println("Got Errors !");
else
System.out.println("I'm cool !");
return "login";
}
}
The bean looks like this :
public class LoginForm {
#NotEmpty
private String userName;
#Size(min=2, max=3)
private String password;
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;
}
}
Finally the view:
<table>
<form:form action="login.htm" modelAttribute="loginForm">
<tr>
<td>User :</td>
<td><form:input path="userName" /></td>
</tr>
<tr>
<td>Password :</td>
<td><form:input path="password" /></td>
</tr>
<tr><td><input type="submit" value="Ok"> </tr>
</form:form>
</table>
What am I missing ?
Adding <mvc:annotation-driven/>in servlet context XML fixed the issue for me.
you are missing form error tag.use like
<table>
<form:form action="login.htm" commandName="logindetails">
<tr>
<td>User :</td>
<td><form:input path="userName" /></td>
<td><form:errors path="userName" /></td>
</tr>
<tr>
<td>Password :</td>
<td><form:input path="password" /></td>
<td><form:errors path="password" /></td>
</tr>
<tr><td><input type="submit" value="Ok"> </tr>
</form:form>
and also you have to maintain property file with error message.
NotEmpty.logindetails.userName = userName is required!
Range.logindetails.password= password value must be between 2 and 3
Example:
Click here
Related
I have class User and userRole, I need to bind UserRole object in User
i tried below code
UserRole.java
public class UserRoleBean {
private Integer role_id;
private String roleName;
private String roleDesc;
//getter setter
}
User.java
public class UserBean {
private Integer userId;
private String firstName;
private String lastName;
private Date dob;
private String emailAddr;
private String mobileNo;
private Integer balance;
private String password;
private UserRoleBean roleBean;
//getter and setter;
}
AddUser.jsp
<form:form method="POST" action="saveUser.html" modelAttribute="userBean">
<table>
<tr>
<td><form:label path="userId">User ID:</form:label></td>
<td><form:input path="userId" value="${user.userId}" readonly="true"/></td>
</tr>
<tr>
<td><form:label path="firstName">First Name:</form:label></td>
<td><form:input path="firstName" value="${user.firstName}"/></td>
</tr>
<tr>
<td><form:label path="lastName">Last Name :</form:label></td>
<td><form:input path="lastName" value="${user.lastName}"/></td>
</tr>
<tr>
<td><form:label path="emailAddr">Email Address :</form:label></td>
<td><form:input path="emailAddr" value="${user.emailAddr}" readonly="false"/></td>
</tr>
<tr>
<td><form:label path="dob">Date Of Birth:</form:label></td>
<td><form:input path="dob" /></td>
</tr>
<tr>
<td><form:label path="mobileNo">Mobile No :</form:label></td>
<td><form:input path="mobileNo" value="${user.mobileNo}"/></td>
</tr>
<tr>
<td><form:label path="password">Password:</form:label></td>
<td><form:password path="password" value="${user.password}"/></td>
</tr>
<tr>
<td><form:label path="balance">Balance:</form:label></td>
<td><form:input path="balance" value="${user.balance}"/></td>
</tr>
<tr>
<td><form:label path="roleBean">Select Role:</form:label></td>
<td>
<form:select path="roleBean">
<form:option value="0" label="Select" />
<form:options items="${forRoles}" itemValue="role_id" itemLabel="roleName" />
</form:select>
</td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="${cap}"/></td>
</tr>
</table>
</form:form>
Other Property is bind but roleBean unable to bind, how to do this,
any help would be appreciated
You have to set each property of roleBean seperately like you were doing for User object.
While setting any property of roleBean use roleBean.role_id for Id, `roleBean.roleName' for 'roleName'.
Like your path for roleName is <form:select path="roleBean"> but it should be <form:select path="roleBean.roleName"> if its for roleName. Same goes for other attributes.
I was able to create values and store into my db, which displays a view of the list of values stored and additional values that is written into a input will automatically show in the table.
Controller
#Controller
public class AppPortController {
private ApServerService apServerService;
#Autowired
public void setApServerService(ApServerService apServerService) {
this.apServerService = apServerService;
}
#RequestMapping(value = "/editApServer", method = RequestMethod.GET)
public String list(Model model) {
model.addAttribute("apList", apServerService.listAllApServerModels());
return "editApServer";
}
#RequestMapping("editApServer/update/{id}")
public String update(#PathVariable String id, Model model) {
model.addAttribute("apList", apServerService.getApServerModelById(id));
return "editApServer";
}
#RequestMapping("editApServer/new")
public String newServer(Model model){
model.addAttribute("apServer", new ApServerModel());
return "editApServer";
}
#RequestMapping(value = "/addServer", method = RequestMethod.POST)
public String addServer(#ModelAttribute ApServerModel apServerModel) {
apServerService.saveApServerModel(apServerModel);
return "redirect:editApServer";
}
#RequestMapping("editApServer/delete")
public String delete(#PathVariable String host){
apServerService.deleteApServerModel(host);
return "redirect:editApServer";
}
Repository
public interface AppPortRepository extends CrudRepository<ApServerModel, String> {}
POJO
#Document(collection = "apDBServer")
public class ApServerModel {
#Id
private String id;
private String host;
private String port;
//getters and setters
HTML SNIPPET
<table>
<thead>
<tr>
<th> Host Name </th>
<th> Port Name</th>
<th>Id</th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
<tr th:each="ApServerModel : ${apList}">
<td th:text ="${ApServerModel.host}"></td>
<td th:text ="${ApServerModel.port}"></td>
<td th:text ="${ApServerModel.id}"></td>
<td><a th:href="${'editApServer/update/' + ApServerModel.id}">Edit</a></td>
<td><a th:href="${'editApServer/delete'}">Delete</a></td>
</tr>
</tbody>
</table>
<br />
<h2>Add AppPortServer</h2>
<form action="/addServer" method="POST">
Host <input type="text" id="host" name="host" /><br />
Port <input type="text" id="port" name="port" /><br />
<input type="submit" />
</form>
Problem
In my controller the delete would not execute(it is not doing what I want it to do). but line below it redirects me back to the same page.
What am I doing wrong? I have been savaging through the internet trying to find the crud functions for mongodb using springboot. Logically speaking why wouldn't my delete work if I follow the logic of the create?
I followed Tutorial, for posting to a table. Then I followed
Tutorial 2 That implements my delete and update. But It does not delete the values.
org.apache.jasper.JasperException: An exception occurred processing JSP page /WEB-INF/jsp/admissionForm.jsp at line 33
Getting error on line 33. I'm new to Spring MVC and cannot figured out this error
:
30: <table>
31: <tr>
32: <td>Customer Name :</td>
33: <td><form:input path="studentName" /></td>
34: <td><form:errors path="studentName" cssClass="error" /></td>
35: </tr>
36: <tr>
Model Class
#Entity
public class Student {
#NotEmpty
private String studentName;
#Size(min=2,max=43)
private String major;
private Long studentMobile;
private Date studentDOB;
private ArrayList<String> studentSkills;
private Address studentAddress;
}
Controller
#RequestMapping(value = "/admissionForm", method = RequestMethod.GET)
public ModelAndView addmissionForm(){
ModelAndView mv = new ModelAndView("admissionForm");
return mv;
}
#RequestMapping(value = "/submitAdmissionForm" , method = RequestMethod.POST)
public ModelAndView submitAdmissionForm(#Valid #ModelAttribute("student1") Student student1, BindingResult result){
if(result.hasErrors()){
ModelAndView model1 = new ModelAndView("admissionForm");
return model1;
}
ModelAndView mv = new ModelAndView("admissionSuccess");
return mv;
}
JSP
<h2> SignUp Form - JSR303 #Valid example</h2>
<form:form method="POST" modelAttribute="student1" action="/submitAdmissionForm">
<form:errors path="*" cssClass="errorblock" element="div" />
<table>
<tr>
<td>Customer Name :</td>
<td><form:input path="studentName" /></td>
<td><form:errors path="studentName" cssClass="error" /></td>
</tr>
<tr>
<td>Customer Age :</td>
<td><form:input path="major" /></td>
<td><form:errors path="major" cssClass="error" /></td>
</tr>
<tr>
<td colspan="3"><input type="submit" /></td>
</tr>
</table>
</form:form>
I am new to SPRING MVC. I am not getting all the details of employee which contains phone and address object as well. Actually, those object are not being binded with employee.
Follow the code:
//(Controller)
EmployeeController.java
#Controller
#RequestMapping(value = "/employee")
public class EmployeeController {
#Autowired
EmployeeService employeeService;
#RequestMapping("/employee")
public ModelAndView registerEmployeer(#ModelAttribute Employee employee) {
Map<String, Object> modelMap = new HashMap<>();
modelMap.put("employee", new Employee());
return new ModelAndView("employee", modelMap);
}
#RequestMapping("/add")
public String addemployee(#ModelAttribute Employee employee) {
employeeService.save(employee);
return "result";
}
#ModelAttribute("phoneTypeList")
public Map<String,String> populatePhoneTypeList()
{
return Phone.getPhoneTypes();
}
#ModelAttribute("addressTypeList")
public Map<String,String> populateAddressTypeList()
{
return Address.getAddressTypes();
}
}
//Form which takes employee details
employee.jsp
<h2>Employee Information</h2>
<form:form method="POST" action="employee/add"
modelAttribute="employee">
<table>
<tr>
<td><form:label path="ssn">SSN</form:label></td>
<td><form:input path="ssn" /></td>
</tr>
<tr>
<td><form:label path="firstname">First Name</form:label> </td>
<td><form:input path="firstname" /></td>
</tr>
<tr>
<td><form:label path="lastname">Last Name</form:label></td>
<td><form:input path="lastname" /></td>
</tr>
<tr>
<td><form:label path="dob">Date of Birth</form:label></td>
<td><form:input path="dob" /></td>
</tr>
<tr>
<td><form:label path="emailid">Email</form:label></td>
<td><form:input path="emailid" /></td>
</tr>
<tr>
<td>Phone Type:</td>
<td><form:select path="phoneList[0].phonetype" multiple="false">
<form:option value="NONE" label="--- Select ---" />
<form:options items="${phoneTypeList}" />
</form:select></td>
</tr>
<tr>
<td></td>
</tr>
<tr>
<td></td>
</tr>
<tr>
<td><form:label path="phoneList[0].phoneno">Phone</form:label></td>
<td><form:input path="phoneList[0].phoneno" /></td>
</tr>
<tr>
<td>Address Type:</td>
<td><form:select path="addressList[0].addresstype"
multiple="false">
<form:option value="NONE" label="--- Select ---" />
<form:options items="${addressTypeList}" />
</form:select></td>
<tr>
<td><form:label path="addressList[0].street">Street</form:label></td>
<td><form:input path="addressList[0].street" /></td>
</tr>
<tr>
<td><form:label path="addressList[0].city">City</form:label></td>
<td><form:input path="addressList[0].city" /></td>
</tr>
<tr>
<td><form:label path="addressList[0].state">State</form:label></td>
<td><form:input path="addressList[0].state" /></td>
</tr>
<tr>
<td><form:label path="addressList[0].zip">Zip</form:label></td>
<td><form:input path="addressList[0].zip" /></td>
</tr>
<tr>
<td><form:label path="addressList[0].country">Country</form:label></td>
<td><form:input path="addressList[0].country" /></td>
</tr>
<tr>
<td></td>
</tr>
<tr>
<td></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit"
value="Submit" /></td>
</tr>
</table>
</form:form>
//Result after submitting form
result.jsp
<h2>Submitted Employee Information</h2>
<table>
<tr>
<td>SSN</td>
<td>${employee.ssn}</td>
</tr>
<tr>
<td>First Name</td>
<td>${employee.firstname}</td>
</tr>
<tr>
<td>Last Name</td>
<td>${employee.lastname}</td>
</tr>
<tr>
<td>Date of Birth</td>
<td>${employee.dob}</td>
</tr>
<tr>
<td>Email</td>
<td>${employee.emailid}</td>
</tr>
<tr>
<td>Phone Type</td>
<td>${employee.phoneList[0].phonetype}</td>
</tr>
<tr>
<td>Phone</td>
<td>${phoneList[0].phoneno}</td>
</tr>
<tr>
<td>Address Type</td>
<td>${addressList.addressTypeList}</td>
</tr>
<tr>
<td>Street</td>
<td>${addressList.street}</td>
</tr>
<tr>
<td>City</td>
<td>${addressList.city}</td>
</tr>
<tr>
<td>State</td>
<td>${addressList.state}</td>
</tr>
<tr>
<td>Zip</td>
<td>${addressList.zip}</td>
</tr>
<tr>
<td>Country</td>
<td>${addressList.country}</td>
</tr>
</table>
//my employee bean looks like this
employee.java
public class Employee {
private List<Phone> phoneList = new ArrayList<Phone>();
private List<Address> addressList = new ArrayList<Address>();
private long ssn;
private String firstname;
private String lastname;
private String dob;
private String emailid;
public long getSsn() {
return ssn;
}
public void setSsn(long ssn) {
this.ssn = ssn;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public String getDob() {
return dob;
}
public void setDob(String dob) {
this.dob = dob;
}
public String getEmailid() {
return emailid;
}
public void setEmailid(String emailid) {
this.emailid = emailid;
}
public void addPhone(Phone ph) {
phoneList.add(ph);
}
public void addAddress(Address ad) {
addressList.add(ad);
}
public void setPhoneList(List<Phone> phoneList) {
this.phoneList = phoneList;
}
public List<Phone> getPhoneList() {
return phoneList;
}
public List<Address> getAddressList() {
return addressList;
}
public void setAddressList(List<Address> adList) {
this.addressList = adList;
}
}
I can get only those details of employee like ssn, first name, last name etc but not phone type, phone no, address details which are the field of another objects. My assumption is the binding is not working here. Any idea?
I had a similar problem, solved by removing this line:
#OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)
before the #ElementCollection that was not copied.
You are missing "employee" as prefix & index in list elements when reading them.
<tr>
<td>Phone</td>
<td>${employee.phoneList[0].phoneno}</td>
</tr>
<tr>
<td>Address Type</td>
<td>${employee.addressList[0].addressTypeList}</td>
</tr>
<tr>
<td>Street</td>
<td>${employee.addressList[0].street}</td>
</tr>
<tr>
<td>City</td>
<td>${employee.addressList[0].city}</td>
</tr>
<tr>
<td>State</td>
<td>${employee.addressList[0].state}</td>
</tr>
<tr>
<td>Zip</td>
<td>${employee.addressList[0].zip}</td>
</tr>
<tr>
<td>Country</td>
<td>${employee.addressList[0].country}</td>
</tr>
I am trying to connect my JSP servlets to a posgress database and I am currently using a java bean class which is playing the role of the middle man. I am experiencing some difficulties with making the registration form successfully store user information into the database. I would really appreciate if you would kindly help me out.
Thanks a lot in advance.
JSP servlet:
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Register here</title>
</head>
<body>
<form method="post" action="registration.jsp">
<center>
<table border="1" width="30%" cellpadding="5">
<thead>
<tr>
<th colspan="2">Enter Information Here</th>
</tr>
</thead>
<tbody>
<tr>
<td>First Name</td>
<td><input type="text" name="fname" value="" /></td>
</tr>
<tr>
<td>Last Name</td>
<td><input type="text" name="lname" value="" /></td>
</tr>
<tr>
<td>Email</td>
<td><input type="text" name="email" value="" /></td>
</tr>
<tr>
<td>User Name</td>
<td><input type="text" name="uname" value="" /></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" name="pass" value="" /></td>
</tr>
<tr>
<td>Current Country</td>
<td><input type="text" name="country" value="" /></td>
</tr>
<tr>
<td>Current City</td>
<td><input type="text" name="city" value="" /></td>
</tr>
<tr>
<td><input type="submit" value="Submit" /></td>
<td><input type="reset" value="Reset" /></td>
</tr>
<tr>
<td colspan="2">Already have an account? Login Here</td>
</tr>
</tbody>
</table>
</center>
</form>
</body>
The Java Bean that I use :
public class UserBean {
private int id;
private String username;
private String password;
private String email;
private String firstName;
private String lastName;
private String endDate;
private boolean validated;
public UserBean() {
// Empty constructor
}
public int getId() {
return id;
}
public String getUsername() {
return username;
}
public String getPassword() {
return password;
}
public String getEmail() {
return email;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public String getEndDate() {
return endDate;
}
public boolean isValidated() {
return validated;
}
public void setId(int id) {
this.id = id;
}
public void setUsername(String username) {
this.username = username;
}
public void setPassword(String password) {
this.password = password;
}
public void setEmail(String email) {
this.email = email;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public void setEndDate(String endDate) {
this.endDate = endDate;
}
public void setValidated(boolean validated) {
this.validated = validated;
}
}
Your POJO JavaBean won't magically get populated with the data. It has no connection to the database and no way to get or save data.
You need a controller that fetches data from the DB, creates model objects, and populates them with the data. The controller is also responsible for saving beans
You could write this yourself but it's generally better to use existing ORM frameworks like JPA2, a custom persistence provider API like Hibernate, or something like MyBatis. If you really want, you can hand-roll your controller with direct JDBC calls, injecting the connection from the environment, but that tends to produce a lot of boilerplate code for little benefit even with things like Spring JDBC to help smooth things over.
Some IDEs, like NetBeans and Eclipse, can even auto-generate models and controllers for you, though I've never been very happy with the results (particularly the failure to use a parent-class and generic methods and the lack of any sort of useful error handling).