Spring Thymeleaf TemplateProcessingException in SpringInputGeneralFieldTagProcessor - java

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>
`

Related

How to disable checkbox when it is already used in database - Spring boot jpa

Spring boot using thymeleaf and jpa
I have a reservation application that stores tickets in h2 database using jpa. When someone booked a seat, the checkbox should be disabled for next people, because for now you can reserve the seat over and over again - user should not be able to click the checkbox which is already reservated by other users. How to solve this problem? I can not get through this
reservation-seat.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<title>Movies</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<div class="container my-2">
<div class="card">
<div class="card-body">
<div class="container my-5">
<h1 th:text="${movieName}"> Movie Name</h1>
<form th:action="#{'/reservation/save/' + ${repertoireId}}" th:object="${seatInfo}" method="post">
<div class="seatStructure">
<center>
<table id="seatsBlock">
<p id="notification"></p>
<tr>
<td colspan="14">
<div class="screen">SCREEN</div>
</td>
<br/>
</tr>
<tr>
<td></td>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
<td>5</td>
<td></td>
<td>6</td>
<td>7</td>
<td>8</td>
<td>9</td>
<td>10</td>
<td>11</td>
<td>12</td>
</tr>
<tr>
<td>A</td>
<td><input th:field="*{seatReservation.seat}" type="checkbox" class="seats" value="A1"></td>
<td><input th:field="*{seatReservation.seat}" type="checkbox" class="seats" value="A2"></td>
<td><input th:field="*{seatReservation.seat}" type="checkbox" class="seats" value="A3"></td>
<td><input th:field="*{seatReservation.seat}" type="checkbox" class="seats" value="A4"></td>
<td><input th:field="*{seatReservation.seat}" type="checkbox" class="seats" value="A5"></td>
<td class="seatGap"></td>
<td><input th:field="*{seatReservation.seat}" type="checkbox" class="seats" value="A6"></td>
<td><input th:field="*{seatReservation.seat}" type="checkbox" class="seats" value="A7"></td>
<td><input th:field="*{seatReservation.seat}" type="checkbox" class="seats" value="A8"></td>
<td><input th:field="*{seatReservation.seat}" type="checkbox" class="seats" value="A9"></td>
<td><input th:field="*{seatReservation.seat}" type="checkbox" class="seats" value="A10"></td>
<td><input th:field="*{seatReservation.seat}" type="checkbox" class="seats" value="A11"></td>
<td><input th:field="*{seatReservation.seat}" type="checkbox" class="seats" value="A12"></td>
</tr>
</table>
<input type = "hidden" th:value="${movieName}">
<input type = "hidden" th:value="${repertoireId}">
</br>
<button type="submit">Order.</button>
</center>
</div>
</form>
<br/><br/>
</div>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
ReservationController.java
#Controller
// #Transactional
public class ReservationController {
TicketRepo ticketRepo;
ReservationRepo reservationRepo;
AppUserRepo appUserRepo;
MovieRepo movieRepo;
RepertoireRepo repertoireRepo;
#Autowired
public ReservationController(TicketRepo ticketRepo, ReservationRepo reservationRepo, AppUserRepo appUserRepo,
MovieRepo movieRepo, RepertoireRepo repertoireRepo) {
this.ticketRepo = ticketRepo;
this.reservationRepo = reservationRepo;
this.appUserRepo = appUserRepo;
this.movieRepo = movieRepo;
this.repertoireRepo = repertoireRepo;
}
#GetMapping("/movies/{movieName}/reservation")
public String reservationPage(Model model, #PathVariable ("movieName") String movieName) {
Movie movie = movieRepo.findByTitle(movieName);
List<Repertoire> repertoires = repertoireRepo.findByMovieId(movie.getId());
// model.addAttribute("seat", new SeatReservation());
// model.addAttribute("movieName", movirepertoireseName);
model.addAttribute("repertoires", repertoires);
return "reservation";
}
#GetMapping("/movies/{movieName}/reservation/{repertoireId}")
public String reservationSeatPage(Model model, #PathVariable("movieName") String movieName,
#PathVariable("repertoireId") Long repertoireId) {
Testing testing1 = new Testing();
testing1.setSeatReservation(new SeatReservation());
model.addAttribute("seatInfo", testing1);
model.addAttribute("movieName", movieName);
model.addAttribute("repertoireId", repertoireId);
return "reservation-seat";
}
#PostMapping("/reservation/save/{repertoireId}")
public String reserve(#ModelAttribute ("seatInfo") Testing testing, Principal principal,
#ModelAttribute("repertoireId") Long repertoireId) {
UUID uuid = UUID.randomUUID();
Ticket ticket = new Ticket();
ticket.setSeat(testing.getSeatReservation().getSeat());
ticket.setPrice(20);
ticket.setUuid(uuid);
ticketRepo.save(ticket);
Reservation reservation = new Reservation();
reservation.setTicket(ticketRepo.findByUuid(uuid).get());
Repertoire repertoire = repertoireRepo.findById(repertoireId).get();
reservation.setMovie(movieRepo.findByTitle(repertoire.getMovie().getTitle()));
reservation.setRepertoire(repertoire);
reservation.setAppUser(appUserRepo.findByUsername(principal.getName()));
reservationRepo.save(reservation);
return "redirect:/movies/list";
}
}
SeatReservation.java
import lombok.Data;
#Data
public class SeatReservation {
private String seat;
private boolean active;
public boolean isActive() {
return active;
}
}
Testing.java
import lombok.Data;
#Data
public class Testing {
private SeatReservation seatReservation;
private Long id;
private String string;
private boolean active;
public boolean isActive() {
return active;
}
}
Ticket.java
import lombok.Data;
import javax.persistence.*;
import java.util.UUID;
#Data
#Entity
public class Ticket {
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Id
#Column(name = "id")
private Long id;
private UUID uuid;
private String seat;
private Integer price;
public Ticket() {
}
}
You should be using th:checked for checking/unchecking and th:disabled for enabling/disabling in Thymeleaf where you should evaluate a logical expression inside of these attributes. A simple example regarding your case is as follows:
<td><input th:field="*{seatReservation.seat}" type="checkbox" th:checked="${seatReservation.isActive}" th:disabled="${seatReservation.isActive}" class="seats" value="A6"></td>
Regards

error:"items" does not support runtime expressions in c:forEach jsp

This is my Servlet class
import java.io.IOException;
import java.util.ArrayList;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
#WebServlet("/Register")
public class Register extends HttpServlet {
static int id=0;
private static final long serialVersionUID = 1L;
private static final ArrayList<Employee> EMPLOYEES = new ArrayList<>();
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
id++;
int uage=0;
long mob=0;
String uexit = request.getParameter("uexit");
if(uexit.equals("Exit")) {
System.out.println("\n\n\n\n\n\n\n\n");
request.getRequestDispatcher("exit.jsp").forward(request, response);
}
else {
String uname = request.getParameter("uname");
uage = Integer.parseInt(request.getParameter("uage"));
mob = Long.parseLong(request.getParameter("umob"));
if(uname!=null && uage!=0 && mob!=0) {
Employee employee = new Employee(id, uname, uage, mob);
EMPLOYEES.add(employee);
request.getSession().setAttribute("employees" , EMPLOYEES);
RequestDispatcher rd = getServletContext().getRequestDispatcher("register.jsp");
rd.forward(request, response);
}
else {
request.getSession().setAttribute("employees", null);
request.getRequestDispatcher("register.jsp").forward(request, response);
}
}
for(int i=0; i<EMPLOYEES.size(); i++) {
System.out.print(EMPLOYEES.get(i).id + "\t");
System.out.print(EMPLOYEES.get(i).name + "\t");
System.out.print(EMPLOYEES.get(i).age + "\t");
System.out.print(EMPLOYEES.get(i).mob + "\t");
System.out.println();
}
}
This is my register.jsp page
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="c" uri="http://java.sun.com/jstl/core"%>
<%#page import="java.util.*"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>MyProject</title>
</head>
<h2 align="center">
<font color="#BF360C" size="10" face="Times New Roman"><b><i>
Register</i></b></font>
</h2>
<body style="background-color: #AED6F1">
<form action="Register" method="POST">
<table align="center" cellpadding="20" width="600"
style="background-color: #33C3DD;">
<tr>
<th><font size="5" face="Times New Roman"><b><i>Name:</i></b></font></th>
<td colspan="2" align="center"><input type="text" name="uname"></td>
</tr>
<tr>
<th><font size="5" face="Times New Roman"><b><i>Age:</i></b></font></th>
<td colspan="2" align="center"><input type="text" name="uage"></td>
</tr>
<tr>
<th><font size="5" face="Times New Roman"><b><i>Mobile
Number:</i></b></font></th>
<td colspan="2" align="center"><input type="text" name="umob"></td>
</tr>
<tr>
<th colspan="3" align="center"><input type="submit"
name="uexit" value="Register"><br /> <br /> <input
type="submit" name="uexit" value="Exit"></th>
</tr>
</table>
</form>
<br>
<br>
<table cellpadding="20" cellspacing="5" width="900"
style="background-color: #FDFEFE;" align="center">
<tr style="background-color: #FDFDFD">
<th style="background-color: #4468D1"><font size="5"
face="Times New Roman"><b><i>Sr. No.</i></b></font></th>
<th style="background-color: #4468D1"><font size="5"
face="Times New Roman"><b><i>Name</i></b></font></th>
<th style="background-color: #4468D1"><font size="5"
face="Times New Roman"><b><i>Age</i></b></font></th>
<th style="background-color: #4468D1"><font size="5"
face="Times New Roman"><b><i>Mobile Number:</i></b></font></th>
<th style="background-color: #4468D1"><font size="5"
face="Times New Roman"><b><i>Edit</i></b></font></th>
</tr>
<c:forEach items="${employees}" var="item">
<tr>
<td style="background-color: #4468D1"><c:out value = "${item.id}"/></td>
<td style="background-color: #4468D1"><c:out value = "${item.name}"/></td>
<td style="background-color: #4468D1"><c:out value = "${item.age}"/></td>
<td style="background-color: #4468D1"><c:out value = "${item.mob}"/></td>
</tr>
</c:forEach>
</table>
</body>
</html>
This is my Entity class
public class Employee {
public int id;
public String name;
public int age;
public long mob;
public Employee() {}
public Employee(int id, String name, int age, long mob) {
this.name= name;
this.age= age;
this.mob= mob;
this.id=id;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name=name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age=age;
}
public long getMob() {
return mob;
}
public void setMob(int mob) {
this.mob = mob;
}
}
I want to pass list EMPLOYEES from the servlet to jsp page abd want to show each Employee object with <c:forEach> but it keeps on saying exception. so please anyone answer me.
Also tell me which jstl standard jar to download if i m using tomcat 8.5
i have jstl-jar 1.2 but i dont think it's working because this error is keeps on coming no matter how i do it.
Try to use
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
instead of
<%# taglib prefix="c" uri="http://java.sun.com/jstl/core"%>
in your jsp code
Seems you are doing something wrong here
<tr>
<td>${item}</td>
</tr>
According to your code you are getting list of object in item . How you are printing a list which containing object ?
Try using
<tr>
<td>${item.id}</td>
<td>${item.name}</td>
<td>${item.age}</td>
<td>${item.mob}</td>
</tr>

Failed to convert property value of type java.lang.String to required type long for property phone; nested exce

I am trying to built my first Spring mvc application And working on Spring Mvc Form Validation.I am trying to check for empty field. But when to validate the 'long' type variable with #NotNull annotation it give me the above error.
I don't know how to solve it.
Here is My Student Bean
public class Student {
#NotNull
#Pattern(regexp="[A-Za-z]+")
private String name;
#Size(min=2, max=10)
private String father;
private String cnic;
#NotBlank
private String email;
#NotNull
private long phone;
public long getPhone() {
return phone;
}
public void setPhone(long phone) {
this.phone = phone;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCnic() {
return cnic;
}
public void setCnic(String cnic) {
this.cnic = cnic;
}
public String getFather() {
return father;
}
public void setFather(String father) {
this.father = father;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
And my studentmessage.properties file
Pattern.student1.name=The should not contain any Digits
Size.student1.father=please give the {0} between {2} and {1} characters
NotBlank.student1.email=please the email are requried
NotNull.student1.phone=sPlease provide integer data
Controller Class
#Controller
#RequestMapping(value="/student")
public class StudentController {
#RequestMapping(value="/Student",method=RequestMethod.GET)
public String std(Model m){
m.addAttribute("message", "Welcome To Registration ");
return "studentreg";
}
public ModelAndView insert(#Valid #ModelAttribute("student1") Student student1,BindingResult result) //ModelAttribute is used to directly connect the form data to the bean class
{
if(result.hasErrors()){
ModelAndView model=new ModelAndView("studentreg");
return model;
}
ModelAndView mo=new ModelAndView("success");
mo.addObject("message","user detail");
mo.addObject("stu", student1);
return mo;
}
}
Jsp file is
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%#taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h2 align="center">${ message}</h2>
<form:errors path="student1.phone" style="color:red"/><br>
<form:form name="form" method="post" action="stu" >
<div align="center">
<table>
${ error}
<tr>
<td>Name :</td><td><input type="text" name="name" placeholder="EnterName"></td>
</tr>
<tr>
<td>Father Name</td>
<td><input type="text" name="father" placeholder="EnterFatherName"/></td>
</tr>
<tr>
<td>CNIC</td>
<td><input type="text" name="cnic" placeholder="Enter CNIC"/></td>
</tr>
<tr>
<td>Email</td>
<td><input type="text" name="email" placeholder="Enter Email"/></td>
</tr>
<tr>
<td>Phone:</td>
<td><input type="text" name="phone" placeholder="Enter Phone"/></td>
<form:errors path="phone"/>
</tr>
<tr>
<td><input type="submit" name="submite" value="Send"/></td>
</tr>
</table>
</table>
</table>
</div>
</table>
</form:form>
</body>
</html>
Try to use Long instead of long.
Because long can never be null it is not primitive type.
So you should use Long.

inserting values into database using java netbeans

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;
}
}

Implementing a java bean into a jsp servlet

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).

Categories