Problem with displaying List by jsp in Java - java

Hi i have a problem with my project,That's my posts.jsp
<!DOCTYPE html>
<html>
<head>
<title>Blog Site-posts</title>
</head>
<body>
<div class="container">
<table class="table table-striped">
<thead>
<tr>
<th>Description</th>
<th>Date</th>
<th>Completed</th>
<th>Written by</th>
</tr>
</thead>
<tbody>
<c:forEach items="${posts}" var="Post">
<tr>
<td>${Post.postId}</td>
<td><fmt:formatDate pattern="dd/MM/yyyy"
value="${post.postDate}" /></td>
<td>${Post.text}</td>
<td>${Post.authorId}</td>
</tr>
</c:forEach>
</tbody>
</table>
</div>
</body>
</html>
That's my PostController
#Controller
public class PostController {
#Autowired
PostService postService;
#RequestMapping(value="/posts",method = RequestMethod.GET)
public String showPosts(ModelMap model) {
model.addAttribute("posts",postService.findall());
return "posts";
}
}
and that is my post class
public class Post {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private int postId;
//#Column(unique=true)
//#NotEmpty
private String title;
//#Column(length=20000)
#Size(max=20000, message="Message cannot be longer than 20000 characters!")
//#NotEmpty
private String text;
private Date postDate;
private int authorId;
I want to display elements of List with posts in jsp to see how it works , but it looks like this :
enter image description here
What's wrong with jsp or controller?

Add this to posts.jsp before tag html :
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

Related

How to fill a jsp form by the data from MySQL database?

I have a jsp page in which there is a dropdown list of some products which is populated from the database. What I want is, when the user selects a product, I want the rate field to be populated automatically from the database.
My jsp page:
<%# page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html, charset=utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="http://code.jquery.com/jquery-1.8.3.js"></script>
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css" />
<title>Purchase new product </title>
</head>
<body>
<script>
$(function() {
$('input[name=date]').datepicker();
});
function multiply()
{
var q = document.getElementById('quantity').value;
var r = document.getElementById('rateid').value;
document.getElementById('total').value = q*r;
}
</script>
<div class="container">
<h1>Place your order:</h1><br/>
<form method="post" action="PurchaseController" name="pform">
<table class="table table-striped table-hover table-condensed table-bordered">
<tr>
<td>Product:</td>
<td><select name="selectedProduct">
<option value=0>Select one</option>
<c:forEach items="${product}" var="product">
<option value="${product.pid}"><c:out value="${product.name}" /> </option>
</c:forEach>
</select>
</td>
</tr>
<tr>
<td>Quantity:</td>
<td><input type="number" name="quantity" id="quantity" oninput="multiply()"
onkeypress="return event.charCode >=48" min="1" required>
</td>
</tr>
<tr>
<td>Rate:</td>
<td><input type="text" name="rate" id="rateid" oninput="multiply()" <%-- value="<c:out value="${product.rate}" />" --%> >
</td>
</tr>
<tr>
<td>Total:</td>
<td><input type="number" name="total" id="total" readonly ></td>
</tr>
<tr>
<td>Date:</td>
<td><input type="text" name="date" placeholder="Date" required></td>
</tr>
</table>
<input type="submit" value="Submit" class="btn btn-primary">
<input type="reset" value="Reset" class="btn btn-danger">
</form>
<br/>
Back to home
</div>
</body>
</html>
When I uncomment the commented parts in the "Rate" field in the above code, I get the NumberFormatException error as follows:
org.apache.jasper.JasperException: An exception occurred processing JSP page [/purchase.jsp] at line [55]
52: <tr>
53: <td>Rate:</td>
54: <td><input type="text" name="rate" id="rateid" oninput="multiply()"
55: value="<c:out value="${product.rate}" />" >
56: </td>
57: </tr>
58: <td>Total:</td>
Stacktrace:
org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:584)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:481)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:386)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:330)
javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
com.product.controller.ProductController.doGet(ProductController.java:57)
javax.servlet.http.HttpServlet.service(HttpServlet.java:635)
javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
Root Cause
java.lang.NumberFormatException: For input string: "rate"
java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
java.lang.Integer.parseInt(Integer.java:580)
java.lang.Integer.parseInt(Integer.java:615)
javax.el.ListELResolver.coerce(ListELResolver.java:150)
javax.el.ListELResolver.getValue(ListELResolver.java:67)
org.apache.jasper.el.JasperELResolver.getValue(JasperELResolver.java:110)
org.apache.el.parser.AstValue.getValue(AstValue.java:169)
org.apache.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:190)
org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate(PageContextImpl.java:944)
org.apache.jsp.purchase_jsp._jspx_meth_c_005fout_005f1(purchase_jsp.java:310)
org.apache.jsp.purchase_jsp._jspService(purchase_jsp.java:178)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:443)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:386)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:330)
javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
com.product.controller.ProductController.doGet(ProductController.java:57)
javax.servlet.http.HttpServlet.service(HttpServlet.java:635)
javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
I tried changing the type of input field of Rate to "number" but the same error occurs.
As the error is shown in the value="<c:out value="${product.rate}" />" line and there is no error when I comment this, I presume that I am using the EL in wrong ways?
But the list of products in the drop down is showing properly where I have used EL as well.
Could someone tell me what I am doing wrong?
Thanks.
EDIT:
The product class is as follows:
public class Product {
private int pid;
private String name;
private int quantity;
private int rate;
private int total;
private Date date;
public int getPid() {
return pid;
}
public void setPid(int pid) {
this.pid = pid;
}
public Date getDate() {
return date;
}
public String getName() {
return name;
}
public int getQuantity() {
return quantity;
}
public int getRate() {
return rate;
}
public int getTotal() {
return total;
}
public void setDate(Date date) {
this.date = date;
}
public void setName(String name) {
this.name = name;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public void setRate(int rate) {
this.rate = rate;
}
public void setTotal(int total) {
this.total = total;
}
}
To me everything looks good; are you sure you didnt inserted 'rate' as a value?
Try outputting rate without el and see what the actual value is:
${product.rate}
Create a javascript function
function setRate(el) {
document.getElementById("rate").value = el.value;
}
And add this to the select:
<select name="selectedProduct" onchange=setRate(this)>

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.

Form values not getting displayed on POST in spring-java-mvc [duplicate]

i am new to spring mvc
i created a project using SpringTemplateProject and used hibernate in that.
i created a form and on post the values are getting inserted in database but the problem is i am not able to display those values on POST.
here is the code.
//Controller
package com.projects.data;
import java.util.Locale;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.projects.data.*;
#Controller
public class HomeController {
private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
#Autowired
ServiceImpl service;
#RequestMapping(value = "/", method = RequestMethod.GET)
public String customer(Locale locale, Model model) {
logger.info("Welcome home! The client locale is {}.", locale);
return "home";
}
#RequestMapping(value = "/customer", method = RequestMethod.POST)
public String addCustomer(#ModelAttribute("customer") Customer customer,Model model)
{
service.addCustomer(customer);
return "customer/customer";
}
}
Home.jsp
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%# page session="false" %>
<html>
<head>
<title>Home</title>
</head>
<body>
<spring:url var="customer" value="/customer"/>
<form:form action="${customer}" method="post" modelAttribute="customer" commandName="custform">
<form:label path="custid">Id:</form:label>
<form:input path="custid"/> <br>
<form:label path="name">Name:</form:label>
<form:input path="name"/> <br>
<form:label path="age">Age:</form:label>
<form:input path="age"/> <br>
<input type="submit" value="Save"/>
</form:form>
</html>
customer.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!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>Submitted Information</title>
</head>
<body>
<h2>Submitted Information</h2>
<table>
<tr>
<td>Customer id</td>
<td>${custform.custid}</td>
</tr>
<tr>
<td>Name</td>
<td>${custform.name}</td>
</tr>
<tr>
<td>Age</td>
<td>${custform.age}</td>
</tr>
</table>
</body>
</html>
Data is getting inserted in the database but it is not getting displayed.Please help me resolve this.
I tried using #modelAttribute
model.addAttribute("custid",customer.getCustId());
model.addAttribute("name", customer.getName());
model.addAttribute("age", customer.getAge());
But this also does not seem to work.
Model Class
package com.projects.data;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="customer")
public class Customer {
#Id
#Column(name="CUST_ID")
int custId;
#Column(name="NAME")
String name;
#Column(name="AGE")
int age;
public Customer(int custId,String name,int age)
{
this.custId=custId;
this.name=name;
this.age=age;
}
//getter and setter methods
public Customer() {
// TODO Auto-generated constructor stub
}
public int getCustId() {
return custId;
}
public void setCustId(int custId) {
this.custId = custId;
}
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;
}
}
Remove custform. from ${custform.age},${custform.name} and ${custform.custid} in jsp and keep yout model.addAttribute as it is in controller. You should be able to access age from customer using ${age} in jsp.
Controller:
#RequestMapping(value = "/customer", method = RequestMethod.POST)
public String addCustomer(#ModelAttribute("customer") Customer customer,Model model)
{
service.addCustomer(customer);
model.addAttribute("custid",customer.getCustId());
model.addAttribute("name", customer.getName());
model.addAttribute("age", customer.getAge());
return "customer/customer";
}
JSP:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!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>Submitted Information</title>
</head>
<body>
<h2>Submitted Information</h2>
<table>
<tr>
<td>Customer id</td>
<td>${custid}</td>
</tr>
<tr>
<td>Name</td>
<td>${name}</td>
</tr>
<tr>
<td>Age</td>
<td>${age}</td>
</tr>
</table>
</body>
</html>
OR
simply do model.addAttribute("custform",customer); in controller and leave everything else as it is.
Controller
#RequestMapping(value = "/customer", method = RequestMethod.POST)
public String addCustomer(#ModelAttribute("customer") Customer customer,Model model)
{
service.addCustomer(customer);
model.addAttribute("custform",customer);
return "customer/customer";
}
JSP
Keep it same as in question.
Try
#RequestMapping(value = "/customer", method = RequestMethod.POST)
public ModelAndView addCustomer(#ModelAttribute("customer") Customer customer)
{
service.addCustomer(customer);
Model model = new ModelMap();
model.addAttribute("custid",customer.getCustId());
model.addAttribute("name", customer.getName());
model.addAttribute("age", customer.getAge());
return new ModelAndView("customer/customer", model);
}
BTW: A better approach is to redirect (http code 303) to a customer show page, after the post. Then the user can Reload the Page (F5) without creating a new customer while each refresh.

Getting a list of the repeated last form data when trying to fetch the list of objects from database

My first jsp is email.jsp and from there it is directed to template.jsp but when I try to get the list of EmailMessages object, I get repeated entries of the last form submitted data when I must be getting all the objects the database. Can anyone please help me through this?
#RequestMapping(value = "/email", method = RequestMethod.GET)
public String addEmail() {
return "email";
}
#RequestMapping(value = "/template", method = RequestMethod.POST)
public String getTemplateEmail(#ModelAttribute EmailMessage emailMessage, ModelMap model) {
emailService.insertTemplate(emailMessage);
List<EmailMessage> emailMessageList = new ArrayList<EmailMessage>();
emailMessageList = emailService.fetchTemplate();
model.addAttribute("emailMessageList", emailMessageList);
return "template";
}
email.jsp
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!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=UTF-8">
<title>Email body</title>
</head>
<body>
<form action="/TemplateEmail/template" method="POST">
<table>
<tr>
<td><b>Category </b>: </td>
<td><select name="category">
<option value=""> </option>
<option value="normal">Normal</option>
<option value="urgent">Urgent</option>
</select></td>
<td>
<button type="button" style="width: 25px;height: 25px;border: solid 1px #000;border-radius: 25px" onclick="addCategory()">+</button>
<script>
function addCategory() {
var category = prompt("Add new category", "");
}
</script>
</td>
</tr>
<tr>
<td><b>Subject </b>: </td>
<td><input type="text" name="subject"/></td>
</tr>
<tr>
<td><b>Body </b>: </td>
<td><textarea name="body" rows="10" columns="50"></textarea> </td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="submit" value=" SAVE "/>
</td>
</tr>
</table>
</form>
</body>
</html>
EmailMessage.java
package com.qburst.templateemail.entity;
public class EmailMessage {
private String category;
private String subject;
private String body;
private Long id;
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
}
template.jsp
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!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=UTF-8">
<title>Template Webpage</title>
</head>
<body>
<center>
<table border="1">
<tr>
<th>select</th>
<th>Category</th>
<th>Subject</th>
<th>Body</th>
</tr>
<c:forEach var="emailMessage" items="${emailMessageList}">
<tr>
<td><label for="${emailMessage.id}"></label><input type="radio" name="emailMsg" id="${emailMessage.id}"/></td>
<td>${emailMessage.category}</td>
<td>${emailMessage.subject}</td>
<td>${emailMessage.body}</td>
</tr>
</c:forEach>
</table><br>
<input type="button" onclick="location.href='/TemplateEmail/email'" value="Add More" />
<br><br><br>
<input type="button" onclick="location.href='/TemplateEmail/send_email'" value="Send To" />
</center>
</body>
</html>
EmailDao.java
This is the code for fetching the list from database.
public List<EmailMessage> fetchTemplate() {
String query = "select * from email_message";
Connection connection = null;
List<EmailMessage> emailMessageList = new ArrayList<EmailMessage>();
try {
EmailMessage emailMessage = new EmailMessage();
connection = dataSource.getConnection();
PreparedStatement preparedStatement = connection.prepareStatement(query);
ResultSet resultSet = preparedStatement.executeQuery(query);
while (resultSet.next()) {
emailMessage.setCategory(resultSet.getString("category"));
emailMessage.setSubject(resultSet.getString("subject"));
emailMessage.setBody(resultSet.getString("body"));
emailMessageList.add(emailMessage);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
return emailMessageList;
}
Ok, try to create always new object at the loop:
EmailMessage emailMessage;
while (resultSet.next()) {
emailMessage = new EmailMessage();
emailMessage.setCategory(resultSet.getString("category"));
emailMessage.setSubject(resultSet.getString("subject"));
emailMessage.setBody(resultSet.getString("body"));
emailMessageList.add(emailMessage);
}
You are added repeated link at object to list. You always change values at the all members of list, because it link to one object.

Categories