Arraylist + database + servlet + DAO - java

Hello i'm new to hava and i'm having a problem viewing my records from an arraylist in JSP page,
whenever i load the page i get:
[content.animalBean#1e8614a, content.animalBean#14b52aa, content.animalBean#2026f3, content.animalBean#dd20b6, content.animalBean#18eb00c] 1 which is not the database records
here is my code:
selectAnimalServlet:
package content;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class selectAnimalServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, java.io.IOException {
try
{
List<animalBean> beans = DAO.selectListAnimal();
request.setAttribute("beans", beans);
request.getRequestDispatcher("checkAnimal.jsp").forward(request, response);
}
catch (Throwable theException)
{
System.out.println(theException);
}
}
}
AnimalBean:
package content;
public class animalBean {
private String animalName;
private String animalDob;
private String animalGender;
private String animalSource;
private String animalBreed;
private String animalRemark;
public String getAnimalName() {return animalName;}
public String getAnimalDob() {return animalDob;}
public String getAnimalGender() {return animalGender;}
public String getAnimalSource() {return animalSource;}
public String getAnimalBreed() {return animalBreed;}
public String getAnimalRemark() {return animalRemark;}
public void setAnimalName(String animalName) {this.animalName = animalName;}
public void setAnimalDob(String animalDob) {this.animalDob = animalDob;}
public void setAnimalGender(String animalGender) {this.animalGender = animalGender;}
public void setAnimalSource(String animalSource) {this.animalSource = animalSource;}
public void setAnimalBreed(String animalBreed) {this.animalBreed = animalBreed;}
public void setAnimalRemark(String animalRemark) {this.animalRemark = animalRemark;}
}
DAO class:
package content;
import java.sql.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class DAO
{
static Connection currentCon = null;
static ResultSet rs = null;
public static loginAuth login(loginAuth bean) {
//preparing some objects for connection
Statement stmt = null;
String username = bean.getUsername();
String password = bean.getPassword();
String searchQuery =
"select * from user where username='"
+ username
+ "' AND password='"
+ password
+ "'";
// "System.out.println" prints in the console; Normally used to trace the process
System.out.println("Your user name is " + username);
System.out.println("Your password is " + password);
System.out.println("Query: "+searchQuery);
try
{
//connect to DB
currentCon = dbConnection.getConnection();
stmt=currentCon.createStatement();
rs = stmt.executeQuery(searchQuery);
boolean more = rs.next();
// if user does not exist set the isValid variable to false
if (!more)
{
System.out.println("Sorry, you are not a registered user! Please sign up first");
bean.setValid(false);
}
//if user exists set the isValid variable to true
else if (more)
{
String firstName = rs.getString("FirstName");
String lastName = rs.getString("LastName");
System.out.println("Welcome " + firstName);
bean.setfname(firstName);
bean.setlname(lastName);
bean.setValid(true);
}
}
catch (Exception ex)
{
System.out.println("Log In failed: An Exception has occurred! " + ex);
}
//some exception handling
finally
{
if (rs != null) {
try {
rs.close();
} catch (Exception e) {}
rs = null;
}
if (stmt != null) {
try {
stmt.close();
} catch (Exception e) {}
stmt = null;
}
if (currentCon != null) {
try {
currentCon.close();
} catch (Exception e) {
}
currentCon = null;
}
}
return bean;
}
public static List<animalBean> selectListAnimal() throws SQLException {
Statement stmt = null;
List<animalBean> beans = new ArrayList<animalBean>();
try {
currentCon = dbConnection.getConnection();
String animalSearchQuery = "select a.aname ,a.dob, a.gender , a.source, s.sname, a.remark from animal as a , specie as s where a.specie_id = s.specie_id and a.available ='y'";
stmt=currentCon.createStatement();
rs = stmt.executeQuery(animalSearchQuery);
while (rs.next()) {
animalBean bean = new animalBean();
bean.setAnimalName(rs.getString("aname"));
bean.setAnimalDob(rs.getString("dob"));
bean.setAnimalGender(rs.getString("gender"));
bean.setAnimalSource(rs.getString("source"));
bean.setAnimalBreed(rs.getString("sname"));
bean.setAnimalRemark(rs.getString("remark"));
beans.add(bean);
}
} finally {
if (rs != null) try { rs.close(); } catch (SQLException logOrIgnore) {}
if (stmt != null) try { stmt.close(); } catch (SQLException logOrIgnore) {}
if (currentCon != null) try { currentCon.close(); } catch (SQLException logOrIgnore) {}
}
return beans;
}
}
and last the JSP page animalCheck.jsp:
<%# page language="java"
contentType="text/html; charset=windows-1256"
pageEncoding="windows-1256"
import="content.animalBean"
import="content.DAO"
%>
<!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=windows-1256">
<title>Animal list</title>
<link rel="stylesheet"
href="./css/styles.css"
type="text/css"/>
</head>
<body>
<table class="title">
<tr><th>Zoo keeper</th></tr>
</table>
<h1>Animal 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">Name</div>
</td>
<td class="tab-highlighted-2" width="20">
<div align="left">Age</div>
</td>
<td class="tab-highlighted-2" width="15">
<div align="left">Gender</div>
</td>
<td class="tab-highlighted-2" width="15">
<div align="left">Status</div>
</td>
<td class="tab-highlighted-2" width="15">
<div align="left">Breed</div>
</td>
<td class="tab-highlighted-2" width="15">
<div align="left">Remarks</div>
</td>
</tr>
<c:forEach items="${beans}" var="view">
<tr>
<td>${view.animalName} </td>
<td>${view.animalDob}</td>
<td>${view.animalGender}</td>
<td>${view.animalSource}</td>
<td>${view.animalBreed}</td>
<td>${view.animalRemark}</td>
</tr>
</c:forEach>
</table>
</center>
</body></html>
I've been struggeling on this since 2 days and i checked many websites and followed many guides but still nothing worked for me :(
I appreciate any kind of help

You forgot to declare the JSTL core taglib. Add the following to top of your JSP:
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
See also:
Our JSTL wiki page - contains information about how to install and use JSTL
Show JDBC ResultSet in HTML in JSP page using MVC and DAO pattern
How to avoid Java code in JSP files?
Unrelated to the concrete problem, there are several other problems in your code:
You should never declare DB resources as static. This is not threadsafe and is prone to resource leaking. Declare them inside the very same method block as you're executing the SQL query.
You have a SQL injection hole in login() method. Use PreparedStatement.
You don't need to use #page import in your JSP if you aren't using any scriptlets.
Classnames are supposed to start with uppercase.

Can you try something like this on top of your page
<% List<animalBean> animals = (animalBean)request.getAttribute("beans"); %>
and then change your c:forEach tag to point it to animals instead of beans?

Related

How to solve after push the submit button it shows 404 error with controller message [duplicate]

This question already has answers here:
Servlet returns "HTTP Status 404 The requested resource (/servlet) is not available"
(19 answers)
Closed 2 years ago.
im currently doing my final year project about lost and found system using java and oracle database (MVC).
my problem is after I submit the form the page will show this the message says it redirect to the FoundRegisterController
it supposedly register the found item. but it did not. how can I solve this problem? Below are the codes for the jsp, controller and DAO
this is registerFoundItem.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!doctype html>
<html class="no-js" lang="en">
<head>
<jsp:include page="css.jsp"></jsp:include>
</head>
<body>
<jsp:include page="header.jsp" />
<!-- tabs & register form Start -->
<div class="basic-form-area mg-b-15">
<div class="container-fluid">
<div class="row">
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<div class="sparkline8-list mt-b-30">
<div class="sparkline8-graph">
<div class="basic-login-form-ad">
<div class="row">
<div class="col-lg12 col-md-12 col-sm-12 col-xs-12">
<h2>
<center>Register New Found Item</center>
</h2>
<br> <br>
</div>
</div>
<%
String userEmail = (String) session.getAttribute("currentSessionUser");
%>
<%
String userNoPhone = (String) session.getAttribute("currentSessionUserNoPhone");
%>
<%
String userName = (String) session.getAttribute("currentSessionUserName");
%>
<div class="row">
<form action="FoundRegisterController" method="post">
<div class="col-lg-4 col-md-4 col-sm-4 col-xs-12">
<div class="basic-login-inner">
<h4>Reporter Details:</h4>
<div class="form-group-inner">
<label>Post by:</label> <input type="text"
class="form-control" name="UserName"
value="<c:out value="<%=userName%>" />" disabled />
</div>
<div class="form-group-inner">
<label>Contact Number: </label><input type="text"
class="form-control" name="UserNoPhone"
value="<c:out value="<%=userNoPhone%>" />" disabled />
</div>
<div class="form-group-inner">
<label>Email: </label><input type="text"
class="form-control" name="UserNoPhone"
value="<c:out value="<%=userEmail%>" />" disabled />
</div>
<br>
</div>
</div>
<div class="col-lg-8 col-md-8 col-sm-8 col-xs-12">
<h4>Found Item Details :</h4></div>
<div class="col-lg-4 col-md-4 col-sm-4 col-xs-12">
<label>Date:</label> <input class="form-control"
name="FItemDate" type="date" required />
</div>
<div class="col-lg-4 col-md-4 col-sm-4 col-xs-12">
<label>Time:</label> <input class="form-control"
name="FItemTime" type="time"
required />
</div>
<div class="col-lg-8 col-md-8 col-sm-8 col-xs-12">
<div class="form-group-inner">
<label><br>Found Item Name:</label> <input type="text"
class="form-control" name="FItemName"
placeholder="eg: iPhone 8 Plus | ASUS | GoPro 5 Black"
title="Please enter the valid name. Do not use shortform"
required />
</div>
<div class="form-group-inner">
<label>Found Item Category:</label>
<div class="form-select-list">
<select class="form-control custom-select-value"
name="account" name="FItemCategory">
<option disabled selected value>-- Select
Category --</option>
<option value="FoundItem">Mobile Phone</option>
<option value="FoundItem">Laptop/Notebook</option>
<option value="FoundItem">Keys</option>
<option value="FoundItem">Cards</option>
<option value="FoundItem">UiTM Matrics Card</option>
<option value="FoundItem">Other..</option>
</select>
</div>
</div>
<div class="form-group-inner">
<label>Location:</label> <input class="form-control"
name="FItemLocation"
placeholder="eg: Blok Kuliah 17 | JMK 8 | Cafe Kuliah"
title="Please enter the valid name. Do not use shortform"
required />
</div>
<div class="form-group-inner">
<label>Description: </label>
<div class="form-group edit-ta-resize res-mg-t-15">
<textarea name="description" name="FItemDescription" placeholder="eg: Barang dijumpai di bawah meja/atas lantai/depan pintu/atas meja pensyarah/etc.. anggaran waktu dijumpai 2ptg-6ptg"></textarea>
</div>
</div>
<div class="login-btn-inner">
<div class="inline-remember-me">
<button
class="btn btn-sm btn-primary pull-right login-submit-cs"
type="submit" name="action">
<b>Register</b>
</button>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<br>
</div>
<!-- tabs & Register form End-->
<!-- JS -->
<jsp:include page="js.jsp"></jsp:include>
</body>
</html>
this is my FoundRegisterController.java
package lofo.controller;
import java.io.IOException;
import java.io.PrintWriter;
import java.security.NoSuchAlgorithmException;
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 lofo.dao.foundDAO;
import lofo.model.FoundItemBean;
/**
* Servlet implementation class RegisterController
*/
#WebServlet("/FoundRegisterController")
public class FoundRegisterController extends HttpServlet {
private static final long serialVersionUID = 1L;
private String VIEW ="/lofo/viewFound.jsp";
private foundDAO dao;
String forward="";
String action="";
/**
* #see HttpServlet#HttpServlet()
*/
public FoundRegisterController() {
super();
// TODO Auto-generated constructor stub
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String action = request.getParameter("action");
if(action.equalsIgnoreCase("viewFound")) {
forward = VIEW;
String UserEmail = request.getParameter("UserEmail");
FoundItemBean found = dao.getUserByEmail(UserEmail);
request.setAttribute("found", found);
}
RequestDispatcher view = request.getRequestDispatcher(forward);
view.forward(request, response);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
action = request.getParameter("action");
try {
String FItemID = request.getParameter("FItemID");
String UserEmail = request.getParameter("UserEmail");
String FItemName = request.getParameter("FItemName");
String FItemCategory = request.getParameter("FItemCategory");
String FItemDate = request.getParameter("FItemDate");
String FItemTime = request.getParameter("FItemTime");
String FItemLocation = request.getParameter("FItemLocation");
String FItemDescription = request.getParameter("FItemDescription");
FoundItemBean found = new FoundItemBean();
found.setFItemID(FItemID);
found.setUserEmail(UserEmail);
found.setFItemName(FItemName);
found.setFItemCategory(FItemCategory);
found.setFItemDate(FItemDate);
found.setFItemTime(FItemTime);
found.setFItemLocation(FItemLocation);
found.setFItemDescription(FItemDescription);
dao = new foundDAO();
found = foundDAO.getUser(found);
try {
dao.FoundAdd(found);
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<script>");
pw.println("alert('The item post has been created');");
pw.println("window.location.href='FoundController?action=listFoundItem';");
pw.println("</script>");
}
catch (Throwable ex) {
System.out.println(ex);
}
}
}
this is my FoundController.java
package lofo.controller;
import java.io.IOException;
import java.io.PrintWriter;
import java.security.NoSuchAlgorithmException;
import java.util.List;
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;
import lofo.dao.foundDAO;
import lofo.model.FoundItemBean;
/**
* Servlet implementation class UserController
*/
#WebServlet("/FoundController")
public class FoundController extends HttpServlet {
private static final long serialVersionUID = 1L;
private String VIEW ="viewFound.jsp";
private String VIEWALL ="listFoundItem.jsp";
private static String UPDATE = "updateFound.jsp";
private static String DELETE = "deleteFound.jsp";
private static String SEARCH = "registerFoundItem.jsp";
String forward;
private foundDAO dao;
/**
* #see HttpServlet#HttpServlet()
*/
public FoundController() {
super();
dao = new foundDAO();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String action = request.getParameter("action");
if(action.equalsIgnoreCase("viewFound")) {
forward = VIEW;
String UserEmail = request.getParameter("UserEmail");
FoundItemBean found = foundDAO.getUserByEmail(UserEmail);
List<FoundItemBean> founds = foundDAO.getAllFound();
request.setAttribute("founds", founds );
request.setAttribute("found", found);
}
else if (action.equalsIgnoreCase("listFoundItem")) {
forward = VIEWALL;
request.setAttribute("founds", foundDAO.getAllFound());
}
else if (action.equalsIgnoreCase("updateFound")){
forward = UPDATE;
String UserEmail = request.getParameter("UserEmail");
FoundItemBean found = foundDAO.getUserByEmail(UserEmail);
List<FoundItemBean> founds = foundDAO.getAllFound();
request.setAttribute("founds", founds);
request.setAttribute("found", found);
}
else if (action.equalsIgnoreCase("search")){
forward = SEARCH;
List<FoundItemBean> found = foundDAO.getAllFound();
request.setAttribute("founds", found);
}
else if (action.equalsIgnoreCase("deleteFound")){
forward = DELETE;
String UserEmail = request.getParameter("UserEmail");
FoundItemBean found = foundDAO.getUserByEmail(UserEmail);
request.setAttribute("found", found);
}
RequestDispatcher view = request.getRequestDispatcher(forward);
view.forward(request, response);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String action = request.getParameter("action");
if(action.equalsIgnoreCase("Submit")) {
String UserEmail = request.getParameter("UserEmail");
String FItemName = request.getParameter("FItemName");
String FItemCategory = request.getParameter("FItemCategory");
String FItemDate = request.getParameter("FItemDate");
String FItemTime = request.getParameter("FItemTime");
String FItemLocation = request.getParameter("FItemLocation");
String FItemDescription = request.getParameter("FItemDescription");
FoundItemBean found = new FoundItemBean();
found.setUserEmail(UserEmail);
found.setFItemName(FItemName);
found.setFItemCategory(FItemCategory);
found.setFItemDate(FItemDate);
found.setFItemTime(FItemTime);
found.setFItemLocation(FItemLocation);
found.setFItemDescription(FItemDescription);
dao = new foundDAO();
try {
dao.updateFound(found);
/*forward = VIEW;
user = UserDAO.getUserByEmail(UserEmail);
request.setAttribute("user", user); */
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<script>");
pw.println("alert('The account is updated');");
pw.println("window.location.href='/lofo/FoundController?action=viewFound&UserEmail="+ UserEmail +"';");
pw.println("</script>");
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//}
//else if(action.equalsIgnoreCase("Delete")) {
//String UserEmail = request.getParameter("UserEmail");
// = new foundDAO();
//dao.deleteUser(UserEmail);
//response.setContentType("text/html");
//PrintWriter pw = response.getWriter();
//pw.println("<script>");
//pw.println("alert('The account has been deleted');");
//pw.println("window.location.href='/Inventory/UserController?action=listAll';");
//pw.println("</script>");
//}
}
}
}
this is my foundDAO.java
package lofo.dao;
import java.sql.Statement;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import lofo.model.FoundItemBean;
import lofo.model.UsersBean;
import lofo.connection.ConnectionManager;
public class foundDAO {
static Connection currentCon = null;
static ResultSet rs = null;
static PreparedStatement ps = null;
static Statement stmt = null;
static String FItemID, UserEmail, FItemName, FItemCategory, FItemDate, FItemTime, FItemLocation, FItemDescription;
public static FoundItemBean getUser(FoundItemBean bean) {
UserEmail = bean.getUserEmail();
String searchQuery = "select * from founditem where useremail='" + UserEmail + "'";
try {
currentCon = ConnectionManager.getConnection();
stmt = currentCon.createStatement();
rs = stmt.executeQuery(searchQuery);
boolean more = rs.next();
// if user exists set the isValid variable to true
if (more) {
String UserEmail = rs.getString("UserEmail");
bean.setUserEmail(UserEmail);
bean.setValid(true);
}
else if (!more) {
System.out.println("Sorry");
bean.setValid(false);
}
}
catch (Exception ex) {
System.out.println("Log In failed: An Exception has occurred! " + ex);
}
finally {
if (rs != null) {
try {
rs.close();
} catch (Exception e) {
}
rs = null;
}
if (stmt != null) {
try {
stmt.close();
} catch (Exception e) {
}
stmt = null;
}
if (currentCon != null) {
try {
currentCon.close();
} catch (Exception e) {
}
currentCon = null;
}
}
return bean;
}
//get user by email
public static FoundItemBean getUserByEmail(String UserEmail) {
FoundItemBean found = new FoundItemBean();
try {
currentCon = ConnectionManager.getConnection();
ps=currentCon.prepareStatement("select * from founditem where useremail=?");
ps.setString(1, UserEmail);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
found.setFItemID(rs.getString("FItemID"));
found.setUserEmail(rs.getString("UserEmail"));
found.setFItemName(rs.getString("FItemName"));
found.setFItemCategory(rs.getString("FItemCategory"));
found.setFItemDate(rs.getString("FItemDate"));
found.setFItemTime(rs.getString("FItemTime"));
found.setFItemLocation(rs.getString("FItemLocation"));
found.setFItemDescription(rs.getString("FItemDescription"));
}
} catch (SQLException e) {
e.printStackTrace();
}
return found;
}
//create Found Item
public void FoundAdd (FoundItemBean bean) throws NoSuchAlgorithmException {
FItemID = bean.getFItemID();
UserEmail = bean.getUserEmail();
FItemName = bean.getFItemName();
FItemCategory = bean.getFItemCategory();
FItemDate = bean.getFItemDate();
FItemTime = bean.getFItemTime();
FItemLocation = bean.getFItemLocation();
FItemDescription = bean.getFItemDescription();
try {
currentCon = ConnectionManager.getConnection();
ps=currentCon.prepareStatement("insert into founditem(FItemID, UserEmail, FItemName, FItemCategory, FItemDate, FItemTime, FItemLocation, FItemDescription) values (FOUNDITEM_SEQ.nextval,?,?,?,?,?,?,?)");
ps.setString(1,UserEmail);
ps.setString(2,FItemName);
ps.setString(3,FItemCategory);
ps.setString(4,FItemDate);
ps.setString(5,FItemTime);
ps.setString(6,FItemLocation);
ps.setString(7,FItemDescription);
ps.executeUpdate();
System.out.println("Your FItemName is " + FItemName);
}
catch (Exception ex) {
System.out.println("failed: An Exception has occured!" + ex);
}
finally {
if (ps != null) {
try {
ps.close();
} catch (Exception e) {
}
ps = null;
}
if (currentCon != null) {
try {
currentCon.close();
} catch (Exception e) {
}
currentCon = null;
}
}
}
//update account
public void updateFound(FoundItemBean bean) throws NoSuchAlgorithmException {
FItemName = bean.getFItemName();
FItemCategory = bean.getFItemCategory();
FItemDate = bean.getFItemDate();
FItemTime = bean.getFItemTime();
FItemLocation = bean.getFItemLocation();
FItemDescription = bean.getFItemDescription();
String searchQuery = "";
searchQuery = "UPDATE founditem SET FItemName ='"+ FItemName +"', FItemCategory='" + FItemCategory + "', FItemDate='" + FItemDate + "', FItemTime='" + FItemTime + "', FItemLocation='" + FItemLocation + "', FItemDescription='" + FItemDescription + "' WHERE UserEmail= '" + UserEmail + "'";
System.out.println(searchQuery);
try {
currentCon = ConnectionManager.getConnection();
stmt = currentCon.createStatement();
stmt.executeUpdate(searchQuery);
System.out.println(searchQuery);
} catch (SQLException e) {
e.printStackTrace();
}
}
//getAllFound for list table
public static List<FoundItemBean> getAllFound() {
List<FoundItemBean> founds = new ArrayList<FoundItemBean>();
try {
currentCon = ConnectionManager.getConnection();
stmt = currentCon.createStatement();
String q = "select * from founditem";
ResultSet rs = stmt.executeQuery(q);
while (rs.next()) {
FoundItemBean found = new FoundItemBean();
found.setUserEmail(rs.getString("UserEmail"));
found.setFItemName(rs.getString("FItemName"));
found.setFItemCategory(rs.getString("FItemCategory"));
found.setFItemDate(rs.getString("FItemDate"));
found.setFItemTime(rs.getString("FItemTime"));
found.setFItemLocation(rs.getString("FItemLocation"));
found.setFItemDescription(rs.getString("FItemDescription"));
founds.add(found);
}
} catch (SQLException e) {
e.printStackTrace();
}
return founds;
}
}
The error message shown in the attached picture is -
"The origin server did not find a current representation for the target resource..."
This error is usually not due to a problem in the code.
This error is caused due to an issue with the IDE (Common with Eclipse), or due to the way the application is deployed on the Web server.
Here is a workaround for this problem:
Take a backup of the project files.
Delete the project from eclipse.
Make sure that the character encoding is set to 'utf-8' in all the html template files**
<html lang="en">
<head>
<meta charset="utf-8"/>
</head>
Restart eclipse.
Do a fresh import of the project into eclipse.
Verify the web.xml file for the correct mapping of servlets
More help:
https://www.codejava.net/java-ee/servlet/solved-tomcat-error-http-status-404-not-found
The origin server did not find a current representation for the target resource or is not ... error when running jsp page
Tomcat 404 error: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists

Inserting a data in jsp by using select and option tag

in my application i am reading a data from table class and i insert the id value in table test. i usually use table and insert link in jsp but this time i need to show my data by option tag and button for inserting. when i click on insert button i have this error ( threw exception [java.lang.NumberFormatException: For input string: ""] with root cause
java.lang.NumberFormatException: For input string: "" )
i have no problem when i use table and link for insert so the servlet and database class working fine. i think problem can be how i am using option tag
jsp file
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<table>
<c:forEach var="tempstudent" items="${select}">
<c:url var="insert" value="add_course">
<c:param name="command" value="insert"/>
<c:param name="courseid" value="${tempstudent.id}"/>
</c:url>
<tr>
<td>${tempstudent.id}</td>
<td>${tempstudent.name}</td>
<td>
<a href="${insert}"
onclick="if (!(confirm('Are you sure you want to insert this student?'))) return false">
insert</a>
</td>
</tr>
</c:forEach>
</table>
<form action="add_course" method="GET">
<input type="hidden" name="command" value="insert" />
<input type="hidden" name="courseid" value="${tempstudent.id}"/>
<select>
<c:forEach var="tempstudent" items="${select}">
<option value="courseid">${tempstudent.id},<td>${tempstudent.name}</td>
</option>
</c:forEach>
</select>
<td><label></label></td>
<td><input type="submit" value="Save" class="save"/></td>
</form>
</body>
</html>
servlet file
package com.web;
import java.io.IOException;
import java.util.List;
import javax.annotation.Resource;
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.sql.DataSource;
/**
* Servlet implementation class add_course
*/
#WebServlet("/add_course")
public class add_course extends HttpServlet {
private dbutil dbutil;
#Resource(name="jdbc/web_student_tracker")
private DataSource dataSource;
#Override
public void init() throws ServletException {
//dbutil= new dbutil(dataSource);
super.init();
try {
dbutil=new dbutil(dataSource);
}
catch(Exception exc) {
throw new ServletException(exc);
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// List<student> student;
// try {
// student = dbutil.getcourse();
// request.setAttribute("select",student);
// RequestDispatcher dispatcher = request.getRequestDispatcher("/course.jsp");
// dispatcher.forward(request,response);
// } catch (Exception e) { // TODO Auto-generated catch block
// e.printStackTrace();
// }
try {
String thecommand=request.getParameter("command");
if(thecommand==null) {
thecommand="LIST";
}
switch(thecommand) {
case"LIST":
listcourse(request,response);
break;
case"insert":
insertcourse(request,response);
break;
}
}
catch(Exception exc) {
throw new ServletException(exc);
}
}
private void insertcourse(HttpServletRequest request, HttpServletResponse response) throws Exception {
int courseid = Integer.parseInt(request.getParameter("courseid"));
student thestudent=new student(courseid);
dbutil.insetcourse(thestudent);
request.setAttribute("message", "Records loaded successfully");
RequestDispatcher dispatcher = request.getRequestDispatcher("/course.jsp");
dispatcher.forward(request,response);
// int courseid = Integer.parseInt(request.getParameter("courseid"));
// student thestudent=new student(courseid);
// dbutil.insetcourse(thestudent);
// insertcourse(request,response);
}
private void listcourse(HttpServletRequest request, HttpServletResponse response) throws Exception {
List<course> student=dbutil.getcourse();
request.setAttribute("select",student);
RequestDispatcher dispatcher = request.getRequestDispatcher("/course.jsp");
dispatcher.forward(request,response);
}
}
// database class
public List <course> getcourse() throws Exception{
List<course> course=new ArrayList<>();
Connection myConn = null;
Statement myStmt = null;
ResultSet myRs = null;
try {
myConn=dataSource.getConnection();
//String sql="select id from class";
String sql ="select id,name from class";
myStmt=myConn.createStatement();
myRs=myStmt.executeQuery(sql);
while (myRs.next()) {
int myid = myRs.getInt("id");
String myname =myRs.getString("name");
course tempstudent = new course(myid,myname);
course.add(tempstudent);
}
return course;
}
finally {
// close JDBC objects
close(myConn, myStmt, myRs);
}
}
public void insetcourse(student thestudent)throws SQLException {
Connection myConn = null;
PreparedStatement myStmt=null;
/////////
try {
myConn = dataSource.getConnection();
String sql="insert into test"+"(id)"+"value(?)";
myStmt=myConn.prepareStatement(sql);
myStmt.setInt(1,thestudent.getId());
myStmt.execute();
}
finally {
close(myConn,myStmt,null);
}
}
Your <select> tag is passing a string value i.e : <option value="courseid">..</option> thats why you are getting java.lang.NumberFormatException: For input string: "" because here value="cousreid" which will get pass it is string .Instead your code should look like below for <select> :
<!--giving name attribute to access it in servlet-->
<select name="select">
<c:forEach var="tempstudent" items="${select}">
<!--passing id-->
<option value="${tempstudent.id}">${tempstudent.id},
<td>${tempstudent.name}</td>
</option>
</c:forEach>
</select>
In your servlet access <select> value using below code :
int courseid = Integer.parseInt(request.getParameter("select"));

Displaying mysql table in a jsp [duplicate]

This question already has answers here:
Show JDBC ResultSet in HTML in JSP page using MVC and DAO pattern
(6 answers)
Closed 5 years ago.
This is my first time asking so im sorry in advance if i messed up.Ok so here it goes
i have this mysql table that i want to display in a jsp page and i actually got it to work but its not really a good approach since all the code(connecting to the database etc) is in the JSP.So i made a java bean that controls the connecting to database and executing sql query part , and a separate JSP page where i can display the table.
main.jsp
<%# page import="java.sql.*" %>
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html">
<head>
<title>Welcome to Car Rental System</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.1/themes/smoothness/jquery-ui.css"></link>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//code.jquery.com/ui/1.11.1/jquery-ui.js"></script>
<script src="jquery.backstretch.min.js"></script>
<link rel="stylesheet" href="style.css"></link>
<link href="https://fonts.googleapis.com/css?family=Source+Sans+Pro" rel="stylesheet">
</head>
<body>
<p><div><center><h1><b>Car Rental System</b></h1></center></div></p>
<%
<jsp:useBean id="displayCarList" class="displayCarList.displayCarList" >
<jsp:setProperty name="displayCarList" property="*"/>
</jsp:useBean>
<%
String carbookId = request.getParameter("carbookId");
String manufacturername = request.getParameter("manufacturername");
String modelname = request.getParameter("modelname");
String price_day = request.getParameter("price_day");
%>
<table border='3' align='center'>
<tr>
<td><b>Car ID</td>
<td><b>Manufacturer</td>
<td><b>Model name</td>
<td><b>Price per day</td>
</tr>
<tr>
<td><%=displayCarList.getCarbookid()%></td>
<td><%=displayCarList.getManufacturername()%></td>
<td><%=displayCarList.getModelname()%></td>
<td><%=displayCarList.getPriceday()%></td>
</tr>
</table>
<br></br>
<form action=secondpage.jsp method="post">
<fieldset><legend>Fill in the form below :</legend>
<p><b>Name:</b> <input type="text" name="name" size="20" maxlength="40" /></p>
<p><b>Telephone number</b> <input type="text" name="phonenumber" th:field="*{phonenumber}" size="20" maxlength="40" /></p>
<p><b>Rental date:</b> <input type="date" th:field="*{rentaldate}" name="rentaldate"></p>
<p><b>Return date:</b> <input type="date" th:field="*{returndate}" name="returndate"></p>
<p><b>Car ID:</b> <input type="text" name="carID" th:field="*{carID}" size="20" maxlength="40" /></p>
<div align="left"><input type="submit" name="submit" value="Submit " /></div>
</form>
<script>
$.backstretch("background2.jpg");
</script>
</body>
</html>
The following is the java bean, displayCarList.java
package displayCarList;
import java.io.*;
import static java.lang.System.out;
import java.util.*;
import javax.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
public class displayCarList {
private String carbookId, manufacturername, modelname, price_day;
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
public displayCarList(){
try {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException ex) {
Logger.getLogger(displayCarList.class.getName()).log(Level.SEVERE, null, ex);
}
con =DriverManager.getConnection ("jdbc:mysql://localhost:3306/rentalcar","root","");
stmt = con.createStatement();
rs = stmt.executeQuery("SELECT * FROM carlist");
while(rs.next()){
carbookId = rs.getString(1);
manufacturername= rs.getString(2);
modelname = rs.getString(3);
price_day = rs.getString(4);
}
stmt.close();
con.close();
// displaying record
} catch (SQLException e) {
System.out.println("couldnotconnecYO");
}
}
public String getCarbookid(){
return carbookId;
}
public void setCarbookid(){
this.carbookId = carbookId;
}
public String getManufacturername(){
return manufacturername;
}
public void setManufacturername(){
this.manufacturername = manufacturername;
}
public String getModelname(){
return modelname;
}
public void setModelname(){
this.modelname = modelname;
}
public String getPriceday(){
return price_day;
}
public void setPriceday(){
this.price_day = price_day;
}
}
But for some reason, only one record is displayed which is the last one , where it shouldve returned everything in the table(supposedly)
enter image description here
So i would appreciate if you guys could help me and point out what i did wrong , and help me get all the records in the table displayed like this one
enter image description here
thanks again
UPDATE
As per the instructions by Shuddh i made a few changes to the codes and yet it still doesnt work for some bloody reason
public ArrayList displayCarList(){
try {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException ex) {
Logger.getLogger(displayCarList.class.getName()).log(Level.SEVERE, null, ex);
}
con =DriverManager.getConnection ("jdbc:mysql://localhost:3306/rentalcar","root","");
stmt = con.createStatement();
rs = stmt.executeQuery("SELECT * FROM carlist");
while(rs.next()){
int i = 1;
while(i <= 12){
carlist.add(rs.getString(i++));
}
}
stmt.close();
con.close();
// displaying record
} catch (SQLException e) {
System.out.println("couldnotconnecYO");
}
return carlist;
}
its now returning null in every colum
The reason you are getting just last row is because you are not storing the other rows anywhere. So it overwrites the variables and this last row is being captured. Store the local variable as list and that will do the trick.
Create a List and add every resultset into that
try {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException ex) {
Logger.getLogger(displayCarList.class.getName()).log(Level.SEVERE, null, ex);
}
con =DriverManager.getConnection ("jdbc:mysql://localhost:3306/rentalcar","root","");
stmt = con.createStatement();
rs = stmt.executeQuery("SELECT * FROM carlist");
while(rs.next()){
carbookId = rs.getString(1);
manufacturername= rs.getString(2);
modelname = rs.getString(3);
price_day = rs.getString(4);
// add to list here.
}
stmt.close();
con.close();
// displaying record
} catch (SQLException e) {
System.out.println("couldnotconnecYO");
}
return List. // If you have no idea about list in java google it and learn how to use it
Write your above code in a method and not in constructor.

In struts 1.3 how to retrieve data from database and display it using DAO

*M new to struts. I am making simple login page that display username and password by retrieving it from database. I m using DAO.
I have LoginDAO.java, LoginAction.java and Displaydata.jsp pages. *
LoginDAO.java
public boolean login(String user,String pass) throws SQLException
{
Connection con = getConnection();
Statement st;
try {
st = con.createStatement();
st.executeQuery("select * from login where Username='" + user + "' and Password='" + pass + "'");
return true;
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
return false;
}
LoginAction.java
public class LoginAction extends Action
{
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
DynaValidatorForm rf= (DynaValidatorForm) form;
String username = rf.get("username").toString();
String password = rf.get("password").toString();
HttpSession session=request.getSession();
session.setAttribute("user", username);
Login dao= new Login();
if(dao.login(username,password))
{
System.out.println("GOT");
return mapping.findForward("success");}
else
{System.out.println("NOT");
return mapping.findForward("failure");
}
}
}
and also what do i write in Dislpaydata.jsp to display username and password in it dont want any java code in it.
Thankyou
Right. Some time ago I built an application with Struts 1.x and MySql with login.
LoginAction
public ActionForward login( ... ) throws Exception {
String forward;
final String mail = PropertyUtils.getProperty(form, "mail");
final String password = PropertyUtils.getProperty(form, "password");
if (LoginService.getInstance().validate(mail, password)) {
// Do something e.g. put name of user in session
forward = SUCCESS;
} else {
forward = ERROR;
}
return mapping.findForward(forward);
}
LoginService
public boolean validate(final String mail, final String password)
throws ServiceException {
try {
final boolean valid;
// Validate null and empty
// Validate with DB
final UserDAO dao = new UserDAO();
final User user = dao.findByPk(mail);
if (user == null) {
valid = false;
} else {
if (password.equals(user.getPassword())) {
valid = true;
} else {
valid = false;
}
}
return valid;
} catch (DAOException e) {
throw new ServiceException("Error validating user and password.", e);
}
}
UserDAO
private static final String FIND_BY_PK_SQL
= "SELECT mail, name, password, admin FROM user WHERE mail = ?";
public User findByPk(final String mail) throws DAOException {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
conn = getConnection();
ps = conn.prepareStatement(FIND_BY_PK_SQL);
ps.setString(1, mail); // PK, NOT NULL
rs = ps.executeQuery();
if (rs.next()) {
return fill(rs);
}
return null;
} catch (final SQLException e) {
throw new DAOException(e);
} finally {
// Close DB resources
}
}
private User fill(final ResultSet rs) throws SQLException {
final User user = new User();
user.setMail(rs.getString("mail"));
user.setName(rs.getString("name"));
user.setPassword(rs.getString("password"));
user.setAdmin(rs.getBoolean("admin"));
return user;
}
In my case I have a table user with mail as a primary key. There are various forms.
More examples:
Building a Login Application
Struts Login Application Using Action Form Tutorial | DZone
Creating a Email Login Web Application with Struts
e.g. For show the name of variable user in session scope from the database:
LoginAction
if (LoginService.getInstance().validate(mail, password)) {
final HttpSession session = request.getSession();
final User user = UserService.getInstance().getUser(mail);
session.setAttribute("user", user);
forward = SUCCESS;
}
home.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#taglib uri="http://struts.apache.org/tags-bean" prefix="bean"%>
Welcome,
<bean:write scope="session" name="user" property="name" filter="false" />
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib uri="/WEB-INF/struts-html.tld" prefix="html"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Login Page</title>
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<script type="text/javascript"
src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.13.1/jquery.validate.min.js"></script>
</head>
<body bgcolor="#2EFEF7">
<form action="action" method="post" id="formDemo" name="MyForm">
<div id="header">
<h2 style="color: red;">Training</h2>
</div>
<hr>
<h3>Login</h3>
<div id="center" style="padding-top: 50px; padding-bottom: 220px;">
<table align="center">
<tr>
<th colspan="2"><h1 style="color: BLUE;">LOGIN</h1></th>
</tr>
<tr>
<th colspan="2"><h5 id="error" style="color: red;"></h5></th>
</tr>
<tr>
<td>UserID:</td>
<td><input type="text" size="40" name="UserId" maxlength="8"></td>
</tr>
<tr>
<td>Password:</td>
<td><input type="text" size="40" name="Password" maxlength="8"></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit"
value="Login"> <input type="button" id="reset"
value="Clear"></td>
</tr>
</table>
</div>
<hr>
<div id="footer">
<label>Copy right# 2000-2008 FUJINET, All Rights Reserved.</label>
</div>
</form>
<script type="text/javascript">
<!--
// Form validation code will come here.
function validate() {
if (document.MyForm.UserId.value === ""
|| document.MyForm.UserId.value === null) {
document.getElementById("error").innerHTML = "Please insert userId";
return false;
}
if (document.MyForm.Password.value === ""
|| document.MyForm.Password.value === null) {
document.getElementById("error").innerHTML = "Please insert password";
return false;
}
return (true);
}
$("#reset").click(function(event) {
document.MyForm.UserId.value = "";
document.MyForm.Password.value = "";
document.getElementById("error").innerHTML = "";
});
$("#formDemo").submit(function(event){
return validate();
});
</script>
</body>
</html>

Not able to fetch values from servlet in jsp

I try to fetch values from servlet into my JSP, but it throws a NullPointerException or some other error.
This is the servlet which gets values from JSP:
buildingprofilerequest.java
package asset.management.arms.buildingprofilemodule;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.sun.xml.internal.ws.client.SenderException;
/**
* Servlet implementation class buildingprofilerequest
*/
public class buildingprofilerequest extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try{
buildingservice building = new buildingservice();
building.setBuilding_name(request.getParameter("combobox"));
building = BuildingDAO.build(building);
request.setAttribute("abcd", building);
RequestDispatcher dispatcher =
getServletContext().getRequestDispatcher("/building_profile_details.jsp");
dispatcher.include(request, response);
}
catch (Throwable theException)
{
System.out.println(theException);
}
}
My bean looks in brief like this:
buildingservice.java
package asset.management.arms.buildingprofilemodule;
public class buildingservice {
private String building_name;
public String getBuilding_name() {
return building_name;
}
public void setBuilding_name(String newbuilding_name) {
this.building_name = newbuilding_name;
}
//and has many more parameters and there getters and setters
}
My other class is BuildingDAO.java, here all the calculations are done:
package asset.management.arms.buildingprofilemodule;
import java.sql.*;
import asset.management.arms.loginmodule.ConnectionManager;
public class BuildingDAO {
static Connection currentCon = null;
static ResultSet rs = null;
public static buildingservice build(buildingservice bean) {
String building_name = bean.getBuilding_name();
String searchQuery = "select * from buildings";
try{
//connect to DB
currentCon = ConnectionManager.getConnection();
stmt=currentCon.createStatement();
rs = stmt.executeQuery(searchQuery);
while(rs.next()){
//retreiving building parameters from database
String buildingname = rs.getString("building_name");
String buildingnumber = rs.getString("building_number");
int buildarea = rs.getInt("build_area");
//setting building parameters
bean.setBuilding_name(buildingname);
bean.setBuilding_number(buildingnumber);
bean.setBuild_area(buildarea);
bean.setBuilt_year(builtyear);
catch (Exception ex)
{
System.out.println(" " + ex);
}
finally
{
if (rs != null) {
try {
rs.close();
} catch (Exception e) {}
rs = null;
}
if (stmt != null) {
try {
stmt.close();
} catch (Exception e) {}
stmt = null;
}
if (currentCon != null) {
try {
currentCon.close();
} catch (Exception e) {
}
currentCon = null;
}
}
return bean;
}
}
My JSP is this:
building_profile_details.jsp
<%# page language="java" contentType="text/html; charset=iso-8859-1"
pageEncoding="ISO-8859-1" import="asset.management.arms.buildingprofilemodule.buildingservice"%>
<% buildingservice hello = (buildingservice) request.getAttribute("abcd"); %>
<table width="1150" height="176" border="1" align="center" bordercolor="lightslategray">
<tr>
<td width="107"><div align="center"><b>Building Number</b> </div></td>
<td width="325"><div align="center"><b>Building Name </b></div></td>
<td width="70"><div align="center"><b>area</b></div></td>
<td width="146"><div align="center"><b>built year</b></div></td>
</tr>
<tr>
<td><div align="center"><%=hello.getBuilding_number()%></div></td>
<td><div align="center"><%= hello.getBuilding_name()%></div></td>
<td><div align="center"><%=hello.getBuild_area()%></div></td>
<td><div align="center"><%= hello.getBuilt_year()%></div></td>
</tr>
</table>
In the JSP I even tried other ways like:
<jsp:useBean id="hello" class="asset.management.arms.buildingprofilemodule.buildingservice">
and then in individual blocks of table:
<jsp:getProperty name="hello" name="building_name">
But nothing works, it throws error which says
org.apache.jasper.JasperException: Exception in JSP: /building_profile_details.jsp:82
82: <td><div align="center"><%=hello.getBuilding_number()%></div></td>
and similarly for other lines.
How is this caused and how can I solve this?
In your servlet, replace
dispatcher.include(request, response);
by
dispatcher.forward(request, response);
In your JSP, remove
<% buildingservice hello = (buildingservice) request.getAttribute("abcd"); %>
and replace
<td><div align="center"><%=hello.getBuilding_number()%></div></td>
<td><div align="center"><%= hello.getBuilding_name()%></div></td>
<td><div align="center"><%=hello.getBuild_area()%></div></td>
<td><div align="center"><%= hello.getBuilt_year()%></div></td>
by
<td><div align="center">${abcd.building_number}</div></td>
<td><div align="center">${abcd.building_name}</div></td>
<td><div align="center">${abcd.build_area}</div></td>
<td><div align="center">${abcd.built_year}</div></td>
See also:
Our Servlets wiki page
Our JSP wiki page
Our EL wiki page
There are by the way many other serious problems in your code, but they are not related to the current concrete problem. I'll however try to sum the most important ones up:
Code holds DB resources as static variables. This is a major threadsafety problem!
Code does not handle exceptions in a sensible manner. This is not developer nor user friendly.
Code does not respect Java naming conventions. This leads to developer confusion and maintainability problems.
Code (particularly the buildingservice and BuildingDAO) uses very odd approaches/patterns/flows. It look like to be written by a procedural programmer who doesn't understand Object Oriented Programming concepts.
JSP uses scriptlets which is discouraged since 2003. Keep yourself up to date. Java code belongs in Java classes and JSP should only contain HTML, JSP tags and EL.
HTML uses deprecated attributes. Keep yourself up to date. Learn CSS.
Work on that as well.

Categories

Resources