I want to automatically increase table row after clicking button - java

Hi, my problem is increasing the table row automatically. Actually, when I click GET button the product type and product name values are getting from database. Here, after getting those values, I will give another id based on that id again for values will come. But it was not setting in another row. Here is my java code and jsp:
Class.forName("com.mysql.jdbc.Driver");
System.out.println("driver loaded");
System.out.println("Driver is loaded");
Connection con= (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/charms?user=root&password=root");
System.out.println("Connection created");
Statement st =con.createStatement();
String query="select * from product where ProductType_v='"+a+"' and ProductId_v='"+b+"'";
ResultSet rs = (ResultSet)st.executeQuery(query);
int i=0;
while(rs.next())
{
i++;
request.getSession().setAttribute("edit","success");
request.getSession().setAttribute("proType ", rs.getString("ProductType_v"));
request.getSession().setAttribute("proId", rs.getString("ProductId_v"));
request.getSession().setAttribute("strength", rs.getString("Strength_v"));
request.getSession().setAttribute("proName", rs.getString("ProductName_v"));
request.getSession().setAttribute("brand", rs.getString("BrandName_v"));
request.getSession().setAttribute("generic", rs.getString("GenricName_v"));
request.getSession().setAttribute("uom", rs.getString("UOM_v"));
request.getSession().setAttribute("formE", rs.getString("FormE_v"));
request.getSession().setAttribute("presReqd", rs.getString("PresReqd_v"));
}
if(i==0)
{
request.getSession().setAttribute("edit", "fail");
}
}
catch(Exception e)
jsp code
<tr>
<td>
<input class="textfield-form-date-req" type="text" id="pro_type">
</td>
<%
if(editStatus =="success")
{
%>
<script type="text/javascript">
document.getElementById("pro_type").value='<%=session.getAttribute("proType")%>';
</script>
<%
}
<td>
<input class="textfield-form-date-req" type="text" id="pro_id">
</td>
<%
if(editStatus =="success")
{
%>
<scripttype="text/javascript">
document.getElementById("pro_id").value='<%=session.getAttribute("proName")%>';
</script>
<%
}
%>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>

I have created a sample for you with ajax. It gets the data from the server side and append it , in the existing table.
The jar files I have used is ,
jackson-all-1.9.0.jar - to convert the java object to json format
servlet-api-2.4.jar - for servlet
My TableAppend.jsp will be,
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script
src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script type="text/javascript">
$(document).ready(function() {
//alert("DOM is ready");
});
function sendData() {
$.ajax({
type : 'POST',
url : "TableAppend",
data : "name=" + $('#name').val() + "&age=" + $('#age').val()
+ "&sid=" + new Date(),
dataType : 'html',
success : function(result) {
//alert("Result ::::>>> "+result);
if(result != null && $.trim(result) != "" && result != undefined){
var json = JSON.parse(result);
//alert(json.name);
//alert(json.age);
appendToTable(json.name, json.age);
}
},
error : function(e) {
alert('Error in Processing');
}
});
}
function appendToTable(name, age) {
var tr = "<tr><td>" + name + "</td><td>" + age + "</td></tr>"
$('#mytable').append(tr);
}
</script>
</head>
<body>
Name :
<input type="text" id="name" name="name" /> Age :
<input type="text" id="age" name="age" />
<input type="button" value="Append to table" onclick="sendData()">
<br></br>
<br></br>
<br></br>
<table id="mytable" border="1">
<tbody>
<tr>
<th>Name</th>
<th>Age</th>
</tr>
<tr>
<td>HumanBeing</td>
<td>25</td>
</tr>
<tr>
<td>Saideep</td>
<td>26</td>
</tr>
</tbody>
</table>
</body>
</html>
My TableAppend.java servlet will be,
public class TableAppend extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* Default constructor.
*/
public TableAppend() {
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setCharacterEncoding("UTF-8");
response.setContentType("UTF");
PrintWriter out = response.getWriter();
request.setCharacterEncoding("UTF-8");
String name = request.getParameter("name");
String age = request.getParameter("age");
String json ="";
System.out.println("-----------------");
if(name != null && age != null){
TableAppendPojo obj = new TableAppendPojo();
obj.setName(name);
obj.setAge(age);
ObjectMapper mapper = new ObjectMapper();
json = mapper.writeValueAsString(obj);
System.out.println("json : "+json);
}
out.println(json);
}
}
Then java class will be,
public class TableAppendPojo {
private String name;
private String age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
}
Note : Please apply the above logic in your code . In your case , you don't need to give the data from the UI. You retrieves the data from the database in the servlet.So please convert the retrieved data from the database to the json format and append it to the table.
Hope this helps.

Related

Restart Servlet after form submit

I'm fairly new to using servlets with JSP and I am having trouble trying to redirect back to the start of the servlet home page JSP after submitting my form jsp and I'm not sure how to accomplish this task or whether it's even possible to do that, the methods i try have at best returned the home page jsp but without the servlet default function called to fetch the data from jdbc. i've tried sendredirect() and request dispatcher to no avail and any help to where i'm going wrong would be appreciated.
i have one single servlet code for handling all operations including the insert and update which are giving problems in redirecting/reloading
public class StudentServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private StudentDao studentDao;
public StudentServlet() {
this.studentDao = new StudentDao();
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String sPath = request.getServletPath();
//switch statement to call appropriate method
switch (sPath) {
case "/new":
try {
showNewForm(request, response);
} catch (ServletException | IOException e) {
e.printStackTrace();
}
break;
case "/insert":
try {
insertStudent(request, response);
} catch (SQLException | IOException e) {
e.printStackTrace();
}
break;
case "/delete":
try {
deleteStudent(request, response);
} catch (SQLException | IOException e) {
e.printStackTrace();
}
break;
case "/update":
try {
updateStudent(request, response);
} catch (SQLException | IOException e) {
e.printStackTrace();
}
break;
case "/edit":
try {
editStudent(request, response);
} catch (ServletException | IOException e) {
e.printStackTrace();
}
break;
case "/StudentServlet":
try {
listAllStudents(request, response);
} catch (ServletException | IOException | SQLException e) {
e.printStackTrace();
}
break;
default:
try {
listAllStudents(request, response); //home page = .../week04/StudentServlet
} catch (ServletException | IOException | SQLException e) {
e.printStackTrace();
}
break;
}
}
// functions to fetch data from studentDao and display data on appropriate jsp
private void listAllStudents(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException, SQLException {
List<Student> allStudents = studentDao.selectAllStudents();
request.setAttribute("listStudents", allStudents);
RequestDispatcher dispatch = request.getRequestDispatcher("student-list.jsp");
dispatch.forward(request, response);
}
private void showNewForm(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
RequestDispatcher dispatch = request.getRequestDispatcher("student-form.jsp");
dispatch.forward(request, response);
}
private void insertStudent(HttpServletRequest request, HttpServletResponse response)
throws SQLException, IOException{
String firstname = request.getParameter("firstname");
String lastname = request.getParameter("lastname");
String email = request.getParameter("email");
Student newStudent = new Student(firstname, lastname, email);
studentDao.insertStudent(newStudent); //student object inserted to table
response.sendRedirect("/StudentServlet"); //redirect to home page
}
private void deleteStudent(HttpServletRequest request, HttpServletResponse response)
throws SQLException, IOException {
int id = Integer.parseInt(request.getParameter("id"));
studentDao.deleteStudent(id); //student object deleted
response.sendRedirect("/StudentServlet");
}
private void updateStudent(HttpServletRequest request, HttpServletResponse response)
throws SQLException, IOException{
String sId = request.getParameter("id");
int id = Integer.parseInt(sId);
String firstname = request.getParameter("firstname");
String lastname = request.getParameter("lastname");
String email = request.getParameter("email");
Student updateStudent = new Student(id, firstname, lastname, email);
studentDao.updateStudent(updateStudent); //student object updated
response.sendRedirect("/StudentServlet");
}
private void editStudent(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
int id = Integer.parseInt(request.getParameter("id"));
Student currentStudent = studentDao.selectStudent(id);
RequestDispatcher dispatch = request.getRequestDispatcher("student-form.jsp"); //student form called with current student info loaded
request.setAttribute("student", currentStudent);
dispatch.forward(request, response);
}
}
here is my xml file:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:web="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd http://java.sun.com/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee" id="WebApp_ID" version="2.4">
<servlet>
<servlet-name>StudentServlet</servlet-name>
<servlet-class>week04.web.StudentServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>StudentServlet</servlet-name>
<url-pattern>/</url-pattern>
<url-pattern>/StudentServlet</url-pattern>
<url-pattern>/new</url-pattern>
<url-pattern>/update</url-pattern>
<url-pattern>/insert</url-pattern>
<url-pattern>/delete</url-pattern>
<url-pattern>/edit</url-pattern>
</servlet-mapping>
</web-app>
here is my home page JSP i named it student-list.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1" import="java.util.*" import="week04.model.Student"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, intial-scale=1 shink-to-fit=yes">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/css/bootstrap.min.css"
integrity="sha38-...." crossorigin="anonymous">
</head>
<body>
<nav class="navbar navbar-dark bg-primary pd-8">
<a class="navbar-brand"> XYZ University</a>
</nav>
<div class="container-fluid">
<div class="container">
<div class="form container-fluid p-4">
<a href="<%=request.getContextPath()%>/new" class="btn btn-success" >Add
Student</a>
</div>
<br>
<!--Assigning ArrayList object containing student data to the local object -->
<% ArrayList<Student> studentList = (ArrayList) request.getAttribute("listStudents"); %>
<table class="table table-bordered">
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Email</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<%
if(request.getAttribute("listStudents") != null) {
Iterator<Student> iterator = studentList.iterator();
while(iterator.hasNext()) {
Student studentDetails = iterator.next();
%>
<tr><td><%=studentDetails.getFirstname()%></td>
<td><%=studentDetails.getLastname()%></td>
<td><%=studentDetails.getEmail()%></td>
<td>Update
Delete</td>
</tr>
<%
}
}
%>
</tbody>
</table>
</div>
</div>
</body>
</html>
and here is my form file that handles inserting and updating data:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, intial-scale=1 shink-to-fit=yes">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/css/bootstrap.min.css"
integrity="sha384-...">
</head>
<body>
<nav class="navbar navbar-dark bg-primary pd-8">
<a class="navbar-brand"> XYZ University</a>
</nav>
<div class="container col-md-5 p-4">
<div class="card">
<div class="card-body">
<% System.out.println(request.getAttribute("student") + "hello"); %>
<% if (request.getAttribute("listStudents") != null || request.getAttribute("student") != null) { %>
<form action="<%=request.getContextPath()%>/update" method="post">
<% } else { %>
<form action="<%=request.getContextPath()%>/insert" method="post">
<% } %>
<div>
<h2>
<% if (request.getAttribute("student") != null) { %>
Edit Student
<% } else { %>
Add New Student
<% } %>
</h2>
</div>
<% if (request.getAttribute("student") != null) { %>
<input type="hidden" name="id" value="${student.id}" />
<% } %>
<fieldset class="form-group">
<legend> First Name</legend>
<% if (request.getAttribute("student") != null) { %>
<input type="text" value="${student.firstname}" class="form-control"
name="fistname" required="required">
<% } else { %>
<input type="text" value="" class="form-control" name="firstname" required="required">
<% } %>
</fieldset>
<fieldset class="form-group">
<legend>Last Name</legend>
<% if (request.getAttribute("student") != null) { %>
<input type="text" value="${student.lastname}" class="form-control"
name="lastname" required="required">
<% } else { %>
<input type="text" value="" class="form-control" name="lastname" required="required">
<% } %>
</fieldset>
<fieldset class="form-group">
<legend>Email</legend>
<% if (request.getAttribute("student") != null) { %>
<input type="text" value="${student.email}" class="form-control" name="email">
<% } else { %>
<input type="text" value="" class="form-control" name="email">
<% } %>
</fieldset>
<button type="submit" class="t-3 btn btn-success">Save</button>
</form>
</div>
</div>
</div>
</body>
</html>
Any help would be appreciated, i dont know if i'm going wrong with my servlet configuration, xml or my form page configuration.
You're receiving the exception
SQLIntergrityConstraintViolation: column firstname cannot be null
because you have a small typo in your first name form group.
<% if (request.getAttribute("student") != null) { %>
<input type="text" value="${student.firstname}" class="form-control"
name="fistname" required="required">
<% } else { %>
<input type="text" value="" class="form-control" name="firstname" required="required">
<% } %>
In the if block, the <input> text field's name="fistname" has been misspelled, while the name="firstname" is correct in the else block.
This is why your insert works with if-else only as it goes through the else block which has the correct field name. Once you fix this typo, the insert should start working without the if-else too as prescribed before.

Java Hibernate application using mySQL- Login page does not work

I am working on a hibernate project using apache.tomcat in netbeans in which I am creating an application with a user login (employee ID and password) that allows baseball field employees (from mysql database) to request passes to use the field. Users should be able to 1) choose an event for reservation (date & time) from a drop down menu, 2) input their group size, group name, and employee department(drop-down) and 3) manage the reservations on file specific to their employee ID.
I can access the login screen, but nothing happens when I enter employee credentials. I am not sent to the memberscreen.jsp upon entering a correct login, and I do not get the errors I set up for invalid logins. I have been at this for hours and I can not seem to find where I went wrong.
Note: The project requires that I use hibernate
I have tried googling ways to fix this but I have come up short, I think my problem may be too specific. I am getting no errors and the build is successful, but not functional.
logonservlet.java
package servlets;
import business.Employee;
import business.EmployeeDB;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class LogonServlet extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
String msg = "", empid = "";
long pattempt;
String URL = "/Logon.jsp";
Employee e;
try {
empid = request.getParameter("empid").trim();
e = EmployeeDB.getEmployee(empid);
if (e == null) {
msg = "No member record found<br>";
} else {
pattempt = Long.parseLong(request.getParameter("password"));
e.setPassattempt((int) pattempt);
if (!e.isAuthenticated()) {
msg = "Member found but not authenticated<br>";
} else {
msg = "member authenticated<br>";
URL = "/MemberScreen.jsp";
}
request.getSession().setAttribute("e", e);
}
} catch (Exception x) {
msg = "Servlet exception: " + x.getMessage();
}
request.setAttribute("msg", msg);
RequestDispatcher disp =
getServletContext().getRequestDispatcher(URL);
disp.forward(request,response);
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods.
Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* #return a String containing servlet description
*/
#Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
Logon.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html >
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Field Pass</title>
</head>
<body>
<h1>Welcome</h1>
<p>Please Enter your id and password:</p>
<form action="Logon" method="post">
<table>
<tr>
<td>User ID:</td>
<td><input type="text" name="userid" id="userid"
value="${empty user.userID ? cookie.memid.value : user.userID }" />
</td>
</tr>
<tr>
<td>Password:</td>
<td><input type="password" name="password" id="password">
</td>
</tr>
</table>
<br>
<input type="submit" value="Log in">
</form>
<br>
</body>
</html>
employee.java
package business;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.Transient;
import org.hibernate.annotations.NamedQuery;
#Entity
#Table(name="Employee")
#NamedQuery(name="dbget_Employee", query="from EMPLOYEE where EMP_ID = :EMP_ID")
public class Employee {
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
#Id
#Column(name="EMP_ID")
private int emp_id;
#Column(name="LAST_NAME")
private String last_name;
#Column(name="FIRST_NAME")
private String first_name;
#Column(name="MIDDLE_INITIAL")
private String middle_initial;
#Column(name="HIRE_DATE")
#Temporal(javax.persistence.TemporalType.DATE)
private Date hire_date;
#Column(name="DEPT_ID")
private int dept_id;
#Column(name="PASSWORD")
private int password;
#Column(name="ADMIN")
private String admin;
#Transient
private int passattempt;
#Transient
private String msg;
public Employee() {
emp_id = 0;
last_name= "";
first_name = "";
middle_initial = "";
hire_date = null;
dept_id = 0;
password = 0;
admin = "";
}
public int getEmp_id() {
return emp_id;
}
public void setEmp_id(int emp_id) {
this.emp_id = emp_id;
}
public String getLast_name() {
return last_name;
}
public void setLast_name(String last_name) {
this.last_name = last_name;
}
public String getFirst_name() {
return first_name;
}
public void setFirst_name(String first_name) {
this.first_name = first_name;
}
public String getMiddle_initial() {
return middle_initial;
}
public void setMiddle_initial(String middle_initial) {
this.middle_initial = middle_initial;
}
public Date getHire_date() {
return hire_date;
}
public void setHire_date(Date hire_date) {
this.hire_date = hire_date;
}
public int getDept_id() {
return dept_id;
}
public void setDept_id(int dept_id) {
this.dept_id = dept_id;
}
public int getPassword() {
return password;
}
public void setPassword(int password) {
this.password = password;
}
public String getAdmin() {
return admin;
}
public void setAdmin(String admin) {
this.admin = admin;
}
public int getPassattempt() {
return passattempt;
}
public void setPassattempt(int passattempt) {
this.passattempt = passattempt;
}
public boolean isAuthenticated() {
if (this.password > 0) {
if (this.password == this.getPassattempt()) {
return true;
} else {
setMsg("Member not authenticated");
}
}
return false;
}
}
employeeDB.java
package business;
import javax.persistence.NoResultException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
/**
*
* #author noah
*/
public class EmployeeDB {
public static Employee getEmployee(int emp_id) {
SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
Session session = null;
Employee e = null;
try {
String qS ="from Employee e where e.emp_id = :emp_id";
session = sessionFactory.openSession();
Query q = session.createQuery(qS);
q.setParameter("emp_id", emp_id);
e = (Employee)q.uniqueResult();
} catch (NoResultException ex) {
return null;
} finally {
session.close();
}
return e;
}
public static Employee getEmployee(String empid) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of
generated methods, choose Tools | Templates.
}
}
memberScreen.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Member Welcome</title>
<style>
table.member-details{
border-collapse: collapse;
}
table.member-details td, table.member-details th{
padding: 6px;
border: 1px solid #999;
}
</style>
</head>
<c:if test="${!e.authenticated}">
<script type="text/javascript">
window.location = "/ClubDB";
</script>
</c:if>
<c:if test="${e.authenticated}">
<body>
<h1>Club member Data</h1>
<form id="memupdate" action="MemberUpdate" method="post">
<table class="member-details">
<tr>uu
<td>Member ID:</td>
<td><input type="text" id="memid" name="memid"
value="${e.empid}" readonly="true"></td>
</tr>
<tr>
<td>Last Name:</td>
<td><input type="text" id="lastname" name="lastname"
value="${e.lastname}" ></td>
</tr>
<tr>
<td>First Name:</td>
<td><input type="text" id="firstname" name="firstname"
value="${e.firstname}" ></td>
</tr>
<tr>
<td>Middle Nm:</td>
<td><input type="text" id="middlename" name="middlename"
value="${e.middlename}" ></td>
</tr>
<tr>
<td>Status:</td>
<td><input type="text" id="status" name="status"
value="${m.status}" readonly="true" ></td>
<tr>
<tr>
<td>Member Date:</td>
<td><input type="text" id="memdt" name="memdt"
value="${m.memdtS}" readonly="true" ></td>
</tr>
<tr>
<td>Password:</td>
<td><input type="password" id="psswd" name="psswd"
value="${m.password}" size="22"></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Update Member data"></td>
</tr>
</table>
</form>
<br>
${msg}
<hr>
<br>View Transaction History From:<br>
<form action="ShowPurchases" method="post" >
<table>
<tr>
<td>Month:</td><td><input type="text" name="month"
id="month" value=""></td>
<td>Day:</td><td><input type="text" name="day"
id="day" value=""></td>
<td>Year:</td><td><input type="text" name="year"
id="year" value=""></td>
</tr>
</table><br>
<input type="submit" value="View Transactions">
</form> <br>
<br><br>
Back to the Login Screen
</body>
</c:if>
</html>
hibernate xml file
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-
iiapp_3_1.xsd">
<servlet>
<servlet-name>LogonServlet</servlet-name>
<servlet-class>servlets.LogonServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LogonServlet</servlet-name>
<url-pattern>/Logon</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>Logon.jsp</welcome-file>
</welcome-file-list>

request.getParameter returns null in JSP

Form.jsp
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Form</title>
<body bgcolor="#FFFFFF" text="#000000">
<h1>Please enter your details</h1>
<form name="RegistrationForm" action="NewUser" method="post">
<table cellspacing="5" cellpadding="5" border="1">
<tr>
<td align="right">First Name:</td>
<td><input type="text" name="NewFirstName"></td>
</tr>
<tr>
<td align="right">Last Name:</td>
<td><input type="text" name="NewLastName"></td>
</tr>
<tr>
<td align="right">Email Address:</td>
<td><input type="text" name="EmailAddress"></td>
</tr>
<tr>
<td align="right">Phone Number:</td>
<td><input type="text" name="Phone Number"></td>
</tr>
<tr>
<td align="right">Semester</td>
<td><input type="text" name="Semester"></td>
</tr>
</table>
<input type="submit" value="Submit">
</form>
</body>
</html>
NewUser.java(Servlet Class)
package com.seria.quiz;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class NewUser
*/
#WebServlet("/NewUser")
public class NewUser extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public NewUser() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
Connection conn = null;
try {
String FirstName = request.getParameter("firstName");
System.out.println("Your firstname: " + FirstName);
String LastName = request.getParameter("lastName");
System.out.println("Your LastName: " + LastName);
String Emailid = request.getParameter("email");
String PhoneNumber = request.getParameter("phoneNumber");
String Semester = request.getParameter("semester");
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/seriaquiz", "root", "root");
PreparedStatement pst = (PreparedStatement) conn
.prepareStatement("insert into formdetails(firstName,lastName,email,phoneNumber,semester) values(?,?,?,?,?)");// try2
// the
// name
pst.setString(1, FirstName);
System.out.println("Your firstname1: " + FirstName);
pst.setString(2, LastName);
System.out.println("Your LastName1: " + LastName);
pst.setString(3, Emailid);
pst.setString(4, PhoneNumber);
pst.setString(5, Semester);
int i = pst.executeUpdate();
String msg = " ";
if (i != 0) {
msg = "Record has been inserted";
pw.println("<font size='6' color=blue>" + msg + "</font>");
} else {
msg = "failed to insert the data";
pw.println("<font size='6' color=blue>" + msg + "</font>");
}
pst.close();
} catch (Exception e) {
pw.println(e);
}
}
}
As the title says request.getParameter is returning null every time. I put sysout statements after requestParameter, and it shows null value. Any help will be appreciated. Sorry for any inconvenience, I'm new here.
The parameter names in servlet need to match them in the JSP
so
String FirstName = request.getParameter("firstName");
should be
String FirstName = request.getParameter("NewFirstName");
you are asking for wrong parameters
you should always ask for same id/name as described in your html
request.getParameter("NewFirstName");
From w3.org section 17.2 Controls
Users interact with forms through named controls.
A control's "control name" is given by its name attribute. The scope of the name attribute for a
control within a FORM element is the FORM element.
When a form is submitted for processing, some controls have their name paired with their current
value and these pairs are submitted with the form.
Example of control is your
<input type="text" name="NewFirstName">
So when the form gets submitted, it contains a control name=value e.g.
NewFirstName=YourFirstName
In your JSP, you should do access it using the the control name
String FirstName = request.getParameter("NewFirstName");
Reference: http://www.w3.org/TR/html401/interact/forms.html
Get the exact value of a form parameter try this....
String FirstName = request.getParameter("NewFirstName");
because ..
you specify name attribute by 'NewFirstName'...

Re-ordering form results with Java/JSP

I'm inexperienced with Java and JSP. I created a form and it works the way it is supposed to, but I want to have some fun with it and have it reorder the results after the form is submitted. I'll include some images to show what I mean. I'm having a hard time searching for what I want and don't really know where to start. Any help will be appreciated.
Here is the form page:
Here is the results:
Here is what I want the results to look like (notice 'last' goes from 2 to 3, 'middle' from 3 to 5, 'item' from 4 to 2, and 'address' from 5 to 4):
Java File
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
public class ShowParameters extends HttpServlet {
private static final long serialVersionUID = 1L;
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String docType =
"<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 " +
"Transitional//EN\">\n";
String title = "Reading All Request Parameters";
out.println(docType +
"<HTML>\n" +
"<HEAD><TITLE>" + title + "</TITLE></HEAD>\n" +
"<BODY BGCOLOR=\"#FDF5E6\">\n" +
"<H1 ALIGN=CENTER>" + title + "</H1>\n" +
"<TABLE BORDER=1 ALIGN=CENTER>\n" +
"<TR BGCOLOR=\"#FFAD00\">\n" +
"<TH>Parameter Name<TH>Parameter Value(s)");
Enumeration paramNames = request.getParameterNames();
while(paramNames.hasMoreElements()) {
String paramName = (String)paramNames.nextElement();
out.print("<TR><TD>" + paramName + "\n<TD>");
String[] paramValues =
request.getParameterValues(paramName);
if (paramValues.length == 1) {
String paramValue = paramValues[0];
if (paramValue.length() == 0)
out.println("<I>No Value</I>");
else
out.println(paramValue);
} else {
out.println("<UL>");
for(int i=0; i<paramValues.length; i++) {
out.println("<LI>" + paramValues[i]);
}
out.println("</UL>");
}
}
out.println("</TABLE>\n</BODY></HTML>");
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("STOP1\n");
doGet(request, response);
}
}
JSP file
<%# 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>Lab 3</title>
<style type="text/css">
.address {
height: 50px;
}
</style>
</head>
<body>
<body BGCOLOR="#FF0000">
<h1 align="center">Basic FORM</h1>
<form action="ShowParameters" method="post">
First Name: <input type="text" name="first"> <br>
Last Name: <input type="text" name="last" value="$"> <hr/>
Middle Name: <input type="text" name="middle"> <br>
Item: <input type="text" name="item"> <br>
Address: <input type="text" name="address" class="address"> <br>
Credit Card: <br>
<input type="radio" name="cardType" value="Visa">Visa <br>
<input type="radio" name="cardType" value="MasterCard">MasterCard <br>
Credit Card Number: <input type="text" name="cardNum"> <br><br>
<center><input type="submit" value="Submit Order"></center>
</form>
</body>
</html>
instead of creating html in servlet create a class to hold form input information like:
public class Person {
private String firstName;
private String midlleName;
private String lastName;
private String item;
private String address;
private String cardType;
private String cardNumber;
//getters and setters
}
in servlet create instance of Person class and set values then simply add person instance to request and forward to jsp.
Person person = new Person();
person.setFirstName(request.getParameter("first"));
//set other person values here
request.setAttribute("person", person);
request.getRequestDispatcher("filename.jsp").forward(request, response);
in jsp display like:
<table border="2">
<tr bgcolor="#FFAD00">
<th>Parameter Name</th>
<th>Parameter Value(s)</th>
</tr>
<tr>
<td>first</td><td>${person.firstName}</td>
</tr>
<tr>
<td>item</td><td>${person.item}</td>
</tr>
<tr>
<td>last</td><td>${person.midlleName}</td>
</tr>
<tr>
<td>address</td><td>${person.address}</td>
</tr>
<tr>
<td>middle</td><td>${person.lastName}</td>
</tr>
<tr>
<td>cardType</td><td>${person.cardType}</td>
</tr>
<tr>
<td>cardNum</td><td>${person.cardNumber}</td>
</tr>
</table>
Benefits:
easy to change the order as you like in html.(simply move the <tr/> elements)
No need of loop.
Follows Object-oriented programming (OOP) style of programming.
Rather than getting an enumeration of the parameters by request.getParameterNames you could have a string array of all the parameter names you expect with them in the order you want, and you could loop through that array like so:
String[] paramNames = { "item", "last", "first" };
for(int i=0; i<paramNames.length; i++)
{
out.print("<tr>");
out.print("<td>" + paramNames[i] + "</td>");
out.print("<td>");
String[] paramValues = request.getParameterValues(paramNames[i]);
...
...
out.print("</td>");
out.print("</tr>");
}
Please take note that one of the things you are not doing in your code is properly closing the cells with </td> and the rows with </tr>. You should really also close the LIs with </li>.

How to implement username availability using JSP

In my application I have a username with a textbox, a checkbutton and a password. After entering the username into the textbox, if I click on check button it should search in the MySQL database for the username, if it is available it should display the message if not an other message should be displayed.
How do I do that with JSP?
i tried the follwing code:
<form method="post" name="frm_addUser" action="./adduserserver.jsp"><br><br>
<table width="500px;" border="0" cellpadding="5" cellspacing="1" bgcolor="#f8f8ff" bordercolor="#333366" align="center">
<tr>
<td bordercolor="Gainsboro"><font size="4">User ID</font></td>
<td bordercolor="Gainsboro"><input name="userid" style="WIDTH: 200px"></td></tr>
<tr>
<td bordercolor="Gainsboro"><font size="4"> </font></td>
<!--<td><input value="Check availability" onclick="" class="btn_checkavail" type="button"></td></tr>-->
</td>
<td>
<input type="submit" value="check" name="check"
onclick="" /></td></tr>
<tr>
<td bordercolor="Gainsboro"><font size="4">Pass Word </font></td>
<td bordercolor="Gainsboro"><input name="password" type="password" style="WIDTH: 200px"></td></tr>
<tr>
<td bordercolor="Gainsboro"><font size="4">Confirm Password </font></td>
<td bordercolor="Gainsboro"><input name="confirmpassword" type="password" style="WIDTH: 200px"></td></tr>
<tr>
<%
try{
String username=request.getParameter("username");
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","sumith");
st=con.createStatement();
sqlQuery="select distinct username from usernameexist where username='"+username+"'";
rs=st.executeQuery(sqlQuery);
int count=0;
while(rs.next())
{
count++;
}
if(count>0)
{
out.println("<html>");
out.println("<head>");
out.println("<title>MeterDetailsPage</title>");
out.println("</head>");
out.println("<body>");
out.println("<table align='center' color='red'>");
out.println("<tr color='red'>");
out.println("<td ><font size=4 color=red >username Already Exist</font></td>");
out.println("</tr>");
out.println("</table>");
out.println("</body>");
out.println("</html>");
}
else
{
if(username!=null )
{
if(!username.equals(""))
{
//st.executeUpdate("insert into usernameexist(username) values('"+username+"')");
out.println("<html>");
out.println("<head>");
out.println("<title>username</title>");
out.println("</head>");
out.println("<body>");
out.println("<table align='center'>");
out.println("<tr>");
out.println("<td ><font size=4 color=green><b>available </b></font></td>");
out.println("</table>");
out.println("</body>");
out.println("</html>");
}
}
}
st.close();
con.close();
}
catch(Exception e){}
%>
</table>
</form>
</body>
</html>
Try This it will work,
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Index Page</title>
<script src="http://code.jquery.com/jquery-1.10.2.js" type="text/javascript"></script>
<script src="js/app-ajax.js" type="text/javascript"></script>
</head>
<body>
Enter Your Name: <input type="text" id="name" /><br>
Enter our user name :<input type="text" id="userName"><br>
Enter your Password :<input type="password" id="password"><br>
<input type="button" value="Submit" onclick="ajaxCall();">
<br>
<strong> Response</strong>:
<div id="ajaxGetUserServletResponse"></div><br>
</body>
</html>
Ajax file
function ajaxCall(){
var name = jQuery("#name").val();
var userName = jQuery("#userName").val();
var password= jQuery("#password").val();
alert(name);
alert(userName);
alert(password);
jQuery.ajax({
url : "GetUserServlet",
method: "GET",
type : "JSON",
data : "name="+name+"&userName="+userName+"&password="+password,// query parameters 1st
success : function(response){
$('#ajaxGetUserServletResponse').text(response);
}
});
}
Servlet
import java.io.IOException;
import java.util.ArrayList;
import javax.management.relation.RelationSupportMBean;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class GetUserServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
userBean ub = new userBean();
String name = request.getParameter("name").trim();
String userName = request.getParameter("userName").trim();
String password = request.getParameter("password").trim();
System.out.println("name catched "+name);
System.out.println("username catched"+userName);
System.out.println("Password catched"+password);
ArrayList<userBean> list = new ArrayList<userBean>();
ub=new userBean();
ub.setName(name);
ub.setUserName(userName);
ub.setPassword(password);
list.add(ub);
response.setContentType("text/plain");
response.getWriter().print(list);
}
}
Pojo Class
public class userBean
{
private String name;
private String userName;
private String password;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
My scenario was little bit different you can alter the code in index.jsp and add the call on button "Check Availability" and bring the response from servlet.
check your table name in query
select distinct username from usernameexist where username='"+username+"'";
make sure your table is usernameexist
and
String username=request.getParameter("username");
here parameter is userid not username
so use
String username=request.getParameter("userid");
Your should do below :
Make sure that your jsp is passing all fields including checked field to servlet. You can do form post which has all attributes.
Your servlet should read all parameters and if check-box is checked then you put appropriate logic in servlet (like querying your MySQL db)
Return proper response from your servlet so that jsp can show appropriate message. You can keep messages in your jsp/js and based on flag you can show appropriate message to user.
you can use as follows.. attach jquery file in source code
<script src="jquery-1.9.1.js">
IN Form
<input type="text" name="userName" id="userName" onBlur="checkId(this.value)">
<span id="status"></span>
<script type="text/javascript">
function checkId(member_id)
{
$.ajax({
type: "POST",
url: "processAjax.jsp", /* The request will be processed in this file.. */
beforeSend: function() {
$("#divIdStatus").html("geting name...");
},
data: "member_id=" + member_id ,
success: function(msg) {
$("#divIdStatus").html(msg);
}
});
}
IN processAjax.js
String member_id = (request.getParameter("member_id")).trim();
if (member_id.equals("")) {
out.print("! This is Required");
} else {
ResultSet result = // check in database if any record with this user name;
if (result.next()) {
out.print("! Not Available");
} else {
out.print("OK..");
}
}

Categories

Resources