JSP not displaying data from POST request to Servlet - java

I have an index.jsp page with buttons named "refresh", "forward" and "edit". If I click on the refresh button then it call a Servlet and values are displayed on the index.jsp page.
When I click on the "forward" button it calls another servlet and goes to another page forward_call_log.jsp. In this page when I click on the "forward" button it calls another servlet and that servlet displays the index.jsp page. The index.jsp page is displayed but the values from the data base are not available.
How can i fix this problem?
index.jsp
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Pager Example - www.javaworkspace.com</title>
</head>
<body>
<form method="post" action="./Problem_retrive" >
<input type="submit" value="Refresh">
</form>
<form action="./edit_call_log" method="post">
<%
ResultSet rs=null;
try
{
rs=(ResultSet)request.getAttribute("rs");
//request.setAttribute("rs",rs);
if(rs.next())
{
%>
<table border=1 cellspacing=1 cellpadding=1>
<tr>
<th>check box</th>
<th>Problem ID</th>
<th>user ID</th>
</tr>
<%
do
{
%>
<tr>
<td><input type="checkbox" name="checkbox" value="<%=rs.getString(1) %>"></td>
<td><%=rs.getString(1) %></td>
<td><%=rs.getString(2) %></td>
</tr>
<%
}
while(rs.next());
%>
</table>
<%
}
else
{
out.println("hiiiiiiii");
}
}
catch(Exception e)
{
e.printStackTrace();
}
%>
<input type="submit" name="act" value="EditCall"/>
<input type="submit" name="act" value="Forward"/>
</form>
</body>
</html>
After click on the Refresh button call Edit_call_servlet.java
import database.problemdesc.Problem_retrive_class;
import database.user_master.User_master;
import java.sql.*;
public class Edit_call extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
response.setContentType("text/html");
HttpSession session = request.getSession(true);
ResultSet rs=null;
Problem_retrive_class prc=new Problem_retrive_class();
int checkbox=Integer.parseInt(request.getParameter("checkbox"));
session.setAttribute("problem_id", checkbox);
String act=request.getParameter("act");
if(act.equals("EditCall"))
{
try
{
rs=prc.select_table(checkbox);
RequestDispatcher rd = request.getRequestDispatcher("edit_call_log.jsp");
request.setAttribute("rs", rs);
rd.forward(request, response);
}
catch(Exception e)
{
e.printStackTrace();
}
}
else if(act.equals("Forward"))
{
System.out.println("Forward page");
try
{
ResultSet rs1=null;
User_master um=new User_master();
rs=prc.select_table(checkbox);
if(rs.next())
{
System.out.println("Value retrieve from PRC select_table");
rs1=um.select_table(rs.getString(7));
System.out.println("Value retrieve from PRC select_table"+rs.getString(7));
RequestDispatcher rd = request.getRequestDispatcher("forward_call_log.jsp");
request.setAttribute("rs1", rs1);
request.setAttribute("user_type", rs.getString(7));
rd.forward(request, response);
}
else
{
RequestDispatcher rd = request.getRequestDispatcher("index.jsp");
rd.forward(request, response);
}
}
catch(Exception e)
{
}
}
}
}
After clicking on the Forward button call Problem_retrive_servlet.java
import database.problemdesc.Problem_retrive_class;
public class Problem_retrive extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out=response.getWriter();
Connection con=null;
ResultSet rs=null;
try
{
Problem_retrive_class prc=new Problem_retrive_class();
DBBean db=new DBBean();
con=db.getDBConnection();
rs=prc.select_table();
RequestDispatcher rd = request.getRequestDispatcher("index.jsp");
rd.forward(request, response);
}
catch(Exception e)
{
e.printStackTrace();
}
}
}

It looks like you're not attaching any data to the request object so index.jsp has nothing to display. I'm assuming this is the code that is executing when the problem occurs.
public class Edit_call extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
...
else if(act.equals("Forward"))
{
try
{
...
{
...
}
else
{
RequestDispatcher rd = request.getRequestDispatcher("index.jsp");
/ *** YOUR PROBLEM IS HERE ***/
rd.forward(request, response);
}
[EDIT]
From your question I assume that the "refresh" button on your JSP works as expected (i.e. the data from the database is displayed as expected). From the following JSP code ...
<form method="post" action="./Problem_retrive" >
<input type="submit" value="Refresh">
</form>
the method being executed on the server is Problem_retrive.doPost()
Based on this we then need to understand what code is being exectued when the "forward" button is being clicked on forward_call_log.jsp. You have described that this "forward" button displays index.jsp but does not include the data from the database. Let's assume its calling Edit_call.doPost()*.
*I suggest you place debugger breakpoints in all of your doPost() methods to confirm this assumption, or just refer to your System.out.println() statements if you can't debug.
Therefore you need to compare what is happening in Problem_retrive.doPost() to what is not happening in Edit_call.doPost() when no data is being displayed. I suspect that you are not calling request.setAttribute()
rs=prc.select_table();
RequestDispatcher rd = request.getRequestDispatcher("index.jsp");
request.setAttribute("rs", rs);
rd.forward(request, response);
A side note about good design
You can read about the MVC Design Pattern for a better way of designing your code.

Related

I can not get updated data on the page after Update request to the database (data updated only after restart applications)

I trying to stop current reservations, by clicking on CANCEL button, which call stopReservation method. Data updated in database, but redirect return the same list as was, without chages. Only after restart I get updatetd list with data. Network show 302 to cancel and 200 to allreservs, but there no chages in list.
#WebServlet("/cancel")
public class CancelReservationServlet extends HttpServlet {
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.getRequestDispatcher("/WEB-INF/pages/cancel.jsp").forward(req, resp);
}
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException, NumberFormatException {
String reservId = req.getParameter("id");
if (reservId.isEmpty()) {
resp.sendRedirect(req.getContextPath() + "/cancel");
} else {
ReservationService reservationService = new ReservationService();
try {
reservationService.stopReservation(Integer.parseInt(reservId));
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
resp.sendRedirect(req.getContextPath() + "/allreservs");
}
}
}
#WebServlet("/allreservs")
public class AllReservationsServlet extends HttpServlet {
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ReservationService reservationService = new ReservationService();
Set<ReservationDto> reservations = null;
try {
reservations = reservationService.getListOfReserves();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
req.setAttribute("reservations", reservations);
RequestDispatcher requestDispatcher = req.getRequestDispatcher("/WEB-INF/pages/allreservs.jsp");
requestDispatcher.forward(req, resp);
}
}
STOP METHOD FROM SERVICE CLASS
public void stopReservation(Integer reservationId) throws IOException, ClassNotFoundException, SQLException {
Connection connection = ConnectionFactory.getConnection();
try {
preparedStatement = connection.prepareStatement("UPDATE reservation set isActive = false where reservationId = ?");
preparedStatement.setInt(1, reservationId);
preparedStatement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
JSP
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>All reservation</title>
<link href="https://fonts.googleapis.com/css2?family=Baloo+Tamma+2:wght#500;600;700&display=swap" rel="stylesheet">
<style>
<%#include file="/styles/style.css"%>
</style>
</head>
<body>
<p>
<a href='<c:url value="/"/>'><- main page</a>
</p>
<table>
<thead>
<tr>
<th>ID</th>
<th>FULL NAME</th>
<th>MANIPULATION</th>
<th>DESCRIPTION</th>
<th>START TIME</th>
<th>END TIME</th>
<th>IS ACTIVE</th>
<th>ROOM NUMBER</th>
<th colspan="2"> CANCEL </th>
</tr>
</thead>
<c:forEach items="${reservations}" var="reservations">
<tbody>
<tr>
<td>${reservations.id}</td>
<td>${reservations.fullName}</td>
<td>${reservations.manipulationName}</td>
<td>${reservations.description}</td>
<td>${reservations.startTime}</td>
<td>${reservations.endTime}</td>
<td>${reservations.isActive}</td>
<td>${reservations.roomNumber}</td>
<td><form action="${pageContext.request.contextPath}/cancel" method="post">
<td>
<button onclick="location.href='/cancel'">cancel</button>
<input type="hidden" name="id" value="${reservations.id}">
</td>
</form></td>
</tr>
</tbody>
</c:forEach>
</table>
</body>
</html>
additional:
public Set<ReservationDto> getListOfReserves() throws IOException, ClassNotFoundException, SQLException {
Connection connection = ConnectionFactory.getConnection();
preparedStatement = connection.prepareStatement(GET_RESERVE_DATA);
result = preparedStatement.executeQuery();
while (result.next()) {
reservs.add(new ReservationDto(
result.getInt("reservationId"),
result.getString("fullName"),
result.getString("manipulationName"),
result.getString("description"),
result.getTimestamp("startTime"),
result.getTimestamp("endTime"),
result.getBoolean("isActive"),
result.getInt("roomNumber")));
}
return reservs;
}
private static final String GET_RESERVE_DATA = "SELECT rsrv.reservationId, CONCAT(empl.name, ' ', empl.surname) as fullname, " +
"rsrv.manipulationName, rsrv.description, rsrv.startTime, " +
"rsrv.endTime, rsrv.isActive, r.roomNumber, empl.employeeId, r.roomId FROM reservation AS rsrv " +
"JOIN room as r ON rsrv.roomid = r.roomId " +
"JOIN employee as empl ON rsrv.emplId = empl.employeeId ";
Declare the reservs set inside the function. As it seems that their are previous values in this set, since you must have declared it outside the function. If you don't want that, you can clear the set before adding any new values to it.
Method 1
Inside getListOfReserves() declare Set<ReservationDto> reservs = new HashSet<>();
Method 2
Just before iterating the result. User clear to remove all the previous values from the set. reservs.clear()

I'm having trouble with doGet and doPost methods

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.

Cannot forward after response has been committed Servlet error

When I run this code, I get an IllegalStateException: Cannot forward after respons has been committed. I apologize, I am new to servlets. What should I do to fix this problem? This occurs at this line:
RequestDispatcher rd = request.getRequestDispatcher("/displayjobs.jsp");
rd.forward(request, response);
Here is the stack trace of the exception:
java.lang.IllegalStateException: Cannot forward after response has been committed
schedule.doGet(schedule.java:71)
javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51)
Here is the rest of my servlet code.
EDIT: I have also included my jsp code, as I am now experiencing a NPE at line 2:
1 List data = (List)request.getAttribute("jobsData);
2 for(itr = data.iterator(); itr.hasNext();)
This means that for some reason data is null rather than having the information of JobsData.
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String connectionUrl = "jdbc:sqlserver://10.11.1.246;databaseName=Test;integratedSecurity=false;user=sa;password=S0l1dConcepts";
Connection con = DriverManager.getConnection(connectionUrl);
String query = "select * from jobs";
stmt = con.createStatement();
res = stmt.executeQuery(query);
while(res.next()){
list.add(res.getString(1));
list.add(res.getString(2));
list.add(res.getString(3));
list.add(res.getString(4));
list.add(res.getString(5));
list.add(res.getString(6));
list.add(res.getString(7));
list.add(res.getString(8));
list.add(res.getString(9));
list.add(res.getString(10));
}
res.close();
}
catch(Exception e){
RequestDispatcher rd = request.getRequestDispatcher("/error.jsp");
rd.forward(request, response);
}
finally{
request.setAttribute("jData", list);
RequestDispatcher rd = request.getRequestDispatcher("/displayjobs.jsp");
rd.forward(request, response);
list.clear();
out.close();
}
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String connectionUrl = "jdbc:sqlserver://10.11.1.246;databaseName=Test;integratedSecurity=false;user=sa;password=S0l1dConcepts";
Connection con = DriverManager.getConnection(connectionUrl);
String query = "select * from jobs";
stmt = con.createStatement();
res = stmt.executeQuery(query);
while(res.next()){
list.add(res.getString(1));
list.add(res.getString(2));
list.add(res.getString(3));
list.add(res.getString(4));
list.add(res.getString(5));
list.add(res.getString(6));
list.add(res.getString(7));
list.add(res.getString(8));
list.add(res.getString(9));
list.add(res.getString(10));
}
res.close();
}
catch(Exception e){
RequestDispatcher rd = request.getRequestDispatcher("/error.jsp");
rd.forward(request, response);
}
finally{
request.setAttribute("jData", list);
RequestDispatcher rd = request.getRequestDispatcher("/displayjobs.jsp");
rd.forward(request, response);
list.clear();
out.close();
}
}
}
Here is the JSP code:
<%#page import="java.util.List" %>
<%#page import="java.util.Iterator" %>
<%# 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>Scheduling</title>
</head>
<body>
<table>
<%Iterator itr;%>
<%List data = (List)request.getAttribute("jobsData");
for(itr = data.iterator(); itr.hasNext();){
%>
<tr>
<% String s = (String) itr.next();%>
<td><%=s%></td>
<td><%=itr.next()%></td>
<td><%=itr.next()%></td>
<td><%=itr.next()%></td>
<td><%=itr.next()%></td>
<td><%=itr.next()%></td>
<td><%=itr.next()%></td>
<td><%=itr.next()%></td>
<td><%=itr.next()%></td>
<td><%=itr.next()%></td>
<td><input type="submit" value="Edit" name="edit" onclick ="editRecord(<%=s%> %>);"></td>
<td><input type="submit" value="Delete" name="delete" onclick ="deleteRecord(<%=s%> %>);"></td>
<%} %>
</tr>
</table>
The problem is simple.The exception is caught,response is delegated from catch block and again from the finally block.
What you should do is have a single place for delegating your response
please note :- A response can be committed only once
boolean exceptionOcured =false;
try{
// your code
}
catch(Exception e){
exceptionOcured =true;
}
finally{
// your code to release resources
}
if(exceptionOcured){
RequestDispatcher rd = request.getRequestDispatcher("/error.jsp");
rd.forward(request, response);
}else{
RequestDispatcher rd = request.getRequestDispatcher("/displayjobs.jsp");
rd.forward(request, response);
}
There are a number of problems with your code... in particular, in the case of an error, you will try to forward twice (once in the catch block and once in the finally block). You should probably add server side logging when you get an exception so that you know there's a problem rather than just tossing the error to the user.
You also have code duplicated between doGet and doPost and a resource leak (you aren't closing the database connection or the statement).
Select * is also a bad idea.
And where is list defined? If it's defined at the servet class level, your code isn't thread safe.

Hang Man Game in MVC with JSP

I want to create Hang man game, but I need to save the session and the username, but I have problems for pass the username. I wrote the JSP, servlet and Javabean, but after the login my user, in the next view I only have Welcome + NULL. Help me please. thanks for the help.
I don't know how Can I pass the name to the next view.
enter code here
this is the JavaBean(Userdata.java):
public class Userdata {
String userName;
public Userdata() {
}
public Userdata(String userName) {
this.userName = userName;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
}
This is the servlet, in this code I need to use a session, but I want to that, in all the time that the user is logging, cans see his/her name
loginServlet.java
public class loginServlet extends HttpServlet {
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws
ServletException, IOException {
doPost(req, resp);
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse resp) throws
ServletException, IOException {
HttpSession session = request.getSession();
Userdata = new Userdata(usuari);
if(request.getParameter("username")!=null &&
!request.getParameter("username").trim().equals("") ){
usuari = new Userdata(request.getParameter("username"));
}
if(request.getParameter("logout")!=null){
session.invalidate();
}
request.setAttribute("username", username);
RequestDispatcher view = request.getRequestDispatcher("juego.jsp");
view.forward(request, resp);
}
}
Finally the Views in JSP, The first view is the login
Nom de jugador:
Contrasenya:
And this is the response of servlet -> juego.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Penjat</title>
</head>
<h2>Benvingut</h2>
<%=request.getAttribute("usuari")%>
<div align="center">
<h1>Joc del Penjat</h1>
</div>
<div align="center">
<!--DelaraciĆ³ d'imatges-->
<img src="Imatges/p_JEE_3.png">
</div>
<div align="center">
<!--DeclaraciĆ³ de les lletres-->
Lletra:
<input type="text" name="lletra" size="1" maxlength="1">
<br/>
<p>
<input type="hidden" name="id" value=""/>
<input type="hidden" name="vegades_jugades" value=""/>
<input type="hidden" name="pistes" value=""/>
<input type="submit" name="boto_jugar" value="Jugar">
</p>
</div>
First you have to put username in request, in your servlet use request.setAttribute in the following manner
request.setAttribute("username", value);
where value happens to be the object you want to read later.
Use it later in a different servlet/jsp using request.getAttribute as
String value = (String)request.getAttribute("username")
or
<%= request.getAttribute("username")>
Thanks for your help, now I understand, I modificated and now I can get the username.
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse resp) throws
ServletException, IOException {
HttpSession session = request.getSession();
Userdata usuari = new Userdata();
if(request.getParameter("username")!=null &&
!request.getParameter("username").trim().equals("") ){
usuari = new Userdata(request.getParameter("username"));
}
if(request.getParameter("logout")!=null){
session.invalidate();
}
request.setAttribute("username", usuari);
RequestDispatcher view = request.getRequestDispatcher("juegoOriginal.jsp");
view.forward(request, resp);
}

Fetch, process and display the result on the same page

I have a jsp page containing a form where a user fills in some value. Now i pass these values into a servlet which processes it and retieves a related set of data. Now, i am able to retrieve the data in the servlet page, but am not able to display it on the same jsp page at which i fetched the request.
I do not want to use java code inside jsp. I wish to do the same using servlets only. I do not want to do something like this
<% if(rollno==null)
// then display the form
else
// process the request on the jsp page itself
%>
I want to process all my reults in a servlet file and then dispaly the result on the jsp page by passing data from servlet to jsp. I am posting my code below :
<form id="form" method="post" action="searchServlet">
Student Roll No :<br><input type="text" value="" name="rollno"><br><br>
<input type="submit" value="SHOW DETAILS" />
</form>
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
String rollno=request.getParameter("rollno");
ResultSet rs=null;
Class.forName("com.mysql.jdbc.Driver");
String url="jdbc:mysql://localhost/schooldatabase";
Connection con = DriverManager.getConnection(url,"root","passwd");
Statement st= (Statement) con.createStatement();
String strquery="SELECT name,regno FROM `schooldatabase`.`student_info` WHERE rollno="+ rollno+ ";";
if(!con.isClosed()) {
rs=st.executeQuery(strquery);
while(rs.next())
{
out.println(rs.getString("name"));
out.println(rs.getString("regno"));
}
}
else
{ // The connection is closed
}
}
catch(Exception e)
{
out.println(e);
}
finally {
out.close();
}
}
You shouldn't be doing the presentation in the servlet. You should not have any of those lines in the servlet.
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
// ...
out.println(rs.getString("name"));
out.println(rs.getString("regno"));
// ...
out.println(e);
You should instead be storing the data in a sensible collection and be setting it as a request attribute and finally forward the request/response to a JSP which in turn generates the proper HTML around all those data. Something like this:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
List<Student> students = studentDAO.find(request.getParameter("rollno"));
request.setAttribute("students", students); // Will be available as ${students} in JSP
request.getRequestDispatcher("/WEB-INF/students.jsp").forward(request, response);
} catch (SQLException e) {
throw new ServletException("Cannot obtain students from DB", e);
}
}
with this in the students.jsp
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
...
<table>
<c:forEach items="${students}" var="student">
<tr>
<td>${student.name}</td>
<td>${student.regno}</td>
</tr>
</c:forEach>
</table>
For a more concrete example, see also this answer: Show JDBC ResultSet in HTML in JSP page using MVC and DAO pattern
See also:
Our Servlets wiki page - Contains several Hello World examples

Categories

Resources