Drop Down list Null Pointer JSP to Servlet - java

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.

Related

ThymeLeaf: Neither BindingResult nor plain target object for bean name available as request attribute

I am trying to build a simple select and Option list in thymeleaf, but i keep getting the error
Neither BindingResult nor plain target object for bean name 'BOLForm' available as request attribute
I am pretty sure there is something wrong with my bol.html. But not able to figure out the missing mappings.
Below is my Controller:
#Controller
public class BillOfLadingController {
#Autowired
private DepotList depotList;
#GetMapping("/BillOfLading")
public String getBOLForm(){
return "bol";
}
#PostMapping("/BillOfLading")
public String Login(#ModelAttribute(name="BOLForm") BOLForm bolForm,Model model) {
model.addAttribute("BOLForm", bolForm);
List<DepotDetailEntity> depotDropDown = depotList.getDepots().getDepotDetail();
if(depotDropDown.size() == 0) {
return "login";
}
model.addAttribute("depots", depotDropDown);
return "bol";
}
}
The Form Class
#Component
public class BOLForm {
private String BOL;
private String depotId;
public String getBOL() {
return BOL;
}
public void setBOL(String bOL) {
BOL = bOL;
}
public String getDepotId() {
return depotId;
}
public void setDepotId(String depotId) {
this.depotId = depotId;
}
}
the bol.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="ISO-8859-1">
<title>BillOfLading Request Page</title>
</head>
<body>
<h1>BillOfLading Report</h1>
<form th:action="#{/BillOfLading}" th:object="${BOLForm}" method="post">
<label for="bol">BOL No.</label>
<input type="text" id="bol" name="bol">
<br/>
<table>
<tr>
<td>Select DC:</td>
<td>
<select th:field="*{depotId}">
<option value=""> -- </option>
<option th:each="depot : ${depots}"
th:value="${depot.depotId}"
th:utext="${depot.depotName}"/>
</select>
</td>
</tr>
<tr>
<td><input name="submit" type="submit" value="submit" /></td>
</tr>
</table>
</form>
</body>
</html>
When I replace my bol.html as below, it works:
<form th:action="#{/BillOfLading}" th:object="${BOLForm}" method="post">
<label for="bol">BOL No.</label>
<input type="text" id="bol" name="bol">
<br/>
<label for="depotId">DepotID </label>
<input type="text" id="depotId" name="depotId">
<br/>
In the controller, you need to add the BOLForm object as an attribute of the model:
#GetMapping("/BillOfLading")
public String getBOLForm(Model model){
model.addAttribute("BOLForm", new BOLForm());
return "bol";
}

How to display different title depends on action?

I have got two methods that redirect to the same .html file.
First method is method responsible for saving, the second method is for updating.
It has got the same view so I just wanted to move user to the same view.
I have <h1>..</h1> in .html I would like to have title "New Mapping" for adding new mapping and "Update mapping" when we want to update mapping.
These are methods that do all the stuff (redirecting to the .html file)
#RequestMapping(path = "/.../update", method = RequestMethod.GET)
public String updatePage(#RequestParam("...") String ..., Model model) {
String[] tokens = ....split("_");
Template template= class.method(...);
model.addAttribute("template", template);
return "save";
}
#RequestMapping(path = "/.../save")
public String newMappingPage(Model model) {
Template template = new Template();
template.setCostIndex("10");
model.addAttribute("template", template);
return "save";
}
#RequestMapping(path = "/.../save", method = RequestMethod.POST)
public String saveMapping(#ModelAttribute Template template) {
class.method(template);
return "redirect:/main-page";
}
save.hml file
<html>
<head>
<title>Engine</title>
<link rel="stylesheet" th:href="#{/css/file.css}"/>
</head>
<body>
<h1>New/Update mapping</h1>
<form action="save" method="post" th:object="${template}">
<fieldset>
<label for="...">....[min]</label>
<input type="number" id="..." th:field="*{...}" step="0.1" min="0"/>
<label for="...">...</label>
<input type="number" id="...." th:field="*{...}" required="true"/>
<label for="...">....</label>
<input type="text" id="..." th:field="*{...}" maxlength="1024" size="50"/>
<br/>
<br/>
<label for="response">Response</label>
<br/>
<textarea id="response" rows="20" cols="150" th:field="*{...}" required="true"/>
<br/>
<input id="submit" type="submit" class="primary" value="Submit"/>
</fieldset>
</form>
</body>
</html>
You do not need to create two separate methods for add and update as you are storing data into DB from JSP page. use only one /save API.
#PostMapping(path = "/.../{}/save")
public String newMappingPage(Model model) {
Template template = new Template();
template.setCostIndex("10");
model = new Model();
if (model.getId() > 0) {
model = findById(model.getId());
model.addAttribute("heading", "Update Mapping");
} else {
model.addAttribute("heading", "New Mapping");
}
//Call method to store data from jsp file
return "save";
}
In JSP :
<html>
<head>
<title>Engine</title>
<link rel="stylesheet" th:href="#{/css/file.css}"/>
</head>
<body>
<h1>${heading}</h1>
<form action="save" method="post" th:object="${template}">
<fieldset>
<label for="...">....[min]</label>
<input type="number" id="..." th:field="*{...}" step="0.1" min="0"/>
<label for="...">...</label>
<input type="number" id="...." th:field="*{...}" required="true"/>
<label for="...">....</label>
<input type="text" id="..." th:field="*{...}" maxlength="1024" size="50"/>
<br/>
<br/>
<label for="response">Response</label>
<br/>
<textarea id="response" rows="20" cols="150" th:field="*{...}" required="true"/>
<br/>
<input id="submit" type="submit" class="primary" value="Submit"/>
</fieldset>
</form>
</body>
</html>
Update your method like this:
#PostMapping(path = "/.../{}/save")
public ModelAndView save(Model model) {
ModelAndView obj = new ModelAndView("save");
model = new Model();
if (model.getId() > 0) {
model = findById(model.getId());
obj .addAttribute("heading", "Update Mapping");
} else {
obj .addAttribute("heading", "New Mapping");
}
//Call method to store data from jsp file
return obj;
}

Inputing data into Google Cloud Datastore

I am trying to create a page that will code that will take in student information from html and use java servlets to catch the information and put into Google Cloud Datastore.
I have the HTML working but whenever I try to run it the page just refreshes and doesn't put anything into the cloud datastore.
I am new to servlets so I'm not sure what I am missing.
Below is the jsp file (i.e add_student.jsp)
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
Add Student
Search Student
Update Student
Delete Student
<form method="post">
<p>Student Number <input name="student_number" type="number" required /></p>
<p>First Name <input name="f_name" type="text" required/></p>
<p>Last Name <input name="l_name" type="text" required/></p>
<p>Address (temporary) <input name="temp_address" type="text" required/></p>
<p>Address (permanent) <input name="perm_address" type="text" required/></p>
<p>Home Number <input name="home_number" type="number" required/></p>
<p>Mobile Number <input name="mobile_number" type="number" required/></p>
<p>Date of Birth <input name="birth_date" type="date" required/></p>
<p>Gender <p>Gender: <br>
<input type="radio" name="gender" value="M" required checked> Male<br>
<input type="radio" name="gender" value="F" required> Female<br>
<p>Major <input name="major" type="text" required/></p>
<p>Course <input name="course" type="text" required/></p>
<p>Study Mode <p>Study Mode: <br>
<input type="radio" name="study_mode" value="full_time" checked> Full-Time<br>
<input type="radio" name="study_mode" value="part_time" required> Part-Time<br>
<p>Start Date <input name="start_date" type="date" required /></p>
<p>End Date <input name="end_date" type="date" required /></p>
<p>Add Student <input name="submitButton" type="submit" value="addStudent" /></p>
</form>
</body>
</html>
Here's the java Servlet file (i.e add_studentServlet.java)
package assignment_redo;
import java.io.IOException;
import javax.servlet.http.*;
import com.google.appengine.api.datastore.*;//import the datastore files from google
#SuppressWarnings("serial")
public class add_studentServlet extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
resp.setContentType("text/html");
String title ="Using the GET Method to Read Form Data!";
String student_number = req.getParameter("student_number");
String f_name =req.getParameter("f_name");
String l_name=req.getParameter("l_name");
String perm_address = req.getParameter("perm_address");
String temp_address = req.getParameter("temp_address");
String home_number = req.getParameter("home_number");
String mobile_number = req.getParameter("mobile_number");
String birth_date = req.getParameter("birth_date");
String gender = req.getParameter("gender");
String major = req.getParameter("major");
String course = req.getParameter("course");
String study_mode = req.getParameter("study_mode");
String start_date = req.getParameter("start_date");
String end_date = req.getParameter("end_date");
// //creating an object of type DatastoreService
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
//creating a new entity of type employee
Entity student = new Entity("Student", student_number);
//set its properties
student.setProperty("f_name", f_name);
student.setProperty("l_name", l_name);
student.setProperty("student_number", student_number);
student.setProperty("temp_address", temp_address);
student.setProperty("perm_address", perm_address);
student.setProperty("home_number", home_number);
student.setProperty("mobile_number", mobile_number);
student.setProperty("birth_date", birth_date);
student.setProperty("gender", gender);
student.setProperty("major", major);
student.setProperty("course", course);
student.setProperty("study_mode", study_mode);
student.setProperty("start_date", start_date);
student.setProperty("end_date", end_date);
//insert student entity into Datastore
datastore.put(student);
//display success message now
resp.getWriter().println("Student with id "+student_number+" added to the system!");
}
}
You have to indicate in your jsp that you are submitting the form to your servlet:
<form action="addStudent" method="post">
This makes the assumption that in the web.xml you have configured your servlet as follow:
<servlet>
<servlet-name>add_studentServlet</servlet-name>
<servlet-class>assignment_redo.add_studentServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>add_studentServlet</servlet-name>
<url-pattern>/addStudent</url-pattern>
</servlet-mapping>
Then you have to put your code in the doPost of your servlet, not in the doGet.

How to combine an javabean with jquery validation plugin?

I am building a web app where users can sign up. I have a jquery validation method for the signup form.
What I need is to also validate the username for availability according to my database.
I am not allowed to use php to do this, so i need to use java, a javabean for that cause.
How can i combine jquery and java like this ? Should i use the "remote" command from jquery or combine validation with another function ?
If name already exists n database i don't want my form to submit.
Signup.xhtml
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>TODO supply a title</title>
<link rel="stylesheet" type="text/css" href="newcss.css" />
<link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.no-icons.min.css" rel="stylesheet"></link>
<script src="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/js/bootstrap.min.js"></script>
<script src="jquery.js" type="text/javascript"></script>
<script src="//code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.14.0/jquery.validate.js" type="text/javascript"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.14.0/jquery.validate.min.js" type="text/javascript"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.14.0/additional-methods.min.js" type="text/javascript"></script>
<script src="validate.js" type="text/javascript"></script>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
</head>
<body>
<div id="container" align="center">
<h2>User Registration</h2>
<form action="welcome.xhtml" method="post" id="contact_form">
<div>
<label for="name">Name</label>
<input id="name" type="text" name="name"/>
<span id="nameInfo"></span>
</div>
<div >
<label for="email" >Email</label>
<input id="email" type="text" name="email"/>
<span id="emailInfo"></span>
</div>
<div>
<label for="password">password</label>
<input id="password" type="password" name="pass1"/>
<span id="pass1Info"></span>
</div>
<div>
<label for="confirm">confirm password</label>
<input id="confirm" type="password" name="pass2"/>
<span id="pass2Info"></span>
</div>
<div>
<label for="message">Message</label>
<textarea id="message" name="message"/>
<span id="messageInfo"></span>
</div>
<div>
<input id="send" name="send" type="submit" value="Send"/>
</div>
<br/>
<!-- <p>Already registered? Sign in.</p> -->
</form>
</div>
</body>
</html>
validate.js
$(document).ready(function () {
//Validation rules for form
$("#contact_form").validate({
// Specify the validation rules
rules: {
name: {
required: true
// remote: ???
},
password: {
required: true,
minlength: 5
},
confirm: {
required: true,
equalto: "#password"
},
email: {
required: true,
email: true
}
},
// Specify the validation error messages
messages: {
name: "Please enter your name",
password: {
required: "Please provide a password",
minlength: "Your password must be at least 5 characters long"
},
confirm:{
equalto: "Passwords are not matching"
},
email: "Please enter a valid email address"
},
submitHandler: function (form) {
form.submit();
}
});
});
CheckAvailability.java (I inserted as js, cause it would not retain its format)
package Beans;
import java.io.*;
import java.sql.*;
import javax.servlet.ServletException;
import javax.servlet.http.*;
public class CheckAvailability extends HttpServlet {
private static final long serialVersionUID = -734503860925086969L;
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
String connectionURL = "jdbc:mysql://localhost:3306/teddb"; // teddb is my database name
Connection connection;
Class.forName("com.mysql.jdbc.Driver").newInstance();
connection = DriverManager.getConnection(connectionURL, "root", "Sk1994!!");
String uname = request.getParameter("name");
PreparedStatement ps = connection.prepareStatement("select username from users where username=?");
ps.setString(1,uname);
ResultSet rs = ps.executeQuery();
if (!rs.next()) {
out.println("");
}
else{
out.println("Username already in use");
}
out.println();
}
catch (ClassNotFoundException | InstantiationException | IllegalAccessException | SQLException ex) {
out.println("Error ->" + ex.getMessage());
} finally {
out.close();
}
}
}

Set a request attribute depending on the link clicked

I would like to determine which link is being click, and set a request attribute accordingly; to be processed in the controller. The controller is generic. It will dispatch to another page according to the attribute set in the JSP. How can I achieve this?
EDIT:
I have followed the BalusC's advice where
Register
Login
RandomController :
#WebServlet(name = "RandomController", urlPatterns = {"/RandomController/*"})
public class RandomController extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
int theRandom = 0;
Random myRandom = new Random();
RequestDispatcher dispatcher = null;
String pathInfo = request.getPathInfo();
String contextPath = request.getContextPath();
String dispatchesPath = contextPath + pathInfo;
System.out.println(pathInfo);
System.out.println(contextPath);
System.out.println(dispatchesPath);
theRandom = myRandom.nextInt(MAX_RANDOM);
request.setAttribute("random", theRandom);
if(pathInfo.equals("/Login")) {
dispatcher = request.getRequestDispatcher("Login.jsp");
dispatcher.forward(request, response);
}
else {
dispatcher = request.getRequestDispatcher("Register.jsp");
dispatcher.forward(request, response);
}
}
}
I have tried this approach but the Exception about maximum depth for nested request dispatchers : 20 is throw.
The generic controller is RandomController which servers two produces random number and set as attribute in request object and sent it to login or register page.
Login.jsp :
<%--
Document : Register
Created on : May 28, 2011, 5:49:35 PM
Author : nicholas_tse
--%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Online Store Register Page</title>
<link rel="stylesheet" href="style.css" type="text/css" media="screen" />
</head>
<body>
<jsp:useBean id="randomBean" class="Helper.RandomInt"
scope="request">
</jsp:useBean>
<h1>Online Store</h1>
<p></p>
<div align="right">
<h3>
<c:if test="${not empty sessionScope.username}">
! Welcome ${sessionScope["username"]} !
<form action="LogoutController" method="POST">
<input type="submit" name="submit" value="Logout"/>
</form>
</c:if>
</h3>
</div>
<ul id="nav_list">
<li>Home</li>
<li>Product</li>
<li>Add Stock</li>
<li>Shopping Cart</li>
<li>Order Status</li>
<li>Register</li>
<li>Login</li>
</ul>
<br></br>
<p></p>
<c:if test="${!not empty sessionScope.username}">
<div id="registerForm" align="center"
style="border:1px solid black; width:760px" >
<form name="RegisterForm" action="RegisterController"
method="POST">
<p>
Username : <input type="text" id="username" name="username">
<c:if test="${message.msg} != null" >
${message.msg}
</c:if>
</p>
<p>
Password : <input type="password" id="password" name="password"
</p>
<p>
Name : <input type="text" id="name" name="name">
<c:if test="${message.msg} != null" >
${message.msg}
</c:if>
</p>
<p>
Address : <input type="text" id="address" name="address">
<c:if test="${message.msg} != null" >
${message.msg}
</c:if>
</p>
<p>
State :
<select>
<option>Selangor</option>
<option>Kuala Lumpur</option>
<option>Cyberjaya</option>
<option>Putrajaya</option>
</select>
</p>
<p></p>
<input type="submit" name="submit" value="Register">
<input type="reset" name="clear" value="Clear">
<p></p>
</form>
</div>
</c:if>
</body>
</html>
Without further info the only suggestion I can think of is to add a querystring to your URLs. Like this:
Page 1
This way you can look at the actiuon parameter in the request to determine what to do in your controller.
You can add a request parameter. This can be done in 2 ways depending on whether your form has a method of POST or GET.
You have implemented the submit buttons in the forms with a name attribute of submit and different value attributes. This should mean that the requests will include a submit parameter in the query string or the POST form data. On the server side, you can use this to figure out which of the submit buttons was clicked.

Categories