HttpSession doesn't persist from JSP to Servlet - java

I've an InitializeServlet that creates and instantiates a HttpSession then redirects to a JSP (betFinalize.jsp). Here I can work on my session. When from that JSP I redirect (through a form) to another Servlet, FinalizeServlet I loose my session. I cannot figure out why. Following code.
InitializeServlet.java
public class InitializeServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
#Override
public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String fName = request.getParameter("fName");
String lName = request.getParameter("lName");
String result = request.getParameter("result");
Bet s = new Bet();
s.setFirstLastName(fName + " " + lName);
s.setResult(result);
s.setMultiplier(calculateMultiplier());
request.getSession(true).setAttribute("bet", s);
RequestDispatcher rd = getServletContext().getRequestDispatcher("/betFinalize.jsp");
rd.forward(request, response);
}
private double calculateMultiplier() {
return 0.8;
}
}
betFinalized.jsp
<%# page import="it.unibo.tw.model.beans.Bet"%>
<%# page import="it.unibo.tw.model.beans.Bets"%>
<%# page session="true"%>
<jsp:useBean id="bet" class="it.unibo.tw.model.beans.Bet" scope="session"></jsp:useBean>
<jsp:useBean id="finalizedBets" class="it.unibo.tw.model.beans.Bets" scope="application"></jsp:useBean>
<!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">
</head>
<body>
<h1>Hi, <%= bet.getFirstLastName() %></h1>
<h2>Current bet: <i><%= bet.toString() %></i></h2>
<form action="finalize" method="get">
<input id="import" type="number" name="import" onkeyup="calculateWin()" ><br />
<input id="win" type="text" name="win" readonly ><br />
<input type="submit">
</form>
<hr />
<ul>
<% for(Bet s : finalizedBets.getList()) { %>
<li><%= s.toString() %></li>
<% } %>
</ul>
</body>
<script>
function calculateWin() {
var multiplier = <%= bet.getMultiplier() %>
var imp = document.getElementById("import").value
document.getElementById("win").value = imp * multiplier
}
</script>
</html>
FinalizeServlet.java
public class FinalizeServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
#Override
public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
double vincita = Double.parseDouble(request.getParameter("win"));
Bet s = (Bet) request.getSession().getAttribute("bet");
if(s != null) {
// NEVER REACH HERE
s.setWin(vincita);
s.setFinalized(true);
Bets scommesseFinalized = (Bets) getServletContext().getAttribute("scommesseFinalized");
scommesseFinalized.getList().add(s);
}
request.getSession().invalidate();
RequestDispatcher rd = getServletContext().getRequestDispatcher("/start.html");
rd.forward(request, response);
}
}

You're trying to get the wrong attribute. When you set the session variable you have:
request.getSession(true).setAttribute("scommessa", s);
When you try to read it:
request.getSession().getAttribute("bet");
it should be:
request.getSession().getAttribute("scommessa");
instead.

Encode the session id in the action of the form as below:
<form action="<%=response.encodeURL("finalize")%>" method="get">

Related

Servlet returning blank page not redirecting to jsp page

I am working on a Login and registration form. I have successfully created the Login and Registration form and linked them together. Now I created a separate page for admin where I want to display my database. But I am not able to move to the admin page. Whenever i input my admin credentials it always shows a blank page. I am a newbie both to Java and stackoverflow so I dont know how to ask proper questions. I pasted all my code here. My main problem is in Login.java . I am using eclipse and tomcat 8.5.
Things I have tried till now:-
1) RequestDispatcher rd = request.getRequestDispatcher("/WEB-INF/admin.jsp");
rd.forward(request, response);
2)HttpServletResponse.sendRedirect("/WEB-INF/admin.jsp")
3)response.sendRedirect("WEB_INF/admin.jsp");
Registeration.java
public class Registeration extends HttpServlet {
private static final long serialVersionUID = 1L;
public Registeration(){
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
}
protected void doPost(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException{
try {
String usernam = request.getParameter("usernam");
String password = request.getParameter("password");
String age = request.getParameter("age");
String gender = request.getParameter("gender");
String event = request.getParameter("event");
String sql = "insert into
registeration(usernam,password,age,gender,event) values(?,?,?,?,?)";
Class.forName("com.mysql.jdbc.Driver");
Connection conn =
DriverManager.getConnection("jdbc:mysql://localhost:3306/portal",
"root", "");
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1,usernam);
ps.setString(2,password);
ps.setString(3,age);
ps.setString(4,gender);
ps.setString(5,event);
ps.executeUpdate();
PrintWriter out = response.getWriter();
out.println("You have successfully registered!");
out.flush();
RequestDispatcher rd = request.getRequestDispatcher("login.jsp");
rd.include(request, response);
}
catch (ClassNotFoundException e) {
e.printStackTrace();
}
catch (SQLException e) {
e.printStackTrace();
}
}
}
Registeration.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
<style>
img {
display: block;
margin-left: auto;
margin-right: auto;
}
</style>
</head>
<img src="unilogo.PNG" style="width:40%">
<body>
<div align="center">
<form action="Registeration" method="POST">
User Name:<input type="text" name="usernam" required="required">
<br>
Password : <input type="password" name="password"
required="required"><br>
Age : <input type="text" name="age" required="required" /><br>
Gender : <select name="gender">
<option>Male</option>
<option>Female</option>
<option>Transgender</option>
</select><br>
Event : <select name="event" multiple="multiple">
<option>Mr.Tanwar Body Building</option>
<option>Fashion Show</option>
<option>Dance</option>
<option>Singing</option>
<option>Coding</option>
</select><br>
<input type="submit" value="REGISTER" />
<input type="reset" value="RESET" /><br>
<a href="${pageContext.request.contextPath}/login.jsp">Click
here
to go to the login page</a>
</form>
</div>
</body>
</html>
Login.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Login Page</title>
</head>
<body>
<div align="center">
<form action="Login" method="POST">
User Name:<input type="text" name="usernam" required="required">
<br>
Password : <input type="password" name="password"
required="required"><br>
<input type="submit" value="Login" />
<input type="reset" value="RESET" /><br>
<a
href="${pageContext.request.contextPath}/registeration.jsp">Click here
to
go to the Registration page</a>
</form>
</div>
</body>
</html>
Login.java
public class Login extends HttpServlet {
private static final long serialVersionUID = 1L;
public Login() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
}
protected void doPost(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
try {
String usernam = request.getParameter("usernam");
String password = request.getParameter("password");
String dbName = null;
String dbPassword = null;
String sql = "select * from registeration where usernam =
? and password = ?";
Class.forName("com.mysql.jdbc.Driver");
Connection conn =
DriverManager.getConnection("jdbc:mysql://localhost:3306/portal",
"root",
"");
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1,usernam);
ps.setString(2,password);
ResultSet rs = ps.executeQuery();
PrintWriter out = response.getWriter();
while(rs.next()){
dbName = rs.getString(2);
dbPassword = rs.getString("password");
if(usernam.equals("admin") &&
password.equals("password")){
RequestDispatcher rd =
request.getRequestDispatcher("/WEB-INF/admin.jsp");
rd.forward(request, response);
}
if(usernam.equals(dbName) &&
password.equals(dbPassword)) {
out.println("You have successfully logged
in!");
out.println("Age:"+rs.getString(4)+"
Gender:"+rs.getString(5)+" Event:"+rs.getString(6));
}
else {
RequestDispatcher rd =
request.getRequestDispatcher("/WEB-INF/registeration.jsp");
rd.forward(request, response);
}
}
}
catch (ClassNotFoundException e) {
e.printStackTrace();
}
catch (SQLException e) {
e.printStackTrace();
}
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID"
version="3.1">
<display-name>Registeration</display-name>
<servlet>
<servlet-name>reg</servlet-name>
<servlet-class>jdbc.registeration</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>reg</servlet-name>
<url-pattern>/regServlet</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>login</servlet-name>
<servlet-class>jdbc.Login</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>login</servlet-name>
<url-pattern>/loginServlet</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>30</session-timeout>
</session-config>
</web-app>
My login page is supposed to redirect me to admin.jsp when i enter my admin details. But all i get is a blank page. My url after entering admin details"http://localhost:8080/Registeration/Login". I am getting the required output when enter the login id which are stored in DB.

Update password from database using JavaServlet

Hello, im working on a project in the university, and im stuck on an error.
Im working on a mypage feature, where you can update your old password, when you are looged in. The problem is that ChangepasswordServlet is not doing what it is supposed to do.
Here you can see my servlet, the problem is probably somewhere in the IF sentence. (Manager=Entitymanager)
#WebServlet(name = "ChangePasswordServlet", urlPatterns = {"/ChangePassword"})
public class ChangePasswordServlet extends HttpServlet {
#EJB
UserManagerLocal manager;
private void changePassword(HttpServletRequest request, HttpServletResponse response) throws IOException {
String loggedInUsersUsername = request.getRemoteUser();
/* PrintWriter writer = response.getWriter(); */
User userFromTheDB = manager.getUser(loggedInUsersUsername);
String oldPasswordFromDB = userFromTheDB.getPassword();
String oldPasswordFromForm = (String) request.getAttribute("theOldPW");
;
String newPasswordFromForm = (String) request.getAttribute("theNewPW");
String newPasswordToCheckFromForm = (String) request.getAttribute("theNewPWCheck");
try {
if (oldPasswordFromDB.toLowerCase().equals(oldPasswordFromForm.toLowerCase()) && newPasswordFromForm.toLowerCase().equals(newPasswordToCheckFromForm.toLowerCase())) {
userFromTheDB.setPassword(newPasswordFromForm);
manager.updateUser(userFromTheDB);
response.sendRedirect("/Slit/MyPage/PasswordSucsess.jsp");
} else {
response.sendRedirect("Slit/Error/error.jsp");
}
}
catch (NullPointerException en) {
PrintWriter print = response.getWriter();
print.println("nullpointeryes");
print.close();
}
}
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
changePassword(request, response);
}
#Override
protected void doPost (HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
changePassword(request, response);
}
so
Here is my JSP with the form
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<head>
<title>Her kan du endre ditt nåværende passord</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" type="text/css"
href="/Slit/Templates/CSS/MainPageTemplate.css">
</head>
<body>
<title>Slit</title>
<div>
<div class="form">
<form method="post" action="/Slit/ChangePassword">
<input type="Password" name="theOldPW" placeholder="Gammelt
Password"/>
<input type="Password" name ="theNewPW" placeholder="Nytt
Password"/>
<input type="Password" name ="theNewPWCheck" placeholder=" Nytt
Password på nytt"/>
<input type="submit" name="ByttePassord" value="Trykk her for å bytte
passord!"/>
</form>
</div>
</div>
</body>
</html>
</head>
<body>
</body>
So im getting nullpointer after i have filled in the form with the old and the new password.
If im running the code now, im getting the "nullpointeryes" error.
Edit:
This is the console error after filling in the form:
12:39:37,194 INFO [stdout] (default task-12) Hibernate: select
user0_.username as username2_3_0_, user0_.fName as fName3_3_0_, user0_.lName
as lName4_3_0_, user0_.password as password5_3_0_, user0_.DTYPE as
DTYPE1_3_0_ from User user0_ where user0_.username=?
Thanks for any answers
After hours i figured that i used get.attribute instead of parameter :/
String newPasswordFromForm = (String) request.getParameter("theNewPW");
String newPasswordToCheckFromForm = (String)
request.Paramter("theNewPWCheck");

getParameter in servlet

I am trying to call getParameter. Everything is ok, but when I click the edit link it gives a NullPointerException. Why does it not get the value?
JSP CODE:
<%#page import="teacher.TeacherBAL"%>
<%#page import="teacher.TeacherBean" %>
<%#page import="java.util.*" %>
<%# 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>Display Data</title>
</head>
<body>
<table border=1>
<th>Name</th>
<th>Degree</th>
<th>Delete</th>
<th>Edit</th>
<%
ArrayList teachers = (ArrayList) request.getAttribute("allRecord");
if (teachers != null) {
int a = 0;
for (; a < teachers.size(); a++) {
TeacherBean teacherBea = (TeacherBean) teachers.get(a);
%>
<tr>
<td><%=teacherBea.getName()%></td>
<td><%=teacherBea.getDegree()%></td>
<td>
Delete
</td>
<td>
Edit
</td>
</tr>
<%}
}
%>
</table>
</body>
Servlet Code:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
String edit= request.getParameter("click");
String del = request.getParameter("delete");
String req= request.getParameter("show");
if(del!=null){
int dele = Integer.parseInt(del);
TeacherBAL.getTeacher().remove(dele);
request.setAttribute("allRecord", TeacherBAL.getTeacher());
RequestDispatcher rd= request.getRequestDispatcher("display.jsp");
rd.forward(request, response);
}
else if(req.equals("ok")){
request.setAttribute("allRecord", TeacherBAL.getTeacher());
RequestDispatcher rd= request.getRequestDispatcher("display.jsp");
rd.forward(request, response);
}
else if(edit!=null){
int num = Integer.parseInt(edit);
PrintWriter out = response.getWriter();
out.print(num);
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String name= request.getParameter("names");
String degre= request.getParameter("degre");
if(name!=null && degre!=null){
TeacherBAL.setTeacher(new TeacherBean(name,degre));
RequestDispatcher rd= request.getRequestDispatcher("index.jsp");
rd.forward(request, response);
}
}
You are getting a null pointer exception because you did not pass the values of delete and show when you clicked the edit button. Because of this, del and req are null and you are getting an exception on req.equals("ok").

passing value to a jsp page from a java class using DAO

I wanted to pass the value retrieved on a java class to a page.I am using DAO classes.
I have retrieved the values from the database and stored them on String variables.Now I want to set them to the text boxes in my view.jsp page.I am new to this area,can anyone help me out??
View.jsp is as
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="process.jsp">
Enter Name <br/> <br> <input type="text" name="uname" onclick="this.value=''"/><br/><br/>
<input type="submit" value="view details"/><br/><br/>
Email id: <br/> <input type="text" name="email" id="email" > <br/><br/>
password: <br/> <input type="text" name="passw" id="passw"><br/><br/>
</form>
</body>
</html>
and My Activity ViewDAO.java is as
public static void view(user u) {
Connection con=ConnectionProvider.getCon();
String uname=u.getUname();
try {
PreparedStatement ps=con.prepareStatement("select email,pass from S1.USER432 where name='"+uname+"'");
ResultSet rs = ps.executeQuery();
while (rs.next()) {
String email = rs.getString("EMAIL");
String pass = rs.getString("PASS");
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Thanks...
If you are using a front controller[spring mvc] then you can pass the data by doing,
model.addAttribute("variable_name ", data);
and in the jsp you can access it by doing this ${variable_name};
You need to call the DAO method from your servlet like below:
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// call DAO method to get the email and password
HashMap<String,String> map=ViewDAO.getDetails();
//from the map you will get the email and password.then you need to set them in the attributes and get them in your jsp
request.setAttribute("email", map.get("email"));
request.setAttribute("password", map.get("password"));
}
your DAO method should be like the below:
public static HashMap<String,String> getDetails(user u) {
Connection con=ConnectionProvider.getCon();
String uname=u.getUname();
Map<String,String> map=new HashMap<>();
try {
PreparedStatement ps=con.prepareStatement("select email,pass from S1.USER432 where name='"+uname+"'");
ResultSet rs = ps.executeQuery();
while (rs.next()) {
String email = rs.getString("EMAIL");
String pass = rs.getString("PASS");
}
map.put("email",email);
map.put("password",pass);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return map;
}
}
Hope this will help you.
if you are using simple jsp and servelt, then make one ViewController.java.
You can two methods one for handling GET and other for POST
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
String email = request.getParameter("email");
String password = request.getParameter("password");
request.setAttribute("email", email);
request.setAttribute("password", password);
request.getRequestDispatcher("view.jsp").forward(request, response);
}
catch(Exception e){
}
View.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="process.jsp">
Enter Name <br/> <br> <input type="text" name="uname" onclick="this.value=''"/><br/><br/>
<input type="submit" value="view details"/><br/><br/>
Email id: <br/> <input type="text" name="email" id="email" value="<%=email%>" > <br/><br/>
password: <br/> <input type="text" name="passw" id="passw" value="<%=password%>"><br/><br/>
</form>
</body>
</html>
The Servlet decides which page must be loaded. So whatever you get from the DAO must go to the Servlet and through that, to the jsp. You can use a bean class to send values from DAO to Servlet.
Like this,
public class Details{
private String email;
private String password;
public void setEmail(String email){
this.email = email;
}
public void setPassword(String password){
this.password= password;
}
public String getEmail(){
return this.email;
}
public String getPassword(){
return this.password;
}
}
And you can make the following changes in DAO after getting the query results in the String. Add these
Details d = new Details();
d.setEmail(email);
d.setPassword(pass);
return d;
You can pass this object d to the servlet and retrieve the values using the getter methods of the bean. Also, the DAO must be called from the Servlet.
And now on the Servlet side.
On the Servlet you can put your code in the get or post method depending on your need. It may be like
public class ExampleServlet extends HttpServlet{
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String email = request.getParameter("email"); //got from the jsp where "email" is the name attribute of the input field
Details d = new Details();
d = ViewDao.view(user_object); //the bean sent by DAO. "user_object" is parameter that your DAO method is taking in your code
if(d.getEmail()!=null){ //just an example
// your code that redirects desired page
}
}
}
Based on d returned by the DAO you may redirect to any page you want.
Something like that
Observe this import
dao.UserDao,bean.*,
dao is the package
UserDao is the class
bean is the method you want or is could an attribute from dao
remember that
jsp
<body>
<%#page import="dao.UserDao,bean.*,java.util.*"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<h1>Users List</h1>
<%
List<User> list=UserDao.getAllRecords();
request.setAttribute("list",list);
%>
<div class="table-responsive">
<table class="table">
<thread class="bg-info">
<th>Id</th><th>Name</th><th>Password</th><th>Edit</th><th>Delete</th>
</thread>
<c:forEach items="${list}" var="u">
<tr>
<td>${u.getId()}</td><td>${u.getUsername()}</td><td>${u.getPassword()}</td>
<td>Edit</td>
<td>Delete</td>
</tr>
</c:forEach>
</table>
</div>
<br/>Add New User
<br>
<br>
<form action="index.jsp">
<button type="submit">IndexUsers</button>
</form>
</body>
Bean or model
package bean;
// classe para as tables
public class User {
private int id;
private String username,password;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
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;
}
}
dao
public class UserDao {
public static Connection getConnection(){
Connection con=null;
try{
Class.forName("com.mysql.cj.jdbc.Driver");
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/mysql_database","root","14570");
}catch(Exception e){System.out.println(e);}
return con;
}
public static int save(User u){
int status=0;
try{
Connection con=getConnection();
PreparedStatement ps=con.prepareStatement(
"insert into login(username,password) values(?,?)");
ps.setString(1,u.getUsername());
ps.setString(2,u.getPassword());
status=ps.executeUpdate();
}catch(Exception e){System.out.println(e);}
return status;
}
public static int update(User u){
int status=0;
try{
Connection con=getConnection();
PreparedStatement ps=con.prepareStatement(
"update login set username=?,password=? where id=?");
ps.setString(1,u.getUsername());
ps.setString(2,u.getPassword());
ps.setInt(3,u.getId());
status=ps.executeUpdate();
}catch(Exception e){System.out.println(e);}
return status;
}
public static int delete(User u){
int status=0;
try{
Connection con=getConnection();
PreparedStatement ps=con.prepareStatement("delete from login where id=?");
ps.setInt(1,u.getId());
status=ps.executeUpdate();
}catch(Exception e){System.out.println(e);}
return status;
}
public static List<User> getAllRecords(){
List<User> list=new ArrayList<User>();
try{
Connection con=getConnection();
PreparedStatement ps=con.prepareStatement("select * from login");
ResultSet rs=ps.executeQuery();
while(rs.next()){
User u=new User();
u.setId(rs.getInt("id"));
u.setUsername(rs.getString("username"));
u.setPassword(rs.getString("password"));
list.add(u);
}
}catch(Exception e){System.out.println(e);}
return list;
}
public static User getRecordById(int id){
User u=null;
try{
Connection con=getConnection();
PreparedStatement ps=con.prepareStatement("select * from login where id=?");
ps.setInt(1,id);
ResultSet rs=ps.executeQuery();
while(rs.next()){
u=new User();
u.setId(rs.getInt("id"));
u.setUsername(rs.getString("username"));
u.setPassword(rs.getString("password"));
}
}catch(Exception e){System.out.println(e);}
return u;
}
}
Another Example this import import="dao.*"% makes available any methods from package dao, Bellow you see how to get the result of the method countid() in the dao.
<%#page import="dao.*"%>
<%#page import="java.sql.DriverManager"%>
<%#page import="java.sql.ResultSet"%>
<%#page import="java.sql.Connection"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<% int id = 0; %>
<%
DaoEvento daoEvento = new DaoEvento();
id = daoEvento.countId();
%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#4.6.1/dist/css/bootstrap.min.css" integrity="sha384-zCbKRCUGaJDkqS1kPbPd7TveP5iyJE0EjAuZQTgFLD2ylzuqKfdKlfG/eSrtxUkn" crossorigin="anonymous">
<body>
<br><br>
<form action="add_event_servletnew" method="POST">
<div class="form-group">
<td>
<font color='green' face = "Arial" size = "4">
<%= request.getParameter("message") %>
</font>
view
<td>
</div>
<div class="form-group">
<label>id</label>
<input type="text" name="id" value="<%= id%>" readonly="readonly" class="form-control"/>
</div>
<div class="form-group">
<label>Title</label>
<input type="text" name="title" value="" class="form-control" />
</div>
<div class="form-group">
<label>Start</label>
<input type="date" name="start" value="" class="form-control"/>
</div>
<div class="form-group">
<label>End</label>
<input type="date" name="end" value="" class="form-control" />
</div>
<div class="form-group">
<td><input type="submit" value="submit" class="btn btn-success btn-block"/></td>
</div>
</form>
</body>
<script src="https://cdn.jsdelivr.net/npm/jquery#3.5.1/dist/jquery.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#4.6.1/dist/js/bootstrap.bundle.min.js" integrity="sha384-fQybjgWLrvvRgtW6bFlB7jaZrFsaBXjsOMm/tB9LTS58ONXgqbR9W8oWht/amnpF" crossorigin="anonymous"></script>
<script src="jquery.mask.min.js"> </script>
</html>

Sending Information Back From Servlet to JSP

A user clicks on edit on the index.jsp page and it sends them to a editCustomer.jsp page. The problem is when I click update it doesnt update the customer information on the index page.
How can I do this using the code I have?
INDEX.JSP
<%#page import="edu.witc.Assignment02.controller.CustomerServlet"%>
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# page import="java.util.ArrayList" %>
<!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>Home</title>
</head>
<body>
<ul>
<% String customerString ="";
ArrayList<edu.witc.Assignment02.model.Customer> customers = (java.util.ArrayList)request.getAttribute("customers");
for (edu.witc.Assignment02.model.Customer customer : customers) {
customerString += "<li>" + customer.getName() +
"(" + customer.getCity() + ") (" +
"<a href='editCustomer?id=" + customer.getId() +
"'>edit</a>)</li>";
}%>
<%=customerString %>
</ul>
<body>
</html>
EDITCUSTOMER.JSP
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%#page import="edu.witc.Assignment02.controller.CustomerServlet"%>
<!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>Edit Customer</title>
</head>
<body>
<h2>Edit Customer</h2>
<% int customerId =
Integer.parseInt(request.getParameter("id"));%>
<form method='post' action='customer'>
<input type='hidden' name ='id' value='<%=customerId%>'/>
<table>
<tr><td>Name:</td><td>"
<input name='name' />
</td></tr>
<tr><td>City:</td><td>
<input name='city' />
</td></tr>
<tr>
<td colspan='2' style='text-align:right'>
<input type='submit' value='Update'/></td>
</tr>
<tr><td colspan='2'>
<a href='customer'>Customer List</a>
</td></tr>
</table>
</form></body>
</html>
SERVLET
package edu.witc.Assignment02.controller;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import edu.witc.Assignment02.*;
import edu.witc.Assignment02.model.Customer;
/*
* Not thread-safe. For illustration purpose only
*/
#WebServlet(name = "CustomerServlet", urlPatterns = {
"/customer", "/editCustomer", "/updateCustomer"})
public class CustomerServlet extends HttpServlet {
private static final long serialVersionUID = -20L;
private List<edu.witc.Assignment02.model.Customer> customers = new ArrayList<Customer>();
#Override
public void init() throws ServletException {
Customer customer1 = new Customer();
customer1.setId(1);
customer1.setName("Donald D.");
customer1.setCity("Miami");
customers.add(customer1);
Customer customer2 = new Customer();
customer2.setId(2);
customer2.setName("Mickey M.");
customer2.setCity("Orlando");
customers.add(customer2);
}
private void sendCustomerList(HttpServletResponse response, HttpServletRequest request)//redirect to index
throws IOException, ServletException {
String url = "/index.jsp";
request.setAttribute("customers", customers);
request.getRequestDispatcher(url).forward(request,response);
}
private Customer getCustomer(int customerId) {
for (Customer customer : customers) {
if (customer.getId() == customerId) {
return customer;
}
}
return null;
}
private void sendEditCustomerForm(HttpServletRequest request,
HttpServletResponse response) throws IOException, ServletException {
String url = "/editCustomer.jsp";
request.setAttribute("customers", customers);
request.getRequestDispatcher(url).forward(request,response);
}
#Override
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
String uri = request.getRequestURI();
if (uri.endsWith("/customer")) {
sendCustomerList(response, request);
} else if (uri.endsWith("/editCustomer")) {
sendEditCustomerForm(request, response);
}
}
#Override
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException, ServletException {
// update customer
int customerId = 0;
try {
customerId =
Integer.parseInt(request.getParameter("id"));
} catch (NumberFormatException e) {
}
Customer customer = getCustomer(customerId);
if (customer != null) {
customer.setName(request.getParameter("name"));
customer.setCity(request.getParameter("city"));
}
sendCustomerList(response, request);
}
}
CUSTOMER.JAVA
package edu.witc.Assignment02.model;
public class Customer {
private int id;
private String name;
private String city;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
}
I'm not sure what you expect to happen. You are submitting this form
<form method='get' action='customer'>
<table>
<tr>
<td>Name:</td>
<td>
"
<input name='name' />
</td>
</tr>
<tr>
<td>City:</td>
<td>
<input name='city' />
</td>
</tr>
<tr>
<td colspan='2' style='text-align:right'>
<input type='submit' value='Update' />
</td>
</tr>
<tr>
<td colspan='2'>
<a href='customer'>Customer List</a>
</td>
</tr>
</table>
</form>
And handling it with
if (uri.endsWith("/customer")) {
sendCustomerList(response, request);
and
private void sendCustomerList(HttpServletResponse response, HttpServletRequest request)//redirect to index
throws IOException, ServletException {
String url = "/index.jsp";
request.setAttribute("customers", customers);
request.getRequestDispatcher(url).forward(request,response);
}
Nothing in the code above modifies anything in the customers List. Objects don't get changed on their own. You have to make the modifications yourself.
Maybe you meant to submit the form with a POST request. In that case, you would need an <input> field for the id.
Think about the request-response cycle.
Your Servlet container receives an HTTP request, it dispatches your Servlet to handle it. Your servlet performs some logic and forwards to a JSP. The JSP renders some HTML which is written to the body of the HTTP response. The response is sent to the client. In this case, your client is a browser which reads the HTML text and renders it graphically. You can then interact with it, fill in input fields and click buttons. When you do this, the browser takes the values you've entered and produces an HTTP request which it sends to your server. And so on, and so on...

Categories