Updating database in JSP - java

I coded this Java code for my JSP page to update current login details of a user. Code is not showing any errors or exceptions but not updates the MySql database.
Help me to to implement this functionality;
My code:
<%
//variable declaration for encrypt and decrypt
byte [] input ;
byte [] keyBytes = "12345678".getBytes();
byte [] ivBytes ="input123".getBytes();
SecretKeySpec key = new SecretKeySpec(keyBytes,"DES");
IvParameterSpec ivSpec = new IvParameterSpec(ivBytes);
Cipher cipher;
byte[] cipherText;
int ctLength=0;
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(CONN_STRING, USERNAME, PASSWORD);
if(request.getParameter("submit")!=null){
String cuser=request.getParameter("currentusername");
String user = request.getParameter("username");
String pwd = request.getParameter("password");
String cpwd = request.getParameter("confirmpassword");
Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
input = pwd.getBytes();
key = new SecretKeySpec(keyBytes, "DES");
ivSpec = new IvParameterSpec(ivBytes);
cipher = Cipher.getInstance("DES/CTR/NoPadding","BC");
cipher.init(Cipher.ENCRYPT_MODE, key, ivSpec);
cipherText = new byte[cipher.getOutputSize(input.length)];
ctLength+=cipher.update(input, 0, input.length, cipherText, 0);
ctLength+= cipher.doFinal(cipherText, ctLength);
String enpwd = new String(cipherText);
String sql2 = "update webadmin set username=? ,password=? where username='"+cuser+"' ";
if((cuser!=null &&cuser.length()>0)
&& (user!=null &&user.length()>0)
&& (pwd!=null && pwd.length()>0)
&& cpwd!=null && cpwd.length()>0) {
if((pwd.equals(cpwd))){
pst =conn.prepareStatement(sql2);
pst.setString(1, user);
pst.setString(2, enpwd);
pst.executeUpdate();
%>
<script language="JavaScript">
alert("Sucessfully Updated");
</script>
<%
}else{
%>
<script language="JavaScript">
alert("Passwords are not matching try again");
</script>
<%
}
}
}
}
%>
Note: I implement to encrypt the password and store that encrypted password to the database.
HTML form;
<form id="login-form" action="adminpg-mysettings.jsp" method="post" role="form" style="display: block;">
<div class="form-group">
<input type="text" name="currentusername" id="currentusername" tabindex="1" class="form-control" placeholder="Current Username" value="" required="">
</div>
<div class="form-group">
<input type="text" name="username" id="username" tabindex="1" class="form-control" placeholder="New Username" value="" required="">
</div>
<div class="form-group">
<input type="password" name="password" id="password" tabindex="2" class="form-control" placeholder="New Password" required="">
</div>
<div class="form-group">
<input type="password" name="confirmpassword" id="password" tabindex="2" class="form-control" placeholder="Confirm New Password" required="">
</div>
<div class="form-group">
<div class="row">
<div class="col-sm-6 col-sm-offset-3">
<input type="submit" name="submit" id="submit" tabindex="4" class="form-control btn btn-login" value="Save">
</div>
</div>
</div>
</form>

First of, like everyone will tell you, it is a very bad idea to put Java in JSP. The correct way of operating is with a Servlet and requests stored in session. It will prevent malicious sql injections.
Second of, your security constraints should be handled in the web.xml and Servlet, which is best for back-end maintenance. Following good programming practice will prevent you from going crazy over bugging logs.
I can help you implement what you are trying to do with a Servlet, but before I do, I need to know the following:
The obvious: Do you have a Servlet?
Do you use JDBC/JNDI connectivity?
Do you have entity and session classes for user?
Which IDE/framework do you use to develop your app?
What server are you deploying to?
It is the most effective way of accomplishing what you want. Please provide with the answers and I will update my answer with some code :)

public class UpdateController extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
}
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
int id = Integer.parseInt(request.getParameter("id"));
request.setAttribute("id", new StudentDAO().getStudent(id));
request.getRequestDispatcher("update.jsp").forward(request, response);
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
int id = Integer.parseInt(request.getParameter("id"));
String name = request.getParameter("name");
Date dob = Date.valueOf(request.getParameter("dob")); // yyyy-mm-dd
String gender = request.getParameter("gender");
Student s = new Student();
s.setId(id);
s.setName(name);
s.setGender(gender);
s.setDob(dob);
StudentDAO db = new StudentDAO();
db.update(s);
response.sendRedirect("list");
request.setAttribute("students", new StudentDAO().getAll());
// request.getRequestDispatcher("list.jsp").forward(request, response);
}
public void update(Student s) {
try {
String sql = "UPDATE [dbo].[Student]\n"
+ " SET [name] = ?\n"
+ " ,[gender] = ?\n"
+ " ,[dob] = ?\n"
+ " WHERE id = ?";
PreparedStatement ps = connection.prepareStatement(sql);
ps.setString(1, s.getName());
ps.setString(2, s.getGender());
ps.setDate(3, s.getDob());
ps.setInt(4, s.getId());
ps.executeUpdate();
} catch (SQLException ex) {
Logger.getLogger(StudentDAO.class.getName()).log(Level.SEVERE, null, ex);
}
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Update</title>
<% String id = request.getParameter("id");%>
</head>
<body>
<form action="update" method="post">
<table>
<tr>
<td>ID: <input type="text" name="id"
value="<%=id%>" readonly></td>
</tr>
<tr>
<td>Name: <input type="text" name="name"/></td>
</tr>
<tr>
<td>Gender: <input type="radio" name="gender" value="male"/> Male
<input type="radio" name="gender" value="female"/> Female </td>
</tr>
<tr>
<td>Dob: <input type="date" name="dob" /></td>
</tr>
</table>
<input type="submit" value="Create" />
</form>
</body>

Related

Java error when using two submit buttons on two different forms in a jsp

I am having some trouble figuring out why I am getting an error with my code. Below is my JSP file (the problem is with the second form):
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Book Drivers</title>
</head>
<body>
<h1>Book Demands</h1>
<form method="POST" action="BookDriver.do">
<br>View a table </br>
<input type="radio" name="tbl" value="ListTodaysDemands">List Todays Demands<br />
<input type="radio" name="tbl" value="ListAllDemands">List All Demands<br />
<input type=submit value="Go!"> <br />
</form>
</body>
<body>
<h2>Demands</h2>
<%=(String)(request.getAttribute("query"))%>
</body>
<body>
<h2>Journeys</h2>
<%=(String)(request.getAttribute("query1"))%>
</body>
<body>
<h2>Drivers</h2>
<%=(String)(request.getAttribute("query2"))%>
</body>
<body>
<h2>Book taxi</h2>
<form method="POST" action="BookDriver.do">
<table>
<tr>
<th></th>
<th>Please provide your following details</th>
</tr>
<tr>
<td>Name:</td>
<td><input type="text" name="name"/></td>
</tr>
<tr>
<td>Address:</td>
<td><input type="text" name="address"/></td>
</tr>
<tr>
<td>Destination:</td>
<td><input type="text" name="destination"/></td>
</tr>
<tr>
<td>Date:</td>
<td><input type="text" name="date"/></td>
</tr>
<tr>
<td>Time:</td>
<td><input type="text" name="time"/></td>
</tr>
<tr>
<td> <input type="submit" value="Book"/></td>
</tr>
</table>
</form>
</body>
Below is my controller:
public class BookDriver extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
LocalDate date = LocalDate.now();
String qry1 = "select * from CUSTOMER";
String qry2 = "select * from DRIVERS";
String qry3 = "select * from DEMANDS where date = '"+date+"'";
String qry4 = "select * from DEMANDS";
String qry5 = "select * from JOURNEY";
//String qry4 = "SELECT Drivers.Name, Drivers.Registration FROM Drivers LEFT JOIN Journey ON Journey.Registration = Drivers.Registration LEFT JOIN Demands ON Demands.Time = Journey.Time WHERE Demands.id IS NULL";
//String qry4 = "SELECT Drivers.Name, Drivers.Registration FROM Drivers LEFT JOIN Journey ON Journey.Registration = Drivers.Registration LEFT JOIN Demands ON Demands.Date = Journey.Date LEFT JOIN Demands ON Demands.Time = Journey.Time WHERE Demands.id IS NULL";
response.setContentType("text/html;charset=UTF-8");
HttpSession session = request.getSession(false);
Jdbc dbBean = new Jdbc();
dbBean.connect((Connection)request.getServletContext().getAttribute("connection"));
session.setAttribute("dbbean", dbBean);
if((Connection)request.getServletContext().getAttribute("connection")==null)
request.getRequestDispatcher("/WEB-INF/conErr.jsp").forward(request, response);
else if (request.getParameter("tbl").equals("ListTodaysDemands")){
String msg="No current demands";
String msg2="No current journeys";
String msg3="No current journeys";
try {
msg = dbBean.retrieve(qry3);
msg2 = dbBean.retrieve(qry5);
msg3 = dbBean.retrieve(qry2);
} catch (SQLException ex) {
Logger.getLogger(BookDriver.class.getName()).log(Level.SEVERE, null, ex);
}
request.setAttribute("query", msg);
request.setAttribute("query1", msg2);
request.setAttribute("query2", msg3);
request.getRequestDispatcher("/WEB-INF/bookDemands.jsp").forward(request, response);
}
else if (request.getParameter("tbl").equals("ListAllDemands")){
String msg="No current demands";
String msg2="No current journeys";
String msg3="No current drivers";
try {
msg = dbBean.retrieve(qry4);
msg2 = dbBean.retrieve(qry5);
msg3 = dbBean.retrieve(qry2);
} catch (SQLException ex) {
Logger.getLogger(BookDriver.class.getName()).log(Level.SEVERE, null, ex);
}
request.setAttribute("query", msg);
request.setAttribute("query1", msg2);
request.setAttribute("query2", msg3);
request.getRequestDispatcher("/WEB-INF/bookDemands.jsp").forward(request, response);
}
///////////THIS PART NOT WORKING//////////////////////////
String [] query = new String[5];
query[0] = (String)request.getParameter("name");
query[1] = (String)request.getParameter("address");
query[2] = (String)request.getParameter("destination");
query[3] = (String)request.getParameter("date");
query[4] = (String)request.getParameter("time");
Jdbc jdbc = (Jdbc)session.getAttribute("dbbean");
if (jdbc == null)
request.getRequestDispatcher("/WEB-INF/conErr.jsp").forward(request, response);
if(query[0].equals("") ) {
request.setAttribute("msg", "Username cannot be NULL");
}
request.getRequestDispatcher("/WEB-INF/bookDemands.jsp").forward(request, response);
}
The first form in the JSP works absolutely fine, the issue is with the second form. Whenever I use the button "Book" I get a null pointer exception and I cannot figure out why and if I comment out all of the code to due with the first form in the servlet, then it no longer throws the exception and it works fine.
I would really appreciate some help with this as I have now spent hours searching for a solution online and i'm still very much struggling to solve the problem.
Cheers,
Use request.getParameterValues("name").. and same for others too maybe the current value be null

Java Servlet not receiving values from JSP Form

This is my first time setting up a Java Servlet, I am trying to retrieve values into my Java Servlet from my input fields in my JSP Form when the user clicks a specific button. I also, am unsure if I used the proper practice for creating my Servlet. I simply right-clicked on my Apache Tomcat 8.0 server and then selected new Servlet.
Java Servlet:
#WebServlet("/loginServlet")
public class loginServlet extends HttpServlet {
private static final long serialVersionUID = 3719628899527775749L;
public loginServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.getWriter().append("Served at: ").append(request.getContextPath());
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String username = request.getParameter("username");
String password = request.getParameter("password");
// do some processing here...
// get response writer
PrintWriter writer = response.getWriter();
// build HTML code
String htmlRespone = "<html>";
htmlRespone += "<h2>Your username is: " + username + "<br/>";
htmlRespone += "Your password is: " + password + "</h2>";
htmlRespone += "</html>";
// return response
writer.println(htmlRespone);
}
}
JSP:
<form name="loginForm" action="loginServlet" method="post" id="loginForm">
<div class="imgcontainer">
<img src="images/img_avatar2.png" alt="Avatar" class="avatar">
</div>
<div class="container">
<label><b>Username</b></label>
<input type="text" placeholder="Enter Username" name="uname" required>
<label><b>Password</b></label>
<input type="password" placeholder="Enter Password" name="psw" required>
<button id="loginButton" name="loginButton" type="submit">Login</button>
<button id="registerButton" name="registerButton" type="button">Register</button>
<input type="checkbox" checked="checked"> Remember me
</div>
<div class="container" style="background-color:#f1f1f1">
<button type="button" class="cancelbtn">Cancel</button>
<span class="psw">Forgot password?</span>
</div>
</form>
Your request attribute's name are uname and psw which are added on Jsp page. So you must change your doPost method like this.
String username = request.getParameter("uname");
String password = request.getParameter("psw");
Or
You must change your form in jsp page like this:
<label><b>Username</b></label>
<input type="text" placeholder="Enter Username" name="username" required>
<label><b>Password</b></label>
<input type="password" placeholder="Enter Password" name="password" required>

values are not inserting into database from servlet

I am trying to develop a simple registration form , i have designed it in HTML and for business logic i used servlet but the values are not inserting into the database. Below is the html and servlet file.. Advance thanks those who resolve.
Register.html
<html>
<head>
<title>Register form</title>
</head>
<body>
<form method="post" action="Patient">
PID:<input type="text" name="pid" /><br/>
Title:<input type="text" name="title" /><br/>
First Name:<input type="text" name="firstname" /><br/>
Last Name:<input type="text" name="lastname" /><br/>
Birthday:<input type="date" name="dob" /><br/>
Address:<input type="text" name="address" /><br/>
E-Mail:<input type="text" name="email" /><br/>
Contact Number:<input type="text" name="contact"/><br/>
Gender:
<input type="radio" name="gender" value="male" checked> Male
<input type="radio" name="gender" value="female"> Female
<input type="radio" name="gender" value="other"> Other<br><br>
Occupation:<input type="text" name="occupation"/><br/>
Age:<input type="text" name="age"/><br/>
<label>Spouse/Parent/Legal Guardian Details</label><br>
Name:<input type="text" name="name"/><br/>
E-Mail:<input type="email" name="email2"/><br/>
Address:<input type="text" name="address2"/><br/>
Contact:<input type="text" name="phone"/><br/>
Relation:<input type="text" name="relation"/><br/>
Occupation:<input type="text" name="occupation2"/><br/>
Age Group:<input type="text" name="agegroup"/><br/>
<input type="submit" value="Register" />
</form>
</body>
</html>
Servlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
public class Patient extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.println("Started");
String pid = request.getParameter("pid");
String title = request.getParameter("title");
String firstname = request.getParameter("firstname");
String lastname = request.getParameter("lastname");
String dob = request.getParameter("dob");
String address = request.getParameter("address");
String email = request.getParameter("email");
String contact = request.getParameter("contact");
String gender = request.getParameter("gender");
String occupation = request.getParameter("occupation");
String age = request.getParameter("age");
String name = request.getParameter("name");
String email2 = request.getParameter("email2");
String address2 = request.getParameter("address2");
String phone = request.getParameter("phone");
String relation = request.getParameter("relation");
String occupation2 = request.getParameter("occupation2");
String agegroup = request.getParameter("agegroup");
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/copd","root","root");
PreparedStatement ps=con.prepareStatement("insert into tbl_patient values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
ps.setString(1, pid);
ps.setString(2, title);
ps.setString(3, firstname);
ps.setString(4, lastname);
ps.setString(5, dob);
ps.setString(6, address);
ps.setString(7, email);
ps.setString(8, contact);
ps.setString(9, gender);
ps.setString(10, occupation);
ps.setString(11, age);
ps.setString(12, name);
ps.setString(13, email2);
ps.setString(14, address2);
ps.setString(15, phone);
ps.setString(16, relation);
ps.setString(17, occupation2);
ps.setString(18, agegroup);
int i=ps.executeUpdate();
if(i>0)
{
out.println("Record has been inserted");
}
else
{
out.println("Failed to insert the data");
}
}
catch(Exception se)
{
se.printStackTrace();
}
finally{}
out.println("ended");
}
}
Given that your servlet is activated ("finally" is printed), I can only see 3 options:
Most importantly: close the connection. That would be important even if you didn't have this missing data problem. By closing, you both 'commit' and prevent a leak. For a quick test it's enough that after "ps.executeUpdate" you'll add "con.close()" (In the longer consider putting it in the 'finally' clause).
A less likely option is that there was an exception but you don't see it, so please check all log files of your container
And also a thousand apologies for this silly suggestion, but could you double-check that you're looking into the correct database/table/etc... at least personally I made such silly mistakes in complex environments ;)

Cannot pass multipart data to servlet when using jsp el

I am passing checkbox values, username , file as parameter to a servlet that uses MultipartRequest class from com.orielly.servlet package. I am using the jsp el in my jsp.
my jsp is
<c:set var="currentUser" value="${currentUser}" />
<div class="container">
<div class="panel panel-default" >
<div class="panel-body">
<div class="panel panel-default">
<div class="panel-body">
<form action="ProcessShareFileReq?username="${currentUser}" method="post" enctype="multipart/form-data">
<h4>Upload file here</h4>
<input type="file" class="form-control" required="required" name="file" value=""/>
<h4 class="page header">Share with</h4>
<ul class="list-group">
<c:forEach var="request" items="${requestList}">
<li class="list-group-item title">
<input type="checkbox" name="usersList" value="${request.senderFullName}" /><strong> ${request.senderFullName} </strong>
</li>
</c:forEach>
</ul>
<label class="label" for ="description">Description(Helps other users understand the content of file)</label>
<textarea id="description" name="fileDescription" rows="10" cols="5"></textarea>
<div class="break"></div>
<input type="submit" class="btn btn-default pull-left" value="Upload">
<input type="reset" class="btn btn-default pull-left" value="Reset">
</form>
</div>
</div>
</div>
</div>
</div>
my servlet
#WebServlet("/ProcessShareFileReq")
#MultipartConfig
public class ProcessShareFileReq extends HttpServlet {
private static final long serialVersionUID = 1L;
private String webTempPath;
public void init( ) {
webTempPath= "C://BEProject/Shared";
//webTempPath = getServletContext( ).getRealPath("/") + "data";
}
//Generates current time suitable for oracle timestamp
private static java.sql.Timestamp getCurrentTimeStamp() {
java.util.Date today = new java.util.Date();
return new java.sql.Timestamp(today.getTime());
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Connection currentCon =null;
PreparedStatement ps = null;
int result;
//list of users to share with
String[] UserList = request.getParameterValues("usersList");
//logged-in-user's username
String loggedInUser = request.getParameter("username");
//Shared file's description
String fileDescription = request.getParameter("fileDescription");
//adding path according to sharer's user-name
String userPath = webTempPath + "/" + loggedInUser;
//generate directory
boolean success =( new File(userPath)).mkdirs();
//make directory
if(success) {
System.out.println("Directory: " + webTempPath + " created");
}
//Renames file to the 'sharer_receipent_timestamp' pattern
//Get the uploaded file with multipartRequest
//file limit size of 50 MB
MultipartRequest mpr = new MultipartRequest(request,userPath,50 * 1024 * 1024);
//Database create operations.
Enumeration enum1 = null;
try {
currentCon = ConnectionManager.getConnection();
currentCon.setAutoCommit(true);
for(int i=0;i<UserList.length;i++)
{
String shareFileQuery = "insert into sharedfiles values(share_seq.NEXTVAL,?,?,?,?,?)";
ps = currentCon.prepareStatement(shareFileQuery);
//set the values to put in the query
ps.setString(1, loggedInUser);
ps.setString(2, UserList[i]);
enum1 = mpr.getFileNames( );
String filename = mpr.getFilesystemName((String) enum1.nextElement());
ps.setString(3, filename);
ps.setString(4, fileDescription);
ps.setTimestamp(5, getCurrentTimeStamp());
result=ps.executeUpdate();
if(result>0)
{
System.out.println("Database updated \n");
}
}
} catch (SQLException e) {
e.printStackTrace();
}
response.setContentType("text/html");
request.setAttribute("username", loggedInUser);
RequestDispatcher rd = request.getRequestDispatcher("/SharedFilesHistory");
rd.forward(request, response);
}
I have annotated the servlet with #MultipartConfig so that it can handle the file parameter.
But after adding this it goes upto to the last line and gives error as
java.io.IOException: Corrupt form data: premature ending
com.oreilly.servlet.multipart.MultipartParser.<init>(MultipartParser.java:207)
com.oreilly.servlet.MultipartRequest.<init>(MultipartRequest.java:223)
com.oreilly.servlet.MultipartRequest.<init>(MultipartRequest.java:110)
servlet.share.ProcessShareFileReq.doPost(ProcessShareFileReq.java:104)
javax.servlet.http.HttpServlet.service(HttpServlet.java:646)
javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
filter.authentication.AuthenticationFilter.doFilter(AuthenticationFilter.java:40)
When remvoving the MultipartConfig it gives a NullPointerException at the for loop since 'UserList' is null since no value is received in servlet from jsp.
Please help
I remember having some little issues when working with MultipartRequest (seems related to some bugs), which made me drop its usage in favor of the native Servelt 3.x Part and which may be a good alternative for you:
Inside your doPost method you can retrieve your file as a Part of the request using its name:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
//...
Part filePart = request.getPart("file"); // Retrieves <input type="file" class="form-control" required="required" name="file" value=""/>
InputStream fileContent = filePart.getInputStream(); // Get an InputStream then let the file make its way to your storage location
}

Drop Down list Null Pointer JSP to Servlet

I'm having a difficulty in getting the value on my drop down list from jsp. I'm getting a Null value of String which is "" only. But if I use only textbox for the department It will work. I'm having a hard time of finding where is the error in my code.
This is my JSP file:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<script type="text/javascript" src="js/jquery-1.7.1.min.js"></script>
<script type="text/javascript" src="js/jquery-ui-1.8.18.custom.min.js"></script>
</head>
<body>
<form method="POST" action='PersonnelController' name="frmAddData" class="form">
<fieldset>
<legend id="myLegend">User</legend>
<label for="firstname">First Name :</label>
<input type="text" name="firstname"
value="<c:out value="${data.firstname}" />" /><br />
<label>Last Name :</label>
<input type="text" name="lastname"
value="<c:out value="${data.lastname}" />" /><br />
<!--<label>Department Name :</label>
<input type="text" name="department_id"
value="<c:out value="${data.department_id}" />" /><br />-->
<label>Department Name :</label>
<select name="personnel">
<c:forEach items="${personnels}" var="personnel">
<option value="${personnel.department_id}"><c:out value="${personnel.department_name}" /></option>
</c:forEach>
</select>
</fieldset>
<input type="submit" value="Submit" class="submit"/>
</form>
</body>
</html>
This is for Servlet:
private DepartmentDao dd;
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
List<DepartmentBean> personnels = dd.getAllDepartmentName();
request.setAttribute("personnels", personnels);
request.getRequestDispatcher("/WEB-INF/personnel.jsp").forward(request, response);
}
}
and this is my DAO:
public List<DepartmentBean> getAllDepartmentName() {
List<DepartmentBean> departments = new ArrayList<DepartmentBean>();
try {
Statement statement = connection.createStatement();
ResultSet rs = statement.executeQuery("select department_name,id from department ORDER BY department_name");
while (rs.next()) {
DepartmentBean department = new DepartmentBean();
department.setPeople_manager_name(rs.getString("department_name"));
departments.add(department);
}
} catch (SQLException e) {
e.printStackTrace();
}
return departments;
The problem is that you're not fulfilling the necessary fields in your DepartmentBean object reference in the dao class. You're only filling people_manager_name field, and in your JSP you're requesting the data for department_id and department_name, which will call DepartmentBean#getDepartment_id() and DepartmentBean#getDepartment_name() methods.
Change this in getAllDepartmentName method:
while (rs.next()) {
DepartmentBean department = new DepartmentBean();
department.setDepartment_name(rs.getString("department_name"));
department.setDepartment_id(rs.getInt("department_id"));
departments.add(department);
}
Here's a useful link about how expression language works.

Categories