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).
Related
I create in controller method:
#RequestMapping(value = "/user/registration", method = RequestMethod.GET)
public String showRegistrationForm(WebRequest request, Model model) {
UserDto userDto = new UserDto();
model.addAttribute("user", userDto);
return "registration";
}
and when I turn to URL localhost:8080/user/registration SpringInputGeneralFieldTagProcessor throw TemplateProcessingException .
org.thymeleaf.exceptions.TemplateProcessingException: Error during
execution of processor
'org.thymeleaf.spring4.processor.SpringInputGeneralFieldTagProcessor'
(template: "registration" - line 12, col 36)
How to resolve this?
registration.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8"/>
<title>Registration page</title>
</head>
<body>
<form name='regForm' th:userDto="${user}" th:action="#{/registration}" enctype="utf8" method="post">
<table>
<tr>
<td>User:</td>
<td><input type="text" th:field="*{username}"/></td>
</tr>
<tr>
<td>Email:</td>
<td><input type='email' th:field="*{email}"/></td>
</tr>
<tr>
<td>Password:</td>
<td><input type='password' th:field="*{password}"/></td>
</tr>
<tr>
<td>Matching password:</td>
<td><input type='password' th:field="*{matchingPassword}"/></td>
</tr>
<tr>
<td><input name="submit" type="submit" value="submit" /></td>
</tr>
</table>
</form>
</body>
</html>
my UserDto.java
package com.eve.web.dto;
import com.eve.validation.ValidEmail;
import org.hibernate.validator.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
public class UserDto {
#NotNull
#NotEmpty
private String username;
#NotNull
#NotEmpty
private String password;
private String matchingPassword;
#ValidEmail
#NotNull
#NotEmpty
private String email;
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 String getMatchingPassword() {
return matchingPassword;
}
public void setMatchingPassword(String matchingPassword) {
this.matchingPassword = matchingPassword;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
since you are using user, you should add to all your attributes user.
here you will find the working code
`
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8"/>
<title>Registration page</title>
</head>
<body>
<form name='regForm' th:userDto="${user}" th:action="#{/registration}" enctype="utf8" method="post">
<table>
<tr>
<td>User:</td>
<td><input type="text" th:field="*{user.username}"/></td>
</tr>
<tr>
<td>Email:</td>
<td><input type='email' th:field="*{user.email}"/></td>
</tr>
<tr>
<td>Password:</td>
<td><input type='password' th:field="*{user.password}"/></td>
</tr>
<tr>
<td>Matching password:</td>
<td><input type='password' th:field="*{user.matchingPassword}"/></td>
</tr>
<tr>
<td><input name="submit" type="submit" value="submit" /></td>
</tr>
</table>
</form>
</body>
</html>
`
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.
It is a simple program for inserting into database.There are no errors but on inserting the value only 2 columns(year and subject) are getting affected in all the other 4 columns it is showing null value.how do I correct it.....................................................................................................
File name-index.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>INSERT</title>
<link rel="stylesheet" type="text/css" href="style1.css" />
</head>
<body>
<h1>Insert File Details</h1>
<form action="loginprocess.jsp">
<table border="1">
<tbody>
<tr>
<td>File No :</td>
<td><input type="text" name="File No" value="" size="50" /></td>
</tr>
<tr>
<td>Name</td>
<td><input type="text" name="Name" value="" size="50" /> </td>
</tr>
<tr>
<td>Place of Origin :</td>
<td><input type="text" name="origin" value="" size="50" /></td>
</tr>
<tr>
<td>Year :</td>
<td><input type="text" name="year" value="" size="50" /> </td>
</tr>
<tr>
<td>Subject :</td>
<td><input type="text" name="subject" value="" size="50" /></td>
</tr>
<tr>
<td>ISBN :</td>
<td><input type="text" name="ISBN" value="" size="50" /> </td>
</tr>
</tbody>
</table>
<input type="reset" value="Clear" name="Clear" />
<input type="submit" value="Submit" name="Submit" />
</form>
</body>
</html>
File name LoginDao.java
package bean;
import java.sql.*;
public class LoginDao {
public static boolean validate(LoginBean bean){
boolean status=false;
try{
Connection conn=ConnectionProvider.getConn();
String sql="insert into file(Fileno,name,place,year,subject,ISBN) values (?,?,?,?,?,?)";
PreparedStatement pstmt =conn.prepareStatement(sql);
pstmt.setInt(1, bean.getfileno());
pstmt.setString(2,bean.getname());
pstmt.setString(3, bean.getoriginPlace());
pstmt.setInt(4, bean.getyear());
pstmt.setString(5, bean.getsubject());
pstmt.setInt(6, bean.getisbn());
int rs=pstmt.executeUpdate();
if(rs>0){status=true;}
}catch(Exception e){}
return status;
}
}
File name LoginBean.java
package bean;
public class LoginBean {
private String name,subject,originPlace;
private int fileno,year,isbn;
public int getfileno() {
return fileno;
}
public void setfileno(int fileno) {
this.fileno = fileno;
}
public String getname() {
return name;
}
public void setname(String name) {
this.name = name;
}
public String getoriginPlace() {
return originPlace;
}
public void setoriginPlace(String originPlace) {
this.originPlace = originPlace;
}
public int getyear() {
return year;
}
public void setyear(int year) {
this.year = year;
}
public String getsubject() {
return subject;
}
public void setsubject(String subject) {
this.subject = subject;
}
public int getisbn() {
return isbn;
}
public void isbn(int isbn) {
this.isbn = isbn;
}
}
File name-loginprocess.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title></title>
</head>
<body>
<%#page import="bean.LoginDao"%>
<jsp:useBean id="obj" class="bean.LoginBean"/>
<jsp:setProperty property="*" name="obj"/>
<%
boolean status=LoginDao.validate(obj);
if(status){
out.println("success");
session.setAttribute("session","TRUE");
}
else
{
out.print("failed");}
%>
<jsp:include page="index.jsp"></jsp:include>
</body>
</html>
If you are using jsp benas tag then property name in class(bean class) and <input > name is jsp must be same.only two field have same name. so only two value are inserted.
In class in jsp
File No fileno
So put same name in class and bean.
I believe that Java cannot match the names in your <input> elements in your JSP file to the correct setter methods in the bean. For example, you had this element and setter:
<input type="text" name="Name" value="" size="50" />
public void setname(String name) {
this.name = name;
}
and the property was never set (due to using setname() instead of setName()), but this did work:
<input type="text" name="year" value="" size="50" />
public void setyear(int year) {
this.year = year;
}
because Java could match year (lowercase) to the correct setter.
Try using the following code:
<tr>
<td>File No :</td>
<td><input type="text" name="FileNo" value="" size="50" /></td>
</tr>
<tr>
<td>Name</td>
<td><input type="text" name="Name" value="" size="50" /> </td>
</tr>
<tr>
<td>Place of Origin :</td>
<td><input type="text" name="Origin" value="" size="50" /></td>
</tr>
<tr>
<td>Year :</td>
<td><input type="text" name="Year" value="" size="50" /> </td>
</tr>
<tr>
<td>Subject :</td>
<td><input type="text" name="Subject" value="" size="50" /></td>
</tr>
<tr>
<td>ISBN :</td>
<td><input type="text" name="ISBN" value="" size="50" /> </td>
</tr>
Use this bean definition:
public class LoginBean {
private String name,subject,originPlace;
private int fileno,year,isbn;
public int getFileNo() {
return fileno;
}
public void setFileFo(int fileno) {
this.fileno = fileno;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getOrigin() {
return originPlace;
}
public void setOrigin(String originPlace) {
this.originPlace = originPlace;
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public int getISBN() {
return isbn;
}
public void setISBN(int isbn) {
this.isbn = isbn;
}
}
In the below Spring form, my object's ID field is populated, but when I receive the submission in the controller method, all of the form's fields are populated except for the ID field. I've quintuple-checked that the field type and getter/setter types are all the same non-primitive, as I've seen many of the other questions on SO similar to this and that seems to be the common issue. The controller doesn't have any method-level #ModelAttributes, so it isn't being populated otherwise.
Here's the declaration of the POST method, as I debugged it on the first containing line and found that the form's id field is empty:
#RequestMapping(value="/{orgId}", method=RequestMethod.POST)
public String editOrganizationPost(#PathVariable int orgId,
#Valid #ModelAttribute(ORG_FORM) OrganizationForm orgForm,
BindingResult result, RedirectAttributes att,
HttpServletRequest request) {
Here's the form object:
public class OrganizationForm {
private Integer id;
#NotBlank
private String name;
#NotBlank
private String description;
private Set<User> users;
int moveToOrganizationId = 0;
String moveToOrganizationName;
int[] moveFromOrganizationUserSelect = null; // List of selected users
// to be moved to a new
// organization
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Set<User> getUsers() {
return users;
}
public void setUsers(Set<User> users) {
this.users = users;
}
public int getMoveToOrganizationId() {
return this.moveToOrganizationId;
}
public void setMoveToOrganizationId(int moveToOrganizationId) {
this.moveToOrganizationId = moveToOrganizationId;
}
public String getMoveToOrganizationName() {
return this.moveToOrganizationName;
}
public void setMoveToOrganizationName(String moveToOrganizationName) {
this.moveToOrganizationName = moveToOrganizationName;
}
public int[] getMoveFromOrganizationUserSelect() {
return this.moveFromOrganizationUserSelect;
}
public void setMoveFromOrganizationUserSelect(
int[] moveFromOrganizationUserSelect) {
this.moveFromOrganizationUserSelect = moveFromOrganizationUserSelect;
}
public boolean isNew() {
return this.id == null || this.id == 0;
}
}
Here is the markup from the JSP file:
<form:form method="post" action="${submitUrl}" commandName="organizationForm">
<form:errors path="*" />
<form:hidden path="id" />
<table class="adminTable editContent">
<tr class="bg_lgtGrey">
<td><fmt:message
key="manageOrganizations.organizationForm.name" />:</td>
<td><form:input path="name" cssClass="inputbox"
tabindex="4" /></td>
</tr>
<tr class="bg_lgtGrey">
<td><fmt:message
key="manageOrganizations.organizationForm.description" />:</td>
<td><form:textarea path="description"
cssClass="inputbox" tabindex="4" /></td>
</tr>
<tr>
<td colspan="2" align="right"><c:choose>
<c:when test="${!organizationForm.new}">
<input type="submit" class="btn btn-primary"
id="submit_button" value="Update" />
</c:when>
<c:otherwise>
<input type="submit" class="btn btn-primary"
id="submit_button" value="Create" />
</c:otherwise>
</c:choose></td>
</tr>
</table>
</form:form>
And here is the generated HTML:
<form id="organizationForm" action="/admin/organizations/1" method="post">
<input id="id" name="id" type="hidden" value="1">
<table class="adminTable editContent">
<tbody><tr class="bg_lgtGrey">
<td>Organization Name:</td>
<td><input id="name" name="name" class="inputbox" tabindex="4" type="text" value="Organization1"></td>
</tr>
<tr class="bg_lgtGrey">
<td>Organization Description:</td>
<td><textarea id="description" name="description" class="inputbox" tabindex="4"></textarea></td>
</tr>
<tr>
<td colspan="2" align="right">
<input type="submit" class="btn btn-primary" id="submit_button" value="Update">
</td>
</tr>
</tbody></table>
</form>
I used Chrome devtools to catch the POST data and here it is:
id=1&name=Organization1&description=
...yet at the breakpoint at the first line of the editOrganizationPost method, the form.id field is set to 0.
I have spent forever trying to figure out why it will bind the name and description but not the ID when sent. I could obviously just inject the ID from the path variable but I am dumbfounded as to why it wouldn't just populate the field naturally.
I had the same problem.. the id field would always be set to 0. Changing the id field to something else didn't work either. After more hit and trail, removing
disabled="true"
from
<form:input path"id" disabled="true"/>
fixed the issue.
I assumed
<form:hidden path="id">
would give the same error but it didn't.
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