ArrayList from server not being displayed on JSP - java

Making a web application that search and sorts through Arraylists that were made by loading the csv, reading the data and storing it in DAO. For some reason when im trying to test if the data can be retrieved and displayed on the JSP.
MajorImportersbycity.csv
"CITY-VILLE","COMPANY-ENTREPRISE","PROVINCE_ENG","PROVINCE_FRA","POSTAL_CODE-CODE_POSTAL","DATA_YEAR-ANNÉE_DES_DONNÉES"
"100 Mile House","BRAD PADDISON CONTRACTING LTD","British Columbia","Colombie-Britannique","V0K 2E0",2014
"100 Mile House","CENTRAL CHEVROLET GMC BUICK LTD.","British Columbia","Colombie-Britannique","V0K 2E0",2014
"100 Mile House","LONE BUTTE SUPPLY LTD.","British Columbia","Colombie-Britannique","V0K 2E0",2014
"100 Mile House","SARVAIR AVIATION LTD.","British Columbia","Colombie-Britannique","V0K 2E0",2014
"Abbotsford","4 SEASON KING MUSHROOMS LTD.","British Columbia","Colombie-Britannique","V4X 1C9",2014
"Abbotsford","A & P FRUIT GROWERS LTD.","British Columbia","Colombie-Britannique","V4X 2M4",2014
"Abbotsford","ABBOTSFORD CONCRETE PRODUCTS LIMITED PARTNERSHIP","British Columbia","Colombie-Britannique","V2S 7W8",2014
....
Listener.java:
public class Listener implements javax.servlet.ServletContextListener {
#Override
public void contextInitialized(ServletContextEvent context) {
try {
LoadCsvData.importersByCity();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void contextDestroyed(ServletContextEvent arg0) {
// TODO Auto-generated method stub
}
}
Listener calls LoadCsvData to load data from csv, parse it and store into global arraylist to be used as global arraylist(populated with the data from csv), LoadCsvData.java:
public class LoadCsvData {
public static ArrayList<Importer> importersByCanCity;
public static ArrayList<Importer> getImportersByCanCity() {
return importersByCanCity;
}
public static void setImportersByCanCity(ArrayList<Importer> importersByCity) {
importersByCanCity = importersByCity;
}
public static ArrayList<HSCode> productHSCode;
public static void importersByCity() throws FileNotFoundException{
try {
ArrayList<Importer> importersByCity = new ArrayList<Importer>();
String data;
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
InputStream url = classLoader.getResourceAsStream("/MajorImportersbycity.csv");
BufferedReader csv = new BufferedReader(new InputStreamReader(url));
String line = csv.readLine();
System.out.println("before while");
while ((line = csv.readLine()) != null){
String[] importer = line.split(",");
String city = importer[0];
String companyName = importer[1];
String province_eng = importer[2];
String province_fr = importer[3];
String postal_code = importer[4];
String year = importer[5].toString();
Importer importers = new Importer(city, companyName, province_eng, province_fr, postal_code);
if (importer != null) {
//System.out.println(importer.toString() + "in while");
importersByCity.add(importers);
}
}
csv.close();
System.out.println(importersByCity.size());
setImportersByCanCity(importersByCity);
} catch (IOException f ) {
System.out.println("in catch clause");
f.printStackTrace();
}
}
}
Created a class that is used as a generic, to load the csv data into objects, Importer.java:
public class Importer {
private String city;
private String companyName;
private String province_eng;
private String province_fr;
private String postal_code;
public Importer(String city, String companyName, String province_eng, String province_fr, String postal_code) {
this.city = city;
this.companyName = companyName;
this.province_eng = province_eng;
this.province_fr = province_fr;
this.postal_code = postal_code;
}
public String getCity() {
return city;
}
private void setCity(String city) {
this.city = city;
}
public String getCompanyName() {
return companyName;
}
private void setCompanyName(String companyName) {
this.companyName = companyName;
}
public String getProvince_eng() {
return province_eng;
}
private void setProvince_eng(String province_eng) {
this.province_eng = province_eng;
}
public String getProvince_fr() {
return province_fr;
}
private void setProvince_fr(String province_fr) {
this.province_fr = province_fr;
}
public String getPostal_code() {
return postal_code;
}
public void setPostal_code(String postal_code) {
this.postal_code = postal_code;
}
#Override
public String toString(){
return "Importer [name =" + getCompanyName() + ", province=" + getProvince_eng() + " city=" + getCity() + " postal code=" + getPostal_code() + "]";
}
}
I created a test class to be a servlet to test if i can now use my loaded arraylist in my jsp, Test.java:
public class Test extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, java.io.IOException {
try {
System.out.println("gets to test servlet");
List<Importer> beans = LoadCsvData.getImportersByCanCity();
request.setAttribute("beans", beans);
request.getRequestDispatcher("index.jsp").forward(request, response);
System.out.println(beans.size());
} catch (Throwable theException) {
System.out.println(theException);
}
}
}
My jsp loads, but it only loads the table header. The table isnt populate with the data from the CSV, index.jsp:
<%# page import="com.importersconnect.importersdata.Importer"
import="com.importersconnect.listener.LoadCsvData" language="java"
contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%# 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=ISO-8859-1">
<title>Importers Connect</title>
</head>
<body>
<h1>Importers List</h1>
<center>
<table width="100 % " id='table1' border="1" cellspacing="2"
cellpadding="2">
<tr class="tab-highlighted-2">
<td class="tab-highlighted-2" width="15">
<div align="left">city</div>
</td>
<td class="tab-highlighted-2" width="20">
<div align="left">companyName</div>
</td>
<td class="tab-highlighted-2" width="15">
<div align="left">province_eng</div>
</td>
<td class="tab-highlighted-2" width="15">
<div align="left">province_fr</div>
</td>
<td class="tab-highlighted-2" width="15">
<div align="left">postal_code</div>
</td>
</tr>
<c:forEach items="${beans}" var="view">
<tr>
<td><c:out value="${view.city}" /></td>
<td><c:out value="${view.companyName}" /></td>
<td><c:out value="${view.province_eng}" /></td>
<td><c:out value="${view.province_fr}" /></td>
<td><c:out value="${view.postal_code}" /></td>
</tr>
</c:forEach>
</table>
</center>
</body>
</html>
Web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>ImportConnect</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<listener>
<listener-class>com.importersconnect.listener.Listener</listener-class>
</listener>
<servlet>
<servlet-name>Test</servlet-name>
<servlet-class>com.importersconnect.sort.Test</servlet-class>
</servlet>
</web-app>

Related

Property Not Found! same naming convention

I'm here again asking a question, I've tried asking this a while ago (for today) but I've reconstructed my code. So, my problem is that when I click the button to show the details from the database, it show me an error that Property Not Found, I'm confused as to why this error pops out, Here is an example of the error, as you can see it can read the elements in the database when I sysout it, displaying it in the console pic of error
)
//empServlet
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
empServices empserv= new empServices();
ArrayList <empGetSet> empgs = new ArrayList<empGetSet>();
if (request.getParameter("process")!=null && request.getParameter("process").equals("showdis")) {
empgs.addAll(empserv.getAll());
request.setAttribute("empdet", empgs);
RequestDispatcher rd = request.getRequestDispatcher("showdet.jsp"); //forward to xxxpage after submit by button
rd.forward(request,response);
}
//empServices
package emppackage;
import java.util.ArrayList;
public class empServices {
empServlet empservlet = new empServlet();
empDAO empdao = new empDAO();
public ArrayList <empGetSet> getAll()
{
return empdao.getAllEmp();
}
//empDAO
public ArrayList<empGetSet> getAllEmp()
{
ArrayList<empGetSet> empdetails = new ArrayList<empGetSet>();
try {
Connection conn = getConnection();
String showsql = "SELECT *FROM csemp;";
PreparedStatement psread= conn.prepareStatement(showsql);
ResultSet rsread = psread.executeQuery();
while (rsread.next())
{
empGetSet readgetset = new empGetSet();
readgetset.setFname(rsread.getString(1));
//System.out.println(readgetset.getFname());
System.out.println(rsread.getString(1));
readgetset.setLname(rsread.getString(2));
readgetset.setNameRes(rsread.getString(3));
readgetset.setSerials(rsread.getString(4));
readgetset.setJrss(rsread.getString(5));
readgetset.setBand(rsread.getString(6));
readgetset.setAcct(rsread.getString(7));
readgetset.setPMPs(rsread.getString(8));
readgetset.setsJRSS(rsread.getString(9));
readgetset.setOpenSeatDesc(rsread.getString(10));
readgetset.setReqSkills(rsread.getString(11));
readgetset.setReqBand(rsread.getString(12));
readgetset.setDreject(rsread.getString(13));
readgetset.setsRreject(rsread.getString(14));
readgetset.setDetActPlan(rsread.getString(15));
readgetset.setDataComplete(rsread.getString(16));
readgetset.setStat(rsread.getString(17));
empdetails.add(readgetset);
}
psread.close();
conn.close();
}
catch (Exception e)
{
e.printStackTrace();
}
return empdetails;
}
This is my Getters and Setters with really the same naming convention
package emppackage;
public class empGetSet {
private String Fname;
private String Lname;
private String NameRes;
private String Serials;
private String Jrss;
private String Band;
private String Acct;
private String PMPs;
private String sJRSS;
private String OpenSeatDesc;
private String ReqSkills;
private String ReqBand;
private String Dreject;
private String Rreject;
private String DetActPlan;
private String DataComplete;
private String Stat;
public String getFname() {
return Fname;
}
public void setFname(String Fname) {
this.Fname=Fname;
}
public String getLname() {
return Lname;
}
public void setLname(String Lname) {
this.Lname=Lname;
}
public String getNameRes() {
return NameRes;
}
public void setNameRes(String NameRes) {
this.NameRes=NameRes;
}
public String getSerials() {
return Serials;
}
public void setSerials(String Serials) {
this.Serials=Serials;
}
public String getJrss() {
return Jrss;
}
public void setJrss(String Jrss) {
this.Jrss=Jrss;
}
public String getBand() {
return Band;
}
public void setBand(String Band) {
this.Band=Band;
}
public String getAcct() {
return Acct;
}
public void setAcct(String Acct) {
this.Acct=Acct;
}
public String getPMPs() {
return PMPs;
}
public void setPMPs(String PMPs) {
this.PMPs=PMPs;
}
public String getsJRSS() {
return sJRSS;
}
public void setsJRSS(String sJRSS) {
this.sJRSS=sJRSS;
}
public String getOpenSeatDesc() {
return OpenSeatDesc;
}
public void setOpenSeatDesc(String OpenSeatDesc) {
this.OpenSeatDesc=OpenSeatDesc;
}
public String getReqSkills() {
return ReqSkills;
}
public void setReqSkills(String ReqSkills) {
this.ReqSkills=ReqSkills;
}
public String getReqBand() {
return ReqBand;
}
public void setReqBand(String Acct) {
this.Acct=Acct;
}
public String getDreject() {
return Dreject;
}
public void setDreject(String Dreject) {
this.Dreject=Dreject;
}
public String getRreject() {
return Rreject;
}
public void setsRreject(String Rreject) {
this.Rreject=Rreject;
}
public String getDetActPlan() {
return DetActPlan;
}
public void setDetActPlan(String DetActPlan) {
this.DetActPlan=DetActPlan;
}
public String getDataComplete() {
return DataComplete;
}
public void setDataComplete(String DataComplete) {
this.DataComplete=DataComplete;
}
public String getStat() {
return Stat;
}
public void setStat(String Stat) {
this.Stat=Stat;
}
}
This is my .jsp
<%# taglib prefix="c" uri="http://java.sun.com/jstl/core_rt" %>
<!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>Show Details</title>
</head>
<body>
<div align="right"><button>Back</button></div>
<form action ="empServlet" method="get">
<table border =1 cellpadding="18">
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Name of Resource (LN ID Format)</th>
<th>Serial Number</th>
<th>JRSS</th>
<th>Band</th>
<th>Account (Proposed)</th>
<th>PMP Seat</th>
<th>Seat JRSS</th>
<th>Open Seat Description</th>
<th>Required Skills</th>
<th>Required Band low/high</th>
<th>Date of Rejection</th>
<th>Reason for Rejection</th>
<th>Detailed Action Plan</th>
<th>Target Date of Completion</th>
<th>Status(Ongoing/Closed)</th>
<th colspan=2>Do This</th>
</tr>
</thead>
<tbody>
<c:forEach items ="${empdet}" var="empdet" >
<tr>
<td><c:out value ="${empdet.Fname}" /></td>
<td><c:out value ="${empdet.Lname}" /></td>
<td><c:out value ="${empdet.NameRes}" /></td>
<td><c:out value ="${empdet.Serials}" /></td>
<td><c:out value ="${empdet.Jrss}" /></td>
<td><c:out value ="${empdet.Band}" /></td>
<td><c:out value ="${empdet.Acct}" /></td>
<td><c:out value ="${empdet.PMPs}" /></td>
<td><c:out value ="${empdet.sJRSS}" /></td>
<td><c:out value ="${empdet.OpenSeatDesc}" /></td>
<td><c:out value ="${empdet.ReqSkills}" /></td>
<td><c:out value ="${empdet.ReqBand}" /></td>
<td><c:out value ="${empdet.Dreject}" /></td>
<td><c:out value ="${empdet.Rreject}" /></td>
<td><c:out value ="${empdet.DetActPlan}" /></td>
<td><c:out value ="${empdet.DataComplete}" /></td>
<td><c:out value ="${empdet.Stat}" /></td>
<td>Update</td>
<td>Delete</td>
</c:forEach>
</tbody>
</table>
<br>
Show All
</form>
</body>
</html>

how to display error message on server side validation in spring mvc

//This is my loginController.java
import java.io.IOException;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
#Controller
public class LoginController
{
#RequestMapping(value="/login.htm", method = RequestMethod.POST)
public String login(#RequestParam(value="userid", required=true) String userid,
#RequestParam(value="password", required=true) String password,
#RequestParam(value="confirmpassword", required=true) String confirmpassword,
#RequestParam(value="role", required=true) String role,
Map<String, Object> model)
{
if(userid.matches("^[a-zA-Z0-9]{5,24}$") && password.matches("^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[##$%^&+=])(?=\\S+$).{5,15}$")
&& confirmpassword.matches("^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[##$%^&+=])(?=\\S+$).{6,20}$")
&& (role.equals(new String("OPS(Operational)"))||role.equals(new String("Helpdesk"))))
{
model.put("userid", userid);
model.put("password", password);
model.put("confirmpassword", confirmpassword);
model.put("role", role);
System.out.println("successful!");
return "page2";
}
else
{
return "login";
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
{
String userid = request.getParameter("userid");
String password = request.getParameter("password");
String confirmpassword = request.getParameter("confirmpassword");
String role = request.getParameter("role");
try
{
request.getRequestDispatcher("/login.jsp").forward(request, response);
}
catch (ServletException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
String userid = request.getParameter("userid");
String password = request.getParameter("password");
String confirmpassword = request.getParameter("confirmpassword");
String role = request.getParameter("role");
request.getRequestDispatcher("/WEB-INF/login.jsp").forward(request, response);
}
}
//This is my login.jsp file
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%# include file="include.jsp" %>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<div align="center" id='formlogin' class="container">
<form method="post" id="loginForm" name="loginForm" action="login.htm">
<table class="tableprop" border="0" width="90%" cellspacing="5" cellpadding="5">
<h3> Add a new user </h3>
<tr>
<td align="center">User ID:</td>
<td><input tabindex="5" size="20" type="text" name="userid" id="userid" value="<%=request.getParameter("userid")!=null?request.getParameter("userid"):""%>"/></td>
</tr>
<tr>
<td align="center">Password:</td>
<td><input tabindex="5" size="20" type="password" name="password" id="password" value="<%=request.getParameter("password")!=null?request.getParameter("password"):""%>"/></td>
</tr>
<tr>
<td align="center">Confirm Password:</td>
<td><input tabindex="5" size="20" type="password" name="confirmpassword" id="confirmpassword" value="<%=request.getParameter("confirmpassword")!=null?request.getParameter("confirmpassword"):""%>"/></td>
</tr>
<tr>
<td align="center">Role:</td>
<td><select name="role" id="role" title="Please select role" tabindex="5" value="<%=request.getParameter("role")!=null?request.getParameter("role"):""%>"/>
<option value="">Select a specific role</option>
<option value="OPS(Operational)">OPS(Operational)</option>
<option value="Helpdesk">Helpdesk</option>
</select></td>
</tr>
<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}" />
<tr>
<td align="center" colspan="4"><input tabindex="7" type="submit" value="Submit" id="submit" class="submit"/></td>
</tr>
<!-- <div id="dialog" title="Dialog Title">I'm in a dialog</div> -->
</table>
</form>
</div>
<script>
// just for the demos, avoids form submit
jQuery.validator.setDefaults({
debug: true,
success: "valid"
});
</script>
</body>
</html>
I have added here 2 files.
first one is loginController.java
and other one is login.jsp
i have done client side validation in jquery.
now i want to display error message on server side validation in loginController.java file which has code for server side validation. and also i want it to be check once whether loginController.java is written correct or not.
You can use Spring Validator interface to build your own custom validator and use spring form tags.
User.java
package com.expertwebindia.beans;
public class User {
private String name;
private String email;
private String address;
private String country;
private String state;
private String city;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
UserValidator.java
package com.expertwebindia.validators;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
import com.expertwebindia.beans.User;
#Component
public class UserValidator implements Validator
{
public boolean supports(Class clazz) {
return User.class.equals(clazz);
}
public void validate(java.lang.Object arg0, Errors arg1) {
ValidationUtils.rejectIfEmptyOrWhitespace(arg1, "name", "name.required", "Name is required.");
ValidationUtils.rejectIfEmptyOrWhitespace(arg1, "email", "Name.required", "Email is required.");
ValidationUtils.rejectIfEmptyOrWhitespace(arg1, "address", "name.required", "Address is required.");
ValidationUtils.rejectIfEmptyOrWhitespace(arg1, "country", "country.required", "Country is required.");
ValidationUtils.rejectIfEmptyOrWhitespace(arg1, "state", "state.required", "State is required.");
ValidationUtils.rejectIfEmptyOrWhitespace(arg1, "city", "city.required", "City is required.");
}
}
In controller you need to the following code to validate your bean.
#RequestMapping(value = "/login", method = RequestMethod.POST)
public String doLogin(#ModelAttribute("userForm") User userForm,
BindingResult result, Map<String, Object> model) {
validator.validate(userForm, result);
System.out.println("Email:"+userForm.getEmail());
if (result.hasErrors()) {
return "register";
}else{
return "success";
}
}
Please find more details about this in link below.
http://www.expertwebindia.com/spring-3-mvc-custom-validator-example/

How can i display all column of a database table using servlet and jsp

I have a database table users containing columns id(int),name(string),department(string),password(string).I am storing table contents in an arrayList object in a servlet (display.java) and then forwarding it to a jsp page(home1.jsp). But i am unable to display all tables using that jsp page.Id contents is not showing and the columns of table has been shifted 1 unit right. i.e not under correct header.
#WebServlet("/Display3")
public class Display3 extends HttpServlet {
private static final long serialVersionUID = 1L;
public Display3() {
super();
// TODO Auto-generated constructor stub
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
Connection conn = null;
Statement st;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection
("jdbc:mysql://localhost:3306/test?user=root&password=Tpg#1234");
ArrayList al=null;
ArrayList userList =new ArrayList();
String query = "select id,name,department,password from users";
st = conn.createStatement();
ResultSet rs = st.executeQuery(query);
while(rs.next())
{
al = new ArrayList();
al.add(rs.getInt(1));
al.add(rs.getString(2));
al.add(rs.getString(3));
al.add(rs.getString(4));
userList.add(al);
}
request.setAttribute("userList",userList);
RequestDispatcher dispatcher = getServletContext()
.getRequestDispatcher("/home1.jsp");
dispatcher.forward(request,response);
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
the jsp code is here
<%# page language="java" contentType="text/html; charset=ISO-8859-1"pageEncoding="ISO-8859-1"%>
<%# 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>Insert title here</title>
<script language ="javascript">
function editData(id){
}
function deleteData(id){
}
</script>
</head>
<body>
<br>
<table align="center">
</table>
<br>
<table border='1' width='300' cellpadding='1' cellspacing='0'>
<tr>
<td colspan=6 align="center"></td>
</tr>
<tr>
<td>Id</td>
<td>Name</td><td>Department</td>
<td>Edit</td>
<td>Delete</td>
</tr>
<%
List Li = new ArrayList();
Iterator lr;
if(request.getAttribute("userList")!=null && request.getAttribute("userList")!="")
{
List userList = (ArrayList)request.getAttribute("userList");
Iterator itr = userList.iterator();
while(itr.hasNext())
{
Li = (ArrayList)itr.next();
lr = Li.iterator();
Integer id = (Integer)lr.next();
%>
<tr>
<%
while(lr.hasNext())
{
%>
<td><%=lr.next()%></td>
<%
}
%>
<td><input type="button" name="edit" value="edit" onclick="editData(<%=id%>);" ></td>
<td><input type="button" name="delete" value="Delete" onclick="deleteData(<%=id%>);"></td>
</tr>
<%
}
}
%>
}
</table>
</body>
</html>
When you cast Integer id = (Integer)lr.next(); you are shifting the position of the iterator by one position.
The method Iterator#next() automatically moves your iterator by one position. When in your while you call
<td><%=lr.next()%></td>
you start from 2nd position, leaving out your id.
I strongly suggest you to read about generics for your array list, object-relational mapping and above all foreach loop.
The most important is ORM, you should create a POJO java class to contain a row of your table:
public class User {
int id;
String name;
String departament;
String password;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDepartament() {
return departament;
}
public void setDepartament(String departament) {
this.departament = departament;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
Then you can iterate your result set and add a new user for each row:
//...
List<User> users = new ArrayList<User>();
//...
while(rs.next())
{
user = new User();
user.setId(rs.getInt(1));
user.setName(rs.getString(2));
user.setDepartament(rs.getString(3));
user.setPassword(rs.getString(4));
users.add(user);
}
now you can iterate over the list using
for(User user: users){
//Whatever...
}
In iterator Once you have called the .next() the pointer is moved to next element. Since you have called the id using Integer id = (Integer)lr.next();. The pointer will move to the next value in the list. So if you are trying to print the id in <td><%=lr.next()%></td> it wont. Instead it will print the name.
instead you can change your jsp with the below one
Integer id = (Integer)lr.next();
%>
<tr>
<td><%=id%></td>
<%
while(lr.hasNext())
{
%>
<td><%=lr.next()%></td>
<%
}

insert update delete in Struts 2 but showing NullPointerException

Here I come up with problem with Operation like update,delete and view so now insert is working but other operation like update, delete, view showing error like. Could some one can guide to go right direction? This what I have tried up to now
Error:
HTTP Status 500 - java.lang.NullPointerException
type Exception report
message java.lang.NullPointerException
description The server encountered an internal error that prevented it from fulfilling this request.
exception
javax.servlet.ServletException: java.lang.NullPointerException
org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:515)
org.apache.struts2.dispatcher.FilterDispatcher.doFilter(FilterDispatcher.java:419)
root cause
java.lang.NullPointerException
Action.Testiue.view(Testiue.java:115)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:606)
com.opensymphony.xwork2.DefaultActionInvocation.invokeAction(DefaultActionInvocation.java:404)
com.opensymphony.xwork2.DefaultActionInvocation.invokeActionOnly(DefaultActionInvocation.java:267)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:229)
com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor.doIntercept(DefaultWorkflowInterceptor.java:221)
com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:86)
com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:224)
com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:223)
com.opensymphony.xwork2.util.profiling.UtilTimerStack.profile(UtilTimerStack.java:455)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:221)
com.opensymphony.xwork2.validator.ValidationInterceptor.doIntercept(ValidationInterceptor.java:150)
org.apache.struts2.interceptor.validation.AnnotationValidationInterceptor.doIntercept(AnnotationValidationInterceptor.java:48)
struts.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<include file="struts-default.xml" />
<package name="a" extends="struts-default">
<action name="adduser" class="Action.Testiue" method="add">
<result name="success">/insert.jsp</result>
<result name="success">/ssuccess.jsp</result>
</action>
<action name="viewuser" class="Action.Testiue" method="view">
<result name="success">/view.jsp</result>
<result name="error">/error.jsp</result>
</action>
<action name="updateuser" class="Action.Testiue" method="update">
<result name="success">/edit.jsp</result>
<result name="error">/error.jsp</result>
</action>
<action name="deleteuser" class="Action.Testiue" method="delete">
<result name="success">/dsuccess.jsp</result>
<result name="error">/error.jsp</result>
</action>
</package>
</struts>
Web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
TestIUE.java
package Action;
import com.opensymphony.xwork2.ActionSupport;
import dao.UserDao;
import dbBean.UseBean;
public class Testiue
{
private String Name;
private String Password;
private String EmailID;
private String Phoneo;
private int ID;
public String getName()
{
return Name;
}
public void setName(String name)
{
Name = name;
}
public String getPassword()
{
return Password;
}
public void setPassword(String password)
{
Password = password;
}
public String getEmailID()
{
return EmailID;
}
public void setEmailID(String emailID)
{
EmailID = emailID;
}
public String getPhoneo()
{
return Phoneo;
}
public void setPhoneo(String phoneo)
{
Phoneo = phoneo;
}
public int getID()
{
return ID;
}
public void setID(int i)
{
ID = i;
}
#Override
public String toString()
{
return "UseBean [id=" + ID + ", Name=" + Name+ ", Password=" + Password + ", EmailID=" + EmailID + ", Phoneo="+ Phoneo + "]";
}
private UserDao dao;
private UseBean bean;
public String add()
{
dao=new UserDao();
bean=new UseBean();
System.out.println(getName()+""+getPassword()+""+getPhoneo()+""+getEmailID());
bean.setID(ID);
bean.setName(Name);
bean.setPassword(Password);
bean.setPhoneo(Phoneo);
bean.setEmailID(EmailID);
dao.addUser(bean);
return ActionSupport.SUCCESS;
}
public String update()
{
dao=new UserDao();
bean=new UseBean();
//System.out.println(getName()+""+getPassword()+""+getPhoneo()+""+getEmailID());
bean.setID(ID);
bean.setName(Name);
bean.setPassword(Password);
bean.setPhoneo(Phoneo);
bean.setEmailID(EmailID);
dao.updateUser(bean);
return ActionSupport.SUCCESS;
}
public String delete()
{
int userId =0;
dao.deleteUser(userId);
return ActionSupport.SUCCESS;
}
public String edit()
{
int userId =0;
bean = dao.getUserById(userId);
return ActionSupport.SUCCESS;
}
public String view()
{
dao.getAllUsers();
return ActionSupport.SUCCESS;
}
}
Index.jsp
<META HTTP-EQUIV="Refresh" CONTENT="0;URL=viewuser.action">
view.jsp;
<%# taglib prefix="s" uri="/struts-tags"%>
<%#page import="java.util.*,dbBean.*,Dbconnect.*,java.util.*"%>
Insert
<table border=1>
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>password</th>
<th>phoneno</th>
<th>emailid</th>
<th colspan=2>Action</th>
</tr>
</thead>
<jsp:useBean id="users" class="java.util.ArrayList" scope="request" />
<% for(int i = 0; i < users.size(); i+=1)
{
UseBean user = (UseBean)users.get(i);
%>
<tbody>
<tr>
<td><%= user.getID() %></td>
<td><%= user.getName() %></td>
<td><%= user.getPassword() %></td>
<td><%= user.getEmailID() %></td>
<td><%= user.getPhoneo() %></td>
<td>Update</td>
<td>Delete</td>
</tr>
<%
}
%>
</tbody>
</table>
edit.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>Insert title here</title>
</head>
<body>
<form action="updateuser">
id:<input type="text" name="ID" ><br/>
Name:<input type="text" name="Name" ><br/>
Password:<input type="text" name="password" ><br/>
phoneno:<input type="text" name="Phoneo" ><br/>
Emailid:<input type="text" name="Emailid" > <br/>
<input type="submit" value="Submit" />
</form>
</body>
</html>
UserDao.java
package dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import dbBean.UseBean;
import Dbconnect.*;
public class UserDao
{
private Connection conn;
public UserDao()
{
conn=Dbconnect.getConnection();
}
public void addUser(UseBean bean)
{
try
{
String sql="insert into senthil (name,pass,phoneno,emailid) values(?,?,?,?)";
PreparedStatement ps=conn.prepareStatement(sql);
ps.setString(1,bean.getName());
ps.setString(2,bean.getPassword());
ps.setString(3,bean.getPhoneo());
ps.setString(4,bean.getEmailID());
ps.executeUpdate();
}
catch (Exception e)
{
// TODO: handle exception
}
}
public void deleteUser(int userId)
{
try
{
PreparedStatement ps = conn.prepareStatement("delete from senthil where id=?");
// Parameters start with 1
ps.setInt(1, userId);
ps.executeUpdate();
} catch (SQLException e)
{
e.printStackTrace();
}
}
public void updateUser(UseBean bean)
{
try
{
PreparedStatement preparedStatement = conn.prepareStatement("update senthil set name=?, pass=?, phoneno=?, emailid=?"+ "where id=?");
// Parameters start with 1
preparedStatement.setString(1, bean.getName());
preparedStatement.setString(2, bean.getPassword());
preparedStatement.setString(3, bean.getPhoneo());
preparedStatement.setString(4, bean.getEmailID());
preparedStatement.setInt(5, bean.getID());
preparedStatement.executeUpdate();
}
catch (SQLException e)
{
e.printStackTrace();
}
}
public List<UseBean> getAllUsers()
{
List<UseBean> users = new ArrayList<UseBean>();
try
{
Statement statement = conn.createStatement();
ResultSet rs = statement.executeQuery("select * from senthil");
while (rs.next())
{
UseBean user = new UseBean();
user.setID(rs.getInt("id"));
user.setName(rs.getString("name"));
user.setPassword(rs.getString("pass"));
user.setPhoneo(rs.getString("phoneno"));
user.setEmailID(rs.getString("emailid"));
users.add(user);
}
}
catch (SQLException e)
{
e.printStackTrace();
}
return users;
}
public UseBean getUserById(int userId)
{
UseBean user = new UseBean();
try
{
PreparedStatement preparedStatement = conn.prepareStatement("select * from senthil where id=?");
preparedStatement.setInt(1, userId);
ResultSet rs = preparedStatement.executeQuery();
if (rs.next())
{
user.setID(rs.getInt("id"));
user.setName(rs.getString("name"));
user.setPassword(rs.getString("pass"));
user.setPhoneo(rs.getString("phoneno"));
user.setEmailID(rs.getString("emailid"));
}
} catch (SQLException e)
{
e.printStackTrace();
}
return user;
}
}
In the JSP the users should be available to the request scope.
public String view() {
UserDao userDao = new UserDao();
List<UseBean> users = userDao.getAllUsers();
ServletActionContext.getRequest().setAttribute("users", users);
return Action.SUCCESS;
}
public String update() {
UserDao dao = new UserDao();
UseBean bean=new UseBean();
HttpServletRequest request ServletActionContext.getRequest();
bean.setID(request.getParameter("ID");
bean.setName(request.getParameter("Name");
bean.setPassword(request.getParameter("Password");
bean.setPhoneo(request.getParameter("Phoneo");
bean.setEmailID(request.getParameter("EmailID");
//System.out.println(getName()+""+getPassword()+""+getPhoneo()+""+getEmailID());
dao.updateUser(bean);
return Action.SUCCESS;
}
public String delete() {
HttpServletRequest request ServletActionContext.getRequest();
int userId = request.getParameter("ID");
dao.deleteUser(userId);
return Action.SUCCESS;
}
for delete action
<s:param name='ID'><%=user.getID()%></s:param></s:url>">Delete
Inside view method you haven't initialized the dao object(i.e reference is null), add the following code :
In TestIUE.java add one more member variable :
List<UseBean> users = new ArrayList<UseBean>();
Also add Accessor method :
public List<UseBean> getUsers()
{
return users;
}
Now modify your view method as follows :
public String view()
{
dao = new UseDao();
users = dao.getAllUsers();
return ActionSupport.SUCCESS;
}

Can't display the data from SQL in the correct order, HTML JSP

I'm currently working on a group project where we're supposed to handle the relation between Building and Room. The relation is OnetoMany, and we're currently able to show the relevant data from sql, but we're not able to display it in a good looking spreadsheet or table as intended. We would like to have the buildings and room sorted into a table, where each room shows connection to related building. How do we put our the HTML code in our (ShowRooms.jsp) jsp to get all rooms for building of choice by user, and then display all rooms by that building in a good-looking-table? In this state we get the data from our sql-database but just in a straight line instead of by a table which connects each room to the relevant building. Thanks in advance!
This is our code: BUILDING:
#Entity
#Table(name = "Building")
public class Building {
private String bname;
private List<Room> rooms; // Building can have many Rooms
#Id
#Column(name = "Bname")
public String getBname() {
return bname;
}
public void setBname(String bname) {
this.bname = bname;
}
#OneToMany(mappedBy = "building", fetch = FetchType.EAGER)
public List<Room> getRooms() {
return rooms;
}
public void setRooms(List<Room> rooms) {
this.rooms = rooms;
}
}
ROOM:
#NamedQueries({
#NamedQuery(name="Room.findByBname",
query="SELECT r FROM Room r WHERE r.bname LIKE :bname"),
})
#Entity
#Table(name = "Room")
public class Room implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private RoomId id;
private String bname;
private Building building;
public String getBname() {
return bname;
}
public void setBname(String bname) {
this.bname = bname;
}
#Id
public RoomId getId() {
return id;
}
public void setId(RoomId id) {
this.id = id;
}
#ManyToOne
#JoinColumn(name = "Bname", insertable = false, updatable = false)
public Building getBuilding() {
return this.building;
}
public void setBuilding(Building building) {
this.building = building;
}
}
ROOMID:
#Embeddable
public class RoomId implements Serializable {
private String bname;
private String rcode;
public RoomId() {
}
public RoomId(String bname, String rcode) {
this.bname = bname;
this.rcode = rcode;
}
#Column(name = "Bname", nullable = false)
public String getbname() {
return bname;
}
public void setbname(String bname) {
this.bname = bname;
}
#Column(name = "Rcode", nullable = false)
public String getrcode() {
return rcode;
}
public void setrcode(String rcode) {
this.rcode = rcode;
}
public boolean equals(Object other) {
if ((this == other)) {
return true;
}
if ((other == null)) {
return false;
}
if (!(other instanceof RoomId)) {
return false;
}
RoomId castOther = (RoomId) other;
return ((this.getbname() == castOther.getbname()) || (this.getbname() != null
&& castOther.getbname() != null &&
this.getbname().equals(castOther.getbname())))
&&
((this.getrcode() == castOther.getrcode()) || (this.getrcode() != null && castOther.getrcode() != null &&
this.getrcode().equals(castOther.getrcode())));
}
public int hashCode() {
return super.hashCode();
}
}
BUILDINGEAO:
#Stateless
public class BuildingEAOImpl implements BuildingEAOImplLocal {
#PersistenceContext(unitName = "LabEJBSql")
private EntityManager em;
public BuildingEAOImpl() {
// TODO Auto-generated constructor stub
}
public Building findByBname(String bname) {
return em.find(Building.class, bname);
}
}
FACADE:
#Stateless
public class Facade implements FacadeRemote, FacadeLocal {
#EJB
BuildingEAOImplLocal BuildingEAO;
#EJB
RoomEAOImplLocal RoomEAO;
public Facade() {
// TODO Auto-generated constructor stub
}
public List<Room> findRoomsByBname(String bname) {
return RoomEAO.findByBname(bname);
}
}
SERVLET:
#WebServlet("/TestClientServlet")
public class TestClientServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
#EJB
private FacadeLocal facade;
/**
* #see HttpServlet#HttpServlet()
*/
public TestClientServlet() {
super();
// TODO Auto-generated constructor stub
}
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
out.println("TestClientServlet-doGet");
out.close();
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String url = null;
// Get hidden field
String operation = request.getParameter("operation");
if (operation.equals("showrooms")) {
String bname = request.getParameter("txtBname");
List<Room> r = facade.findRoomsByBname(bname);
request.setAttribute("rooms", r);
url = "/ShowRooms.jsp";
} else if (operation.equals("searchbuilding")) {
System.out.println("TestClientServlet-searchbuilding");
url = "/SearchBuilding.jsp";
} else {
url = "/SearchBuilding.jsp";
}
System.out.println(url);
RequestDispatcher dispatcher = getServletContext()
.getRequestDispatcher(url);
dispatcher.forward(request, response);
}
*/
}
SEARCHBUILDING.JSP:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-
8859-1">
<title>Search Building</title>
</head>
<body>
<form action="/BuildRoomClientProject/TestClientServlet" method="post">
<table cellspacing="0" cellpadding="0" border="0" align="left">
<tr>
<td><h2>Search Building:</h2></td>
</tr>
<tr>
<td>
<input type= "text" name= "txtBname" size ="25" maxlength="25">
<input type="submit" name="submit" value="Search" />
</td>
<td></td>
</tr>
</table>
<input name="operation" value="showrooms" type="hidden">
</form>
</body>
</html>
SHOWROOMS.JSP:
<%# page contentType="text/html;charset=windows-1252"%>
<%# page import = "org.ics.ejb.Building" %>
<%# page import = "org.ics.ejb.Room" %>
<%# page import = "org.ics.ejb.RoomId" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>
Show Rooms
</title>
</head>
<body>
<h2>
Rooms:
</h2>
<%List<Room> r = (List<Room>)request.getAttribute("rooms"); %>
<% for (Room r1 : r){
out.println(r1.getBname() + " " + r1.getId().getrcode());
}%>
<p>
</p>
<form action="/BuildRoomClientProject/TestClientServlet" method="post">
<input type="submit" name="submit" value="Tillbaka">
<input name="operation" value="searchbuilding" type="hidden">
</form>
</body>
</html>
For your jpql, youldn't you use a GROUPBY combined with a GROUPBY directive?
Then for each table entry that is one you get render the bname (= BuildingName ??) as first row.
Then render your retrieved list as a table, a short example could be somehow this:
<table>
<c:forEach var="o" items="${objects}">
<tr>
<td>${o.bname}</td>
<td>${o.id}</td>
<td>${o.name}</td>
<td>${o.descriptio}</td>
</tr>
</c:forEach>
</table>
In fact, I just found this: displaying a list of entities in jsp file by using java searching for "jsp, listview, table"

Categories