This question already has answers here:
How should I use servlets and Ajax?
(7 answers)
Closed 4 years ago.
I have a CRUD table that lists a bunch of products, what I need is that when I click on a button, Ajax automatically sends a request to the servlet telling it that I want to change the state (instead of deleting the product) in the database, then after that is done it should reload the table.
I already have most of the code done, here is the AJAX that I had (Which I suppose is the part that is wrong), I was working on it trying to get it to work when I clicked on a row so ignore that part, there's a delete button per row).
<script>
$("#test").on('click','tr',function() {
var id = $(this).find("td:first-child").text();
console.log(id);
$.ajax({
url: "statecontroller.do",
type: 'POST',
data: { id : id},
success: function() {
}
});
});
</script>
And here is the servlet code:
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
int id = Integer.parseInt(request.getParameter("id"));
ProductDAO productBD = new ProductDAO();
Product products = productBD.selectById(id);
if(products.getState() == "Active"){
Product product = new Product(id,"Not Active");
productBD.update(product);
ArrayList<Product> productList = new ArrayList<>();
productList = productBD.selectAll();
request.getSession().setAttribute("productList", productList);
request.getRequestDispatcher("/wproduct/listing.jsp").forward(request, response);
}else if(products.getState() == "Not Active"){
Product product = new Product(id,"Active");
productBD.update(product);
ArrayList<Product> productList = new ArrayList<>();
productList = productBD.selectAll();
request.getSession().setAttribute("productList", productList);
request.getRequestDispatcher("/wproduct/listing.jsp").forward(request, response);
}
}
I tried looking it up but only found how to do this with Spring
(Here is the full servlet code, it has Spanish names on it which is why I translated it for the original post):
package controladores;
import daos.ClienteDAO;
import dtos.Cliente;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* #author lycan
*/
#WebServlet(name = "ControladorEstado", urlPatterns = {"/controladorestado.do"})
public class ControladorEstado extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
int id = Integer.parseInt(request.getParameter("id"));
ClienteDAO clientebd = new ClienteDAO();
Cliente clientes = clientebd.selectById(id);
if(clientes.getEstado() == "Activo"){
Cliente cliente = new Cliente(id,"No Activo");
clientebd.update(cliente);
ArrayList<Cliente> lista = new ArrayList<>();
lista = clientebd.selectAll();
request.getSession().setAttribute("lista", lista);
request.getRequestDispatcher("/wcliente/listar.jsp").forward(request, response);
}else if(clientes.getEstado() == "No Activo"){
Cliente cliente = new Cliente(id,"Activo");
clientebd.update(cliente);
ArrayList<Cliente> lista = new ArrayList<>();
lista = clientebd.selectAll();
request.getSession().setAttribute("lista", lista);
request.getRequestDispatcher("/wcliente/listar.jsp").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>
}
And here is the listing code:
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%--
Document : listar
Created on : 19-oct-2018, 11:00:29
Author : lycan
--%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<%#include file="../WEB-INF/jspf/estilos.jspf"%>
<title>Sistema Ventas</title>
</head>
<body>
<div class="container-fluid">
<%#include file="../WEB-INF/jspf/header.jspf"%>
<%#include file="../WEB-INF/jspf/nav.jspf"%>
<section>
<table id="test" class="table table-bordered">
<thead class="thead-dark">
<tr>
<th>ID</th>
<th>Nombre</th>
<th>Descripcion</th>
<th>Categoria</th>
<th>Estado</th>
<th><i class="fas fa-binoculars"></i></th>
<th><i class="fas fa-pen-alt"></i></th>
<th><i class="fas fa-user-times"></i></th>
</tr>
</thead>
<tbody>
<c:forEach var="clientes" items="${sessionScope.lista}">
<tr>
<td>${clientes.id}</td>
<td>${clientes.nombre}</td>
<td>${clientes.descripcion}</td>
<td>${clientes.categoria}</td>
<td>${clientes.estado}</td>
<td><a href="<%=request.getContextPath()%>/controladorcliente.do?operacion=detalle&id=${clientes.id}" class="btn btn-primary btn-lg " role="button" >Detalle</a></td>
<td><a href="<%=request.getContextPath()%>/controladorcliente.do?operacion=actualizar&id=${clientes.id}" class="btn btn-primary btn-lg " role="button" >Actualizar</a></td>
<td><a href="<%=request.getContextPath()%>/controladorcliente.do?operacion=eliminar&id=${clientes.id}" class="btn btn-primary btn-lg eliminar" role="button" >Eliminar</a></td>
</tr>
</c:forEach>
</tbody>
</table>
Registrar
Buscar
</section>
<%#include file="../WEB-INF/jspf/footer.jspf"%>
</div>
<%#include file="../WEB-INF/jspf/js.jspf"%>
<script>
$("#test").on('click','tr',function() {
var id = $(this).find("td:first-child").text();
console.log(id);
$.ajax({
url: "controladorestado.do",
type: 'POST',
data: { id : id},
success: function() {
}
});
// Locate HTML DOM element with ID "somediv" and set its text content with the response text.
});
</script>
</body>
</html>
okay i see what you are doing now, thanks for including more information. The reason why nothing happens is because in your servlet you are trying to return the same page you are making the ajax call from. (and you're not even handling the response)
From the looks of it, you want to return a table through the ajax method, but in order to do that you need to create a separate jsp that you will return.. For example:
create a new jsp called user-table inside /wcliente/
user-table.jsp
<?xml version="1.0" encoding="UTF-8"?>
<%#page contentType="application/xml" 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" %>
<data>
<table class="table table-bordered">
<thead class="thead-dark">
<tr>
<th>ID</th>
<th>Nombre</th>
<th>Descripcion</th>
<th>Categoria</th>
<th>Estado</th>
<th><i class="fas fa-binoculars"></i></th>
<th><i class="fas fa-pen-alt"></i></th>
<th><i class="fas fa-user-times"></i></th>
</tr>
</thead>
<tbody>
<c:forEach var="clientes" items="${lista}">
<tr>
<td>${clientes.id}</td>
<td>${clientes.nombre}</td>
<td>${clientes.descripcion}</td>
<td>${clientes.categoria}</td>
<td>${clientes.estado}</td>
<td><a href="<%=request.getContextPath()%>/controladorcliente.do?operacion=detalle&id=${clientes.id}" class="btn btn-primary btn-lg " role="button" >Detalle</a></td>
<td><a href="<%=request.getContextPath()%>/controladorcliente.do?operacion=actualizar&id=${clientes.id}" class="btn btn-primary btn-lg " role="button" >Actualizar</a></td>
<td><a href="<%=request.getContextPath()%>/controladorcliente.do?operacion=eliminar&id=${clientes.id}" class="btn btn-primary btn-lg eliminar" role="button" >Eliminar</a></td>
</tr>
</c:forEach>
</tbody>
</table>
</data>
Now in your servlet, instead of this:
request.getRequestDispatcher("/wcliente/listar.jsp").forward(request, response);
do this:
request.getRequestDispatcher("/wcliente/user-table.jsp").forward(request, response);
For the ajax in your listar.jsp do this instead:
<script>
$("#test").on('click','tr',function() {
var id = $(this).find("td:first-child").text();
$.post("controladorestado.do", {id : id}, function(responseXml) { // Execute Ajax POST request on URL of "controladorestado.do" and execute the following function with Ajax response XML...
$("#test").html($(responseXml).find("data").html()); // Parse XML, find <data> element and append its HTML to HTML DOM element with ID "test".
});
});
</script>
Reference:
How to use Servlets and Ajax?
Related
PersonalInfoOutput.java servlet is using the doPost method. The user logs in at index.html. From index.html, the request is sent to Login.java servlet.
From there, the user is directed to the PersonalInfoOutput.java servlet.
Now, consider another page called ChangePassAdmin.html. In this html code, one of these goes to PersonalInfoOutput.java. But when I click on it from that page,
I get HTTP Status 405 - HTTP method GET is not supported by this URL.
Can someone please help me as to how I should solve this problem?
I tried changing PersonalInfoOutput.java to doGet instead of doPost but then Login.java servlet will return HTTP Status 405 - HTTP method POST is not supported by this URL. So it seems I need both doGet and doPost for this PersonalInfoOutput.java servlet.
PersonalInfoOutput.java (servlet)
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
public class PersonalInfoOutput extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
HttpSession session = request.getSession(false);
String employeeid = "";
if(session != null) {
employeeid = (String)session.getAttribute("employeeid");
}
boolean st = false;
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/payroll_system", "root", "");
PreparedStatement ps = con.prepareStatement("select employeeID, FirstName, LastName, Admin, DOB, Address, Email, HourlyRate, Gender, ALeaveBalance, SLeaveBalance, ActiveStatus, Role, BSB, BankName, AccNumber, SuperNumber, SuperCompany from payroll_system.employee_info where employeeID = ?");
ps.setString(1, employeeid);
ResultSet rs = ps.executeQuery();
st = rs.next();
if(st){
etc... (rest of the code isn't relevant to question)
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<link rel = "stylesheet" type = "text/css" href = "main.css">
<title>Login</title>
</head>
<body>
<form action="Login" method="post">
<h1>
Login
</h1>
<b>Employee ID:</b> <br>
<input type="text"name="employee_id" size="20"><br><br>
<b>Password:</b><br>
<input type="password" name="password" size="20"><br><br>
<input type="submit" value="Login"><br><br>
</form>
</body>
</html>
Login.java (servlet)
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
public class Login extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String employee_id = request.getParameter("employee_id");
String password = request.getParameter("password");
HttpSession session = request.getSession();
session.setAttribute("employeeid", employee_id);
if(ValidateLogin.user(employee_id, password)) {
RequestDispatcher rs = request.getRequestDispatcher("PersonalInfoOutput");
rs.forward(request, response);
}
else
{
out.print("Employee ID or Password is incorrect. Please try again.");
RequestDispatcher rs = request.getRequestDispatcher("index.html");
rs.include(request, response);
}
}
}
ChangePassAdmin.html
<!DOCTYPE html>
<html>
<head>
<meta charset = "UTF-8">
<link rel = "stylesheet" type = "text/css" href = "main.css">
<link rel = "stylesheet" type = "text/css" href = "sidebar.css">
<title>Change Password</title>
<style>
table { border-collapse: collapse; width: 50%; } th, td { text-align: left; padding: 8px; } tr:nth-child(even){background-color: #f2f2f2}
tr:hover {background-color: #e2f4ff;}
</style>
</head>
<body>
<ul>
<li><a href=PersonalInfoOutput>View Personal Information</a></li>
<li><a href=PersonalInfoOutput>View Expense Claims</a></li>
<li><a href=PersonalInfoOutput>View Payslips</a></li>
<li><a class=active >Change Password</a></li>
<li><a href=PersonalInfoOutput>Maintain Employee Information</a></li>
<li><a href=PersonalInfoOutput>Maintain Tax Information</a></li>
<li><a href=PersonalInfoOutput>Maintain Payroll Items</a></li>
<li><a href=PersonalInfoOutput>Maintain Timesheet</a></li>
<li><a href=PersonalInfoOutput>Maintain Employee Expenses</a></li>
<li><a href=PersonalInfoOutput>Run Payroll</a></li>
<li><a href=PersonalInfoOutput>Generate Reports</a></li>
</ul>
<div style=margin-left:25%;padding:1px;>
</div>
<div id="container">
<h1>Change Password</h1>
<form action ="NewPassword" method = post>
<table border ="1">
<tr>
<td>Existing Password:</td>
<td><input type = "password" name = "oldpassword" size = "20"></td>
</tr>
<tr>
<td>New Password:</td>
<td><input type = "password" name = "newpassword" size = "20"></td>
</tr>
<tr>
<td>Confirm New Password</td>
<td><input type = "password" name = "confirmpassword" size = "20"></td>
</tr>
</table>
<br>
<br>
<input type = "submit" value = "Update Password">
</form>.
</div>
</body>
</html>
In ChangePassAdmin.html, double quotes around post are missing.
Both of your Servlet should have doPost method as your form is using "post" action.
<form action ="NewPassword" method = "post">
Additionally you will need two methods in this case. Add both doGet and doPost in your servlet. doPost will be used by form and doGet by links. By default all links are GET.
You can do it like:
Edit:
public class PersonalInfoOutput extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Your servlets code should be here
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
doPost() method to receive form based request. doGet() method to receive href based request. But in both cases processRequest() method will be called.
I believe the problem is that you're using the PersonalInfoOutput servlet in two ways:
Forwarding from Login servlet, which by forwarding keeps using POST method
And by href from the HTML, which by default uses method GET
Wouldn't a possible solution be for you to refactor your code, which would be good for you to do anyway, so that you implement both doGet() and doPost() in the PersonalInfoOutput servlet without repeating a lot of code?
Or you could refactor the employee database retrieval to an external class, that would be called from Login without the need to redirect from one servlet to another, and implement GET instead of POST in PersonalInfoOutput.
I use a html page with a textfield where you have to enter your name and then click on a login button.
On the same page is a list with all names.
Now I have to send the name by clicking on the login button to a servlet. The servlet have to add the name into the playerlist.
The servlet already receives the entered name but it post it on hole new HTML page. How do I have to change the code so that name will be added to playerlist on the same HTML page not on new page?
#WebServlet("/Playerlist")
public class Playerlist extends HttpServlet {
private static final long serialVersionUID = 1L;
public Playerlist() {
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String name = request.getParameter("name");
PrintWriter out = response.getWriter();
out.println("<html><Body>Hallo" + name + "</body></html>");
out.flush();
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
Textfield:
<div id= "loginFormular" >
<form action="Playerlist" method="get" >
<label>
Name:
<input class="textbox" id="loginbox" type="text" name="name" size="30" maxlength="30">
</label>
<br>
<input id=buttonLogin class="loginbutton" type="submit" value="Login" name="loginname" />
<input id=startButton class="loginbutton" type="submit" value="Start" onclick="showQuestion()" />
</form>
</div>
Playerlist:
<div class="highscore" style="float:right">
<h4>
<span class="glyphicon glyphicon-star" aria-hidden="true"></span>
<span>Highscore</span>
</h4>
<hr/>
<table id="highscoreTable" class="table table-hover">
<thead>
<tr>
<td>Player</td>
<td>Score</td>
</tr>
</thead>
<tbody id="tablePlayerlistBody">
</tbody>
</table>
</div>
I konw there are better ways instead of using a servlet, but I have to it this way.
Your page is too static for what you want to do. I am assuming that you are doing this for practice.
What you are doing is
submitting your name from a static page.
Getting the submitted name on servlet side.
Sending new content to client.
Instead what you need to do is
Create a dynamic page (JSP) with a text field and list.
Submit the field value to servlet.
Receive the value and persist it on server side. Maintain some type of list on server side and add this value to it and set it on either of the servlet contexts.
redirect to the same page using request dispatcher and then iterate over the list of values maintained on server side.
Something as below.
Servlet
String name = request.getParameter("name");
serverSideList.add(name );
JSP
<table id="highscoreTable" class="table table-hover">
<thead>
<tr>
<td>Player</td>
<td>Score</td>
</tr>
</thead>
<tbody id="tablePlayerlistBody">
<% for(int i=0 ; i< serverSideList.size(); i++){ %>
<tr>
<td>
<%=serverSideList.get(i)%>
</td>
<td>Some Score</td>
</tr>
<%}%>
</tbody>
</table>
For persisting you can do two things.
Simple : Maintain server side list in Application Context
Standard : Persist player detail in database.
Please feel free to ask if you have any questions.
I'm new to mysql and teaching myself the ropes. I've come across a problem and hoping for some advice.
I created a form in a jsp page to insert data to a mysql database. All data is properly inserted, and when I do select* all data is properly displayed in a table I created. My problem is with my update page.
When I call data from the database back into a form on my editdata.jsp page, only everything before a space is returned. For example, I put the name 'Tom Jones' into a database, but when I go to retrieve it from the name field, only 'Tom' is returned; 'Jones' is not, but is still there in the database.
Here's my editdata.jsp code:
<%#page import="java.sql.ResultSet"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<form action ="UpdateData" method ="post">
<table border ="1" width="80%">
<%ResultSet res = (ResultSet) request.getAttribute("EditData");%>
<%if(res.next()){
%>
<tr>
<td>ID</td>
<td><input type="text" name="id" value=<%=res.getString("id")%>>
</td>
</tr>
<tr>
<td>Container Number </td>
<td><input type="text" name="id" value=
<%=res.getString("containerNumber")%> ></td>
</tr>
<tr>
<td>Size </td>
<td><input type="text" name="id" value=<%=res.getString("size")%>>
</td>
</tr>
<tr>
<td>Vessel </td>
<td><input type="text" name="id" value=<%=res.getString("vessel")%>>
</td>
</tr>
<tr>
<td>Full Out Date </td>
<td><input type="text" name="id" value=
<%=res.getString("fullOut")%>> </td>
</tr
<tr>
<td>Empty In Date </td>
<td><input type="text" name="id" value=<%=res.getString("emptyIn")%>
></td>
</tr>
<tr>
<td>Empty Out Date </td>
<td><input type="text" name="id" value=
<%=res.getString("emptyOut")%>> </td>
</tr>
<tr>
<td>Full In Date </td>
<td><input type="text" name="id" value=<%=res.getString("fullIn")%>>
</td>
</tr>
<tr>
<td>Comments </td>
<td><input type="text" name="id" value=
<%=res.getString("comments")%>> </td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Update" name="update"> </td>
</tr>
<%}%>
</table>
</form>
</body>
</html>
And my EditRecord servlet:
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
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 EditRecord extends HttpServlet {
Connection conn;
ResultSet res;
Statement stmt;
String id, query;
DatabaseConnection dbconn;
protected void processRequest(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
id = request.getParameter("id");
dbconn = new DatabaseConnection();
conn = dbconn.setConnection();
stmt = conn.createStatement();
query = "select * from inventory where id = "+id;
res = dbconn.getResult(query, conn);
}catch(Exception e){
}
finally {
request.setAttribute("EditData", res);
RequestDispatcher rd = request.getRequestDispatcher("editdata.jsp");
rd.forward(request, response);
out.close();
}
}
/**
* 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>
}
Again, the long and short of my problem is that full strings of data are not returned after spaces. So 'TOM JONES' only returns 'TOM' to the form above for editing. How do I get the full string of data to be returned. I don't know if it matters, but I used VARCHAR for all my record info.
Thanks for any and all help.
Attributes inside HTML tags are separated by spaces. That's why you're supposed to use quotes around the attribute values.
BAD:
<input type="text" name="id" value=<%=res.getString("comments")%>>
GOOD:
<input type="text" name="comments" value="<%=res.getString("comments")%>" />
My Servlet Code is
package DBCon;
import java.io.*;
import java.net.*;
import java.util.ArrayList;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
/**
*
* #author Nayan
*/
public class loadCourseId extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
* #param request servlet request
* #param response servlet response
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
ArrayList ar1=new ArrayList();
ArrayList ar2=new ArrayList();
int i;
i=0;
try
{
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con=DriverManager.getConnection("jdbc:mysql://localhost/online_exam?"+"user=root&password=pass");
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("select * from course");
while(rs.next())
{
ar1.add(rs.getString(1));
ar2.add(rs.getString(2));
}
request.getSession().setAttribute("CourseID", ar1);
request.getSession().setAttribute("CourseName", ar2);
RequestDispatcher requestDispatcher=getServletContext().getRequestDispatcher("http://localhost:8080/ONLINE_EXAM/removeCourse.jsp");
requestDispatcher.forward(request,response);
}
catch(Exception e) {
out.println("<h1>"+e.getStackTrace()+"</h1>");
}
}
// <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
*/
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
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*/
public String getServletInfo() {
return "Short description";
}
// </editor-fold>
}
And Jsp Code is
<%#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">
<%#page import="javax.servlet.*"%>
<%# page import="java.util.ArrayList.*" %>
<%# page import="java.sql.*;" %>
<html>
<head>
<script type="text/javascript" language="Javascript" >
window.onload=function LoadCombo()
{
window.action="loadCourseId.do";
ArrayList cd=new ArrayList();
cd.add(request.getSession().getAttribute("CourseID"));
if(cd.isEmpty()==false)
{
for(int i=0;i<cd.size();i++)
{
var newOpt = cid.appendChild(document.createElement('option'));
newOpt.text = cd.get(i);
}
}
else
{
alert("Course table is empty")
}
}
</script>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Remove Course</title>
<style type="text/css">
<!--
body {
background-color: #FFCCFF;
}
.style1 {
color: #0066FF;
font-weight: bold;
}
.style2 {font-size: 18px}
.style17 { font-family: "Monotype Corsiva";
font-size: 24px;
font-weight: bold;
font-style: italic;
color: #6633CC;
}
.style19 {color: #000099}
.style21 {color: #000099; font-weight: bold; }
-->
</style>
</head>
<body>
<jsp:include page="Log_Admin.jsp"/><br/>
<form action="" method="post" name="form1" id="form1" >
<table width="46%" height="43" border="3" bgcolor="##CCCC99" align="center">
<tr>
<td width="85%" align="center" bgcolor="##CCCC99"><label><span class="style17">Course Information</span></label></td>
</tr>
<tr><td>
<table width="666" height="207" border="0" align="center" bordercolor="#F0F0F0" bgcolor="#CCCC99" >
<tr>
<td width="186" height="46" align="left"><div align="left"><span class="style19">
<label><strong>Course ID</strong></label>
</span></div></td>
<td><label>
<select name="cid" size="1" id="cid" align="left">
</select>
</label></td>
</tr>
<tr>
<td height="53" align="left"><div align="left"><label><span class="style21">Course Name</span></label></div></td>
<td align="left"><input name="cname" type="text" id="cname" size="50" maxlength="50" /></td>
</tr>
<tr>
<td> </td>
<td> <input name="save" type="submit" id="save" value="Save" />
<input name="reset" type="reset" id="reset" value="Reset" /></td>
</tr>
</table>
</td></tr>
</table>
</form>
</body>
</html>
Bt by writing this code i am not able to add item CourseId to the combobox cid. Can you say me where is the problem? Thanks.
You've 2 synchronous lists whose items are related to each other. This is not really easy to maintain and traverse. Rather put the values of the two lists in a Map.
Map<String, String> courses = new LinkedHashMap<String, String>();
// ...
while(resultSet.next()) {
map.put(resultSet.getString(1), resultSet.getString(2));
}
// ...
request.setAttribute("courses", courses);
In JSP you can use the JSTL <c:forEach> tag to iterate over a List or a Map. In case of a Map, each iteration will give you a Map.Entry in the var attribute which in turn has getKey() and getValue() methods. So this should do:
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
...
<select name="cid" size="1" id="cid" align="left">
<c:forEach items="${courses}" var="course">
<option value="${course.key}">${course.value}</option>
</c:forEach>
</select>
Further, the first two lines in your processRequest() method
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
should be removed since that's the responsibly of the JSP, not the servlet. You will otherwise risk IllegalStateException errors when doing so.
Also get rid of the #page import in top of your JSP. They are at the wrong place, all associated code belongs in the servlet.
class MyBean{
String val;
String label;
//+getters setters method
}
Servlet
//fetching list of MyBean and setting it to request as attribute
request.setAttribute("beanList",beanList);
// forward this request to jsp
jsp
<select>
<c:forEach var="bean" items="${beanList}">
<option value="${bean.value}">${bean.label}</option>
</c:forEach>
</select>
My Servlet Code is
package DBCon;
import java.io.*;
import java.net.*;
import java.util.ArrayList;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
/**
*
* #author Nayan
*/
public class loadCourseId extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
* #param request servlet request
* #param response servlet response
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
ArrayList ar1=new ArrayList();
ArrayList ar2=new ArrayList();
int i;
i=0;
try
{
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con=DriverManager.getConnection("jdbc:mysql://localhost/online_exam?"+"user=root&password=pass");
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("select * from course");
while(rs.next())
{
ar1.add(rs.getString(1));
ar2.add(rs.getString(2));
}
request.getSession().setAttribute("CourseID", ar1);
request.getSession().setAttribute("CourseName", ar2);
RequestDispatcher requestDispatcher=getServletContext().getRequestDispatcher("http://localhost:8080/ONLINE_EXAM/removeCourse.jsp");
requestDispatcher.forward(request,response);
}
catch(Exception e) {
out.println("<h1>"+e.getStackTrace()+"</h1>");
}
}
// <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
*/
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
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*/
public String getServletInfo() {
return "Short description";
}
// </editor-fold>
}
And Jsp Code is
<%#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">
<%#page import="javax.servlet.*"%>
<%# page import="java.util.ArrayList.*" %>
<%# page import="java.sql.*;" %>
<html>
<head>
<script type="text/javascript" language="Javascript" >
window.onload=function LoadCombo()
{
window.action="loadCourseId.do";
ArrayList cd=new ArrayList();
cd.add(request.getSession().getAttribute("CourseID"));
if(cd.isEmpty()==false)
{
for(int i=0;i<cd.size();i++)
{
var newOpt = cid.appendChild(document.createElement('option'));
newOpt.text = cd.get(i);
}
}
else
{
alert("Course table is empty")
}
}
</script>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Remove Course</title>
<style type="text/css">
<!--
body {
background-color: #FFCCFF;
}
.style1 {
color: #0066FF;
font-weight: bold;
}
.style2 {font-size: 18px}
.style17 { font-family: "Monotype Corsiva";
font-size: 24px;
font-weight: bold;
font-style: italic;
color: #6633CC;
}
.style19 {color: #000099}
.style21 {color: #000099; font-weight: bold; }
-->
</style>
</head>
<body>
<jsp:include page="Log_Admin.jsp"/><br/>
<form action="" method="post" name="form1" id="form1" >
<table width="46%" height="43" border="3" bgcolor="##CCCC99" align="center">
<tr>
<td width="85%" align="center" bgcolor="##CCCC99"><label><span class="style17">Course Information</span></label></td>
</tr>
<tr><td>
<table width="666" height="207" border="0" align="center" bordercolor="#F0F0F0" bgcolor="#CCCC99" >
<tr>
<td width="186" height="46" align="left"><div align="left"><span class="style19">
<label><strong>Course ID</strong></label>
</span></div></td>
<td><label>
<select name="cid" size="1" id="cid" align="left">
</select>
</label></td>
</tr>
<tr>
<td height="53" align="left"><div align="left"><label><span class="style21">Course Name</span></label></div></td>
<td align="left"><input name="cname" type="text" id="cname" size="50" maxlength="50" /></td>
</tr>
<tr>
<td> </td>
<td> <input name="save" type="submit" id="save" value="Save" />
<input name="reset" type="reset" id="reset" value="Reset" /></td>
</tr>
</table>
</td></tr>
</table>
</form>
</body>
</html>
Bt by writing this code i am not able to add item CourseId to the combobox cid. Can you say me where is the problem? Thanks.
You've 2 synchronous lists whose items are related to each other. This is not really easy to maintain and traverse. Rather put the values of the two lists in a Map.
Map<String, String> courses = new LinkedHashMap<String, String>();
// ...
while(resultSet.next()) {
map.put(resultSet.getString(1), resultSet.getString(2));
}
// ...
request.setAttribute("courses", courses);
In JSP you can use the JSTL <c:forEach> tag to iterate over a List or a Map. In case of a Map, each iteration will give you a Map.Entry in the var attribute which in turn has getKey() and getValue() methods. So this should do:
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
...
<select name="cid" size="1" id="cid" align="left">
<c:forEach items="${courses}" var="course">
<option value="${course.key}">${course.value}</option>
</c:forEach>
</select>
Further, the first two lines in your processRequest() method
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
should be removed since that's the responsibly of the JSP, not the servlet. You will otherwise risk IllegalStateException errors when doing so.
Also get rid of the #page import in top of your JSP. They are at the wrong place, all associated code belongs in the servlet.
class MyBean{
String val;
String label;
//+getters setters method
}
Servlet
//fetching list of MyBean and setting it to request as attribute
request.setAttribute("beanList",beanList);
// forward this request to jsp
jsp
<select>
<c:forEach var="bean" items="${beanList}">
<option value="${bean.value}">${bean.label}</option>
</c:forEach>
</select>