How I can get object as parameter from Servlet - java

I can't understand how I can use getParameter() with object, as I understand it's impossible. And what I should do?
Currency currency = req.getParameter("currencies");-it doesn't work.
My servlet:
public class AddPurseServlet extends HttpServlet {
private PurseDao purseDao;
private CurrencyDao currencyDao;
#Override
public void init() throws ServletException {
purseDao = (PurseDao) getServletContext().getAttribute("purseDao");
currencyDao = (CurrencyDao) getServletContext().getAttribute("currencyDao");
}
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
List<Currency> currencies = currencyDao.getAll();
req.setAttribute("currencies", currencies);
req.getRequestDispatcher("WEB-INF/view/addPurse.jsp").forward(req, resp);
}
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
HttpSession session = req.getSession();
User user = (User) session.getAttribute("user");
String amount = req.getParameter("amount");
Currency currency = req.getParameter("currencies");
Purse purse = new Purse(user, currency, new BigDecimal(amount), new Timestamp(System.currentTimeMillis()));
purseDao.insert(purse);
resp.sendRedirect("userPage");
}
}
And my jsp page where I require parameters of currency and amount:
<html>
<head>
<title>Title</title>
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap-theme.min.css">
<script src="//netdna.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>
</head>
<body>
<h1>Hello USER!</h1>
<div class="container">
<h1>Save User</h1>
<form method="post" action="addPurse">
<div class="form-group">
<label>Currency</label>
<select>
<c:forEach var="currency" items="${currencies}">
<option value="${currency.id}">${currency.name}</option>
</c:forEach>
</select>
</div>
<div class="form-group">
<label>Amount</label>
<input class="form-control" name="amount" placeholder="Amount">
</div>
<input class="btn btn-default btn-xs" type="submit" value="Save">
<a class="btn btn-default btn-xs" href="usersList" role="button">cancel</a>
</form>
</div>
</body>
</html>

So what I understand from your code is that you are trying to populate a list of currencies and then try to set some amount for the currency object.
For this, you have your currencies identified by a unique ID. That's perfect.Now what you need to understand is that you don't really need the object from the JSP page. All you need is the ID of the currency.
So I would go around and modify your JSP with something like this:
<html>
<head>
<title>Title</title>
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap-theme.min.css">
<script src="//netdna.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>
</head>
<body>
<h1>Hello USER!</h1>
<div class="container">
<h1>Save User</h1>
<form method="post" action="addPurse">
<div class="form-group">
<label>Currency</label>
<select id="currency" name="currency">
<c:forEach var="currency" items="${currencies}">
<option value="${currency.id}">${currency.name}</option>
</c:forEach>
</select>
</div>
<div class="form-group">
<label>Amount</label>
<input class="form-control" name="amount" placeholder="Amount">
</div>
<input class="btn btn-default btn-xs" type="submit" value="Save">
<a class="btn btn-default btn-xs" href="usersList" role="button">cancel</a>
</form>
</div>
</body>
</html>
Now, coming to your servlet. Seeing the keywords "DAO" and "CurrencyDAO", I assume that you are using JPA/Hibernate. So you need to modify the code with something like this:
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
HttpSession session = req.getSession();
User user = (User) session.getAttribute("user");
String amount = req.getParameter("amount");
String currencyid = req.getParameter("currency");
//Get your currency object from database
Currency currencyToBeEdited = currencyDao.findById(Integer.parseInt(currencyid));
//Add the code to set the amount and save it back to the database
Purse purse = new Purse(user, currency, new BigDecimal(amount), new Timestamp(System.currentTimeMillis()));
purseDao.insert(purse);
resp.sendRedirect("userPage");
}
Note: I am not 100% sure about your goal but I have provided the advice that would hopefully take you in the right direction

Parameters are strings.
If your currency is an enum
final String currencyStr = request.getParameter("currency");
final Currency currency = Stream.of(Currency.values()).filter(currency -> currency.code.equals(currencyStr)).findFirst().orElse(null));

Related

Java Servlet HttpServletRequest parameters showing up as null

I am trying to get form parameters from a GET request. The html code is below.
<!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">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>DesignMatch. Matching the best clients and best designers.</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" src="jquery.backstretch.js"></script>
<script type="text/javascript" src="design_match.js"></script>
<link rel="stylesheet" type="text/css" media="all" href="design_match.css" />
</head>
<body>
<div id="matte_bg"></div>
<div id="entire_wrapper">
<div class="divModule" id="section_head_1">
<p class="primaryPageText">
Clients
</p>
<div class="url-bar">
<form name="clientUrls" action="SaveDatabase2" target="_blank" method="get">
<input type="text" class="url-box" id="url-box1" name="name1" size="20" value="Paste a link to a website that has the design qualities you want.">
<a id="add-url" href="#">Add</a>
<a id="del-url" href="#">Remove</a>
</form>
</div>
</div>
<div class="divModule" id="section_head_2">
<p class="primaryPageText">
Designers
</p>
<div class="portfolio-bar">
<form name="designerUrls" action="SaveDatabase2" target="_blank" method="get">
<input type="text" class="portfolio-box" id="portfolio-box1" name="name1" size="20" value="Paste a link to a website you designed.">
<a id="add-portfolio" href="#">Add</a>
<a id="del-portfolio" href="#">Remove</a>
</form>
</div>
</div>
<div class="divModule">
<div class="filterSentence">
<ul class="primaryPageText">
<li>
To me,
</li>
<li class="budgetTypeFilter">
[what price]
<div id='budgetFilter' style="display:none" class="budgetTypeMenu">
$500 and under
$500-$1,000
$1,000-$2,500
$2,500-$5,000
$5,000-$7,500
$7,500-$10,000
Over $10,000
</div>
</li>
<li>
seems fair to pay for
</li>
<li class="budgetTypeFilter">
[what type of]
<div id='typeFilter' style="display:none" class="budgetTypeMenu">
a basic (e.g., front-end only)
a dynamic (e.g., a little back-end)
a sophisticated (e.g., lots of back-end)
</div>
</li>
<li>
website.
</li>
</ul>
</div>
</div>
<div class="divModule contact-bar" id="contact">
<form name="nameForm" action="SaveDatabase2" target="_blank" method="get">
<input type="text" id="name_form" name="name_form" size="20" value="Tell us your name.">
</form>
<form name="contactForm" action="SaveDatabase2" target="_blank" method="get">
<input type="text" id="contact_form" name="contact_form" size="20" value="Enter your e-mail (no spam, ever).">
</form>
</div>
<div id="submit">
<form accept-charset="UTF-8" action="SaveDatabase2" method="get">
<input class="btn primary large" id="submit-button" name="submit" type="submit" value="✔" />
</form>
</div>
</div>
</body>
</html>
Here is the Servlet code. The parameter values I get in doPost are null. I tried changing all the get requests to post in the html and it didn't help. The doGet function is just rerouted to doPost. The two main parameters I am interested in right now are the "contact_form" and "name_form" parameters at the end of the html. Thanks again!
package web;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.mysql.jdbc.StringUtils;
import java.sql.*;
import java.io.*;
import java.util.*;
/**
* Servlet implementation class SaveDatabase2
*/
public class SaveDatabase2 extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public SaveDatabase2() {
super();
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doPost(request, response);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<h1> Thank You </h1>");
//Get Info for Database
int designer=0;
String clientType="";
String name= "";
String email="";
//Get parameters to put into database
Enumeration parameterNames = request.getParameterNames();
if ((request.getParameter("designerUrls")!=null) && !request.getParameter("designerUrls").matches(".*\\w.*") ){
designer=1;
}
if (designer==1){
clientType="designer";
}else clientType="client";
name= request.getParameter("name_form");
email=request.getParameter("contact_form");
}
First of all, I think you should leave doPost and doGet as 2 different methods. doPost will automatically be triggered if you set the attribute method of your form to post.
Besides, your form should be like this:
<form name="myForm" accept-charset="UTF-8" action="SaveDatabase2" target="_blank" method="post">
<input type="text" id="name_form" name="name_form" size="20" value="Tell us your name.">
<input type="text" id="contact_form" name="contact_form" size="20" value="Enter your e-mail (no spam, ever).">
<input class="btn primary large" id="submit-button" name="submit" type="submit" value="✔" />
</form>
In your question, the submit button is in its own form which does not contain the 2 input text fields: name_form and contact_form. That's why you got the null values.
I think you are misunderstanding the <form> element. To send data from the page to the servlet you can use method="get" or method="post" - both still send the data one way (client to server). For the difference see When do you use POST and when do you use GET?
The <form> can encompass many <input>s and but the crucial part that is missing from your code is that the <form> that is submitting (the one with the <input type="submit"/>) does not contain any of the <input> elements you are expecting. They are in other <form>s which are not submitted. Only the <form> that contains the submit button is submitted.
You should use one <form> around all your fields and submit button.

ModelAttribute Values are not populating values

I have a form as shown below
<!DOCTYPE html>
<html>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<head>
<meta charset="utf-8" />
<title>Dealer Details</title>
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" />
<link href="css/app.css" rel="stylesheet" />
<script src="//code.jquery.com/jquery-2.0.3.min.js"></script>
<script type="text/javascript">
function onChange() {
var value = ($("#jsonTextArea").text());
alert(value);
document.getElementById("jsonTextHidden").value = value;
};
</script>
</head>
<body class="body-bg">
<form modelAttribute="jsonString" method="post" action="postHome">
<div class="container">
<div class="col-sm-8 col-sm-offset-2">
<div class="row">
<div class="col-md-6 col-md-offset-3">
<div class="centerediv">
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">Select Home</h3>
</div>
<div class="panel-body">
<div class="form-group">
<textarea rows="4" cols="40" name="jsonTextArea"></textarea>
</div>
<input class="btn btn-danger" type="button" value="Cancel">
<input class="btn btn-success" type="submit" value="Ok" onclick="onChange();">
<input type=hidden id="jsonTextHidden" name="jsonTextHiddenField" />
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</form>
</body>
</html>
I have a controller class as shown below.
#Controller
public class HomeController {
#RequestMapping(value = "/home", method = RequestMethod.GET)
public String callHomePage() {
return "home";
}
#POST
#Consumes({MediaType.APPLICATION_XML})
#RequestMapping(value = "/postHome")
public ModelAndView postHomeList(#ModelAttribute("jsonString") HomeRequest request, #Context HttpServletRequest servletReq, #Context HttpServletResponse servletRes) {
ModelAndView mav = null;
System.out.println(request.getHomeId());
return mav;
}
}
In this home.jsp a textarea field is there where I can enter some values ( json string ). After submission the value for request.getHomeId() is coming as null. Can any one help me to solve this issue?
Create a HomeRequestDTO
e.g
public class HomeRequestDto {
private Integer homeId;
private String homeName;
//your getter and setter
}
2.
#RequestMapping(value = "/home", method = RequestMethod.GET)
public String callHomePage(final Model model) {
HomeRequestDto home = new HomeRequestDto();
home.setHomeName("Princess Home");
home.setHomeId(123);
model.addAttribute("homeRequest", home);
return "home";
}
3.
your home.jsp
<form:form commandName="homeRequest" name="homeRequest" method="post" enctype="multipart/form-data" action="postHome" >
<spring:bind path="homeRequest.homeName">
<form:textarea maxlength="100" path="${status.expression}"/>
</spring:bind>
<spring:bind path="homeRequest.homeId">
<form:textarea maxlength="100" path="${status.expression}"/>
</spring:bind>
<input type="submit" value="Submit" />
4.on submit your controller
#POST
#RequestMapping(value = "/postHome")
public String postHomeList(#ModelAttribute HomeRequestDto home,
#Context HttpServletRequest servletReq, #Context HttpServletResponse servletRes) {
System.out.println(home.getHomeId());
System.out.println(home.getHomeName());
return "home";
}

My servlet returns null

I wrote the following form and servlet , hoping that the servlet would return the value of the text field from the form , but it returns null instead. What should be corrected ?
<html>
<head>
<title>Simple form</title>
</head>
<body>
<form method="post" action="theServlet">
<input type="text" id="userName"/>
<input type="submit" value="Post"/>
</form>
</body>
</html>
public class theServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String username=request.getParameter("userName");
response.setContentType("text/html");
PrintWriter writer=response.getWriter();
writer.println("<html>");
writer.println("userName = "+ username);
writer.println("</html>");
}
}
You should use name attribute instead of id to send parameters to the server.
<input type="text" id="userName" name="username" />

The server encountered an internal error that prevented it from fulfilling this request - in servlet 3.0

I want to run easy registration jsp page with servlet. And it throw this error message:
description The server encountered an internal error that prevented it from fulfilling this request.
java.lang.NullPointerException
com.java.task11.utils.ValidationUtils.isEmailValid(ValidationUtils.java:22)
com.java.task11.webapp.RegistrationServlet.validateInputs(RegistrationServlet.java:95)
com.java.task11.webapp.RegistrationServlet.processRegistration(RegistrationServlet.java:66)
com.java.task11.webapp.RegistrationServlet.doPost(RegistrationServlet.java:39)
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)
Here is my registration.jsp:
<%# page contentType="text/html;charset=UTF-8" language="java" pageEncoding="UTF-8" %>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%# taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<c:set var="language"
value="${not empty param.language ? param.language : not empty language ? language : pageContext.request.locale}"
scope="session"/>
<fmt:setLocale value="${language}"/>
<fmt:setBundle basename="com.java.task11.i18n.text"/>
<html lang="${language}">
<head>
<title>Registration</title>
<jsp:include page="parts/header.jsp"/>
</head>
<body>
<div class="container-fluid registration">
<div class="row">
<div class="login-screen">
<div class="login-part">
<div class="login-ico col-md-1 col-sm-2 col-xs-12 col-md-offset-3">
<h4>
<small><fmt:message key="registration.label"/></small>
</h4>
</div>
<div class="login-form col-md-4 col-sm-8 col-xs-12 col-md-offset-1 col-sm-offset-1">
<form action="/registration" enctype="multipart/form-data" method="post">
<%-- error messages --%>
<div class="form-group">
<c:forEach items="${registrationErrors}" var="error">
<p class="error">${error}</p>
</c:forEach>
</div>
<%-- input fields --%>
<div class="form-group">
<input class="form-control" placeholder="<fmt:message key="employee.firstName"/>" name="first_name" required
id="first-name"/>
<label class="login-field-icon fui-user"></label>
</div>
<div class="form-group">
<input class="form-control" placeholder="<fmt:message key="employee.lastName"/>" name="last_name" required
id="last-name"/>
<label class="login-field-icon fui-user"></label>
</div>
<div class="form-group">
<div class="input-group">
<span class="input-group-btn">
<span class="btn btn-primary btn-file">
<fmt:message key="button.browse"/>
<input type="file" name="userImage" accept="image/*"/>
</span>
</span>
<input type="text" class="form-control" readonly="">
</div>
</div>
<div class="form-group">
<input class="form-control" type="email" placeholder="<fmt:message key="login.email"/>" name="email"
pattern="[^ #]*#[^ #]*\.[^ #]{2,}" required id="email"/>
<label class="login-field-icon fui-mail"></label>
</div>
<div class="form-group">
<input class="form-control" type="password" placeholder="<fmt:message key="employee.password"/>" name="password" required
id="password"/>
<label class="login-field-icon fui-lock"></label>
</div>
<div class="form-group">
<input class="form-control" type="text" placeholder="<fmt:message key="employee.position"/>" name="position" required
id="position"/>
<label class="login-field-icon fui-plus"></label>
</div>
<div class="form-group">
<button class="btn btn-primary btn-lg btn-block" name="submit"
type="submit" value="Submit">
<fmt:message key="button.submit"/>
</button>
<a class="login-link" href="<c:url value="/login"/>"><fmt:message key="registration.login"/></a>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
<jsp:include page="parts/scripts.jsp"/>
</body>
</html>
RegistrationServlet:
#WebServlet("/registration")
public class RegistrationServlet extends HttpServlet {
private static Logger log = Logger.getLogger(RegistrationServlet.class);
private EmployeeService employeeService = new EmployeeService();
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) {
try {
request.getRequestDispatcher("/pages/registration.jsp").forward(request, response);
} catch (ServletException | IOException e) {
log.error(e);
}
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) {
try {
request.setCharacterEncoding("UTF-8");
processRegistration(request, response);
} catch (ServletException | IOException e) {
log.error(e);
e.printStackTrace();
}
}
private void processRegistration(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
String firstName = request.getParameter("first_name");
String lastName = request.getParameter("last_name");
String email = request.getParameter("email");
String password = request.getParameter("password");
String imageName = "default.png";
String position = request.getParameter("position");
System.out.printf("Request fields: %s %s %s %s %s%n", firstName, lastName, email, password, position);
Part filePart = request.getPart("userImage");
try {
String contentType = filePart.getContentType();
if (contentType.startsWith("image")) {
File image = FileUploadUtils.uploadFile(this, "img\\employees", filePart);
imageName = FileUploadUtils.getFilename(image);
}
} catch (Exception e) {
log.error(e);
}
List<String> registrationErrors = validateInputs(firstName, lastName, email, password, position);
if (registrationErrors.size() > 0) {
request.setAttribute("registrationErrors", registrationErrors);
request.getRequestDispatcher("/pages/registration.jsp").forward(request, response);
} else {
Employee employee = new Employee();
employee.setFirstName(firstName);
employee.setLastName(lastName);
employee.setEmail(email);
employee.setEncryptedPassword(password);
employee.setImage(imageName);
employee.setPosition(position);
employeeService.save(employee);
response.sendRedirect("/login");
}
}
private List<String> validateInputs(String firstName, String lastName, String email, String password, String position) {
List<String> registrationErrors = new ArrayList<>();
if (ValidationUtils.isNullOrEmpty(firstName)) {
registrationErrors.add(ValidationErrors.FIRST_NAME);
}
if (ValidationUtils.isNullOrEmpty(lastName)) {
registrationErrors.add(ValidationErrors.LAST_NAME);
}
if (!ValidationUtils.isEmailValid(email)) {
registrationErrors.add(ValidationErrors.EMAIL);
}
if (employeeService.getByEmail(email).getId() != 0) {
registrationErrors.add(ValidationErrors.EMAIL_ALREADY_PRESENT);
}
if (ValidationUtils.isNullOrEmpty(password)) {
registrationErrors.add(ValidationErrors.PASSWORD);
}
if (!ValidationUtils.isNullOrEmpty(position)) {
registrationErrors.add(ValidationErrors.POSITION_EMPTY);
}
return registrationErrors;
}
}
It couldn't extract from request parameters. From my easy checking it prints:
Request fields: null null null null null
I couldn't figure out why this happen?
Any suggestions?
In here:
if (ValidationUtils.isNullOrEmpty(lastName)) {
registrationErrors.add(ValidationErrors.LAST_NAME);
}
if (!ValidationUtils.isEmailValid(email)) {
registrationErrors.add(ValidationErrors.EMAIL);
}
you check for null or empty value on lastname, but in isEmailValid you don't check for empty value. Something like this should do
if (ValidationUtils.isNullOrEmpty(email) || !ValidationUtils.isEmailValid(email)) {
registrationErrors.add(ValidationErrors.EMAIL);
}
or better yet, fix your ValidationUtils.isEmailValid() to cope with null email values. It shouldn't crash, it should just return false.
I found solution. It works fine when I throw away next line from form:
enctype="multipart/form-data"
And now it pass all parameters at request ok:
<form action="/registration" method="post">
<%-- error messages --%>
<div class="form-group">
<c:forEach items="${registrationErrors}" var="error">
<p class="error">${error}</p>
</c:forEach>
</div>

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.

Resources