Using objects in Session with Servlets and JSP - java

Could someone explain to me briefly how does passing an object and using it later in JSP.
I have this servlet, with the capability to make a new object and store it to session.
package application.servlets.test;
import java.io.IOException;
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 javax.servlet.http.HttpSession;
import application.data.character.House;
/**
*
* Servlet implementation class SessionTest
*/
#WebServlet("/persons")
public class SessionTest extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public SessionTest() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
House house = new House(34);
HttpSession session = request.getSession();
session.setAttribute("House", house);
request.getRequestDispatcher("test.jsp").forward(request, response);
}
}
This is the first JSP that forwards me to that servlet:
<html>
<body>
<h2>Hello World!</h2>
<form method="post" action="persons">
<input type="submit", value="Submit"/>
</form>
</body>
</html>
And Finally the servlet will forward me to this JSP. How do I now show it JSP getLevel() method. Or any method that would be in the object House? How do I print out the values?
<%# 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>
Hello this is just a test
<h1>Hello ${sessionScope.House}!!!</h1>
<% Object o = session.getAttribute("House");
%>
</body>
</html>
Just for in case this is my house class:
package application.data.character;
public class House {
private int level;
public House(int level) {
super();
this.level = level;
}
public int getLevel() {
return level;
}
public void setLevel(int level) {
this.level = level;
}
}

you need to import the page in which your class is present
<%# page import="com.servlet.java.*"%>

Related

How should I send a parameter from jsp page to a servlet then to a jsp page then to a servlet?

I am trying to make a login form. and want the username parameter to accessed by the changepass.java file.
The flow of the application is:
login.jsp -> LoginServlet -> AfterLogin.jsp -> ChangePass.jsp -> ChangePassword Servlet
I tried using the session and request dispatcher for this it is not working.
I am able to get the parameter from login.jsp to ChangePass.jsp but after that the changePassword servlet is not able to access it.
My code for the flow is:
login.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<body>
<div align="center">
<form name="login" onsubmit="return onSubmit()" action="LoginServlet">
<h2 style="color:blue">Account Login</h2>
<table style="background-color:powderblue;border: 2px solid green;border-color:green;">
<tr><td>Enter User Name:</td><td><input type="text" name="username" minlength="6" required></td></tr>
<tr><td>Enter Pass Word:</td><td><input type="password" name="password" id="password" required></td></tr>
<tr><td colspan="2" align="center"><input type="submit" value="login"></td></tr>
</table>
<br>
<u>Home</u>
</form>
</div>
<%
String msg=(String) request.getAttribute("msg");
if(msg!=null){
%>
<p style="color:red"><%=msg%></p>
<%
}
%>
<script type="text/javascript">
function onSubmit(){
var y=document.login.password.value;
var passR=/^(?=.*\d)(?=.*[A-Z]).{6,20}$/;
if(!y.match(passR)){
alert("Password must contain at least one number and one UpperCase letter");
document.getElementById("password").focus();
}
}
</script>
</body>
</html>
LoginServlet.java
package com.wipro.controller;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
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 javax.servlet.http.HttpSession;
import com.wipro.util.DButil;
/**
* Servlet implementation class LoginServlet
*/
#WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public LoginServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
try{
Connection con=DButil.getConnection();
PrintWriter out=response.getWriter();
String username=request.getParameter("username");
String password=request.getParameter("password");
String sql="select * from user_table where username=? and password=?";
PreparedStatement st=con.prepareStatement(sql);
st.setString(1, username);
st.setString(2, password);
ResultSet rs=st.executeQuery();
if(rs.next()) {
HttpSession se=request.getSession();
se.setAttribute("username", username );
request.getRequestDispatcher("AfterLogin.jsp").include(request, response);
}
else {
request.setAttribute("msg", "Invalid Credentials");
request.getRequestDispatcher("login.jsp").include(request, response);
}
}
catch(Exception e) {
e.printStackTrace();
}
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
AfterLogin.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h1><font color=green> Welcome <%=session.getAttribute("username")%></font></h1>
Change Password
</body>
</html>
ChangePass.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<div align="center">
<form name="changePS" onsubmit="return onSubmit()" action="ChangePassword">
<%
String username=(String)session.getAttribute("username");
request.setAttribute("username", username);
%>
<h1><font color=green> Welcome <%=username%></font></h1>
<h2 style="color:blue">Change Password</h2>
<table style="background-color:powderblue;border: 2px solid green;border-color:green;">
<tr><td>Old Password:</td><td><input type="password" name="oldpwd" id="oldpwd" required></td></tr>
<tr><td>New Password:</td><td><input type="password" name="newpwd" id="newpwd" required></td></tr>
<tr><td>Confirm Password:</td><td><input type="password" name="confpwd" id="confpwd" required></td></tr>
<tr><td colspan="2" align="center"><input type="submit" value="login"></td></tr>
</table>
<br>
<u>Home</u>
</form>
</div>
<script type="text/javascript">
function onSubmit(){
y=document.changePS.oldpwd.value;
z=document.changePS.newpwd.value;
a=document.changePS.confpwd.value;
passR=/^(?=.*\d)(?=.*[A-Z]).{6,20}$/;
if(z != a){
alert("New Password and Confirm Password do not match");
document.getElementById("confpwd").focus();
return false;
}
if(!y.match(passR)){
alert("Old Password must contain at least one number,one UpperCase letters");
document.getElementById("oldpwd").focus();
return false;
}
if(!z.match(passR)){
alert("New Password must contain at least one number,one UpperCase letters");
document.getElementById("newpwd").focus();
return false;
}
return true;
}
</body>
</html>
ChangePassword.java
package com.wipro.controller;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.wipro.util.DButil;
/**
* Servlet implementation class ChangePassword
*/
#WebServlet("/ChangePassword")
public class ChangePassword extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public ChangePassword() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
try{
Connection con=DButil.getConnection();
PrintWriter out=response.getWriter();
String username = (String)request.getAttribute("username");
String password=request.getParameter("newPwd");
String sql="update user_table set password=? where username=?";
PreparedStatement st=con.prepareStatement(sql);
st.setString(1, username);
st.setString(2, password);
int rs=st.executeUpdate();
if(rs!=0) {
out.println("<h1><font color=green> Updated the password </font></h1>");
}
else {
out.println("<h1><font color=red> Sorry no username with this name </font></h1>"+username);
}
}
catch(Exception e) {
e.printStackTrace();
}
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}

while accessing two different servlets one is available and the other is throwing servlet not found error

I am working on a student management project in which I created two servlets in same folder, LoginController for handling the login and TestContoller for registering new student. The problem is that when I try to login LoginController is accessible and I am able to login but when i try to register a student through a register.jsp page mapped to TestController , I get HTTP Status 404 – Not Found. The requested resource [/StudentManagement/TestController] is not available error
Here is my code:-
register.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/TestController" method="post">
<input type="text" name="name">
<input type="submit" value="submit">
</form>
</body>
</html>
TestController
package com.controller;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class TestController
*/
#WebServlet("/TestController")
public class TestController extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public TestController() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println(request.getParameter("name"));
}
}

Show session history

I've created a small mortg. calc. and it's working correctly, however i would like to have let's say three last calculations shown on the right side and the ability to remove (clear) them (like a small history log or similar). Whatever I try previous results get deleted. Quite new to servlets and sessions.
.jsp
<%# page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<body>
<div style="width:100%;">
<div style="float:left; width:20%;">
<form id="mortgage" action="mocalc" " method="post">
<p>
Principal:
<input name="principal">
Interest rate (%):
<input name="interest_rate">
Monthly payment:
<input name="monthly_payment">
<input name="calculate" type="submit" value="Calculate" />
</form>
<form id="clear" action="index.jsp" method="get"/>
<input name="clear" type="submit" value="CE"/></form>
</p>
</div>
<div style="float:right; width:80%; ">
<p>
<table>
<tr><td>Principal:</td>
<td align="right">${pr}</td>
<tr><td>Interest Rate:</td>
<td align="right">${ir}</td>
<tr><td>Monthly Payment:</td>
<td align="right">${mp}</td>
</tr></table>
<p>
It will take ${y} years and ${m} months to payoff the loan
<p>
Total interest to be paid: $${i}
</div>
</div>
</body>
</html>
.java
import java.io.IOException;
import java.io.PrintWriter;
import java.text.DecimalFormat;
import javax.servlet.RequestDispatcher;
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 javax.servlet.http.HttpSession;
/**
* Servlet implementation class MoCalc
*/
#WebServlet("/mocalc")
public class MoCalc extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public MoCalc() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.getWriter().append("Served at: ").append(request.getContextPath());
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Float pr=Float.valueOf(request.getParameter("principal"));
Float ir = Float.valueOf(request.getParameter("interest_rate"));
Float mp = Float.valueOf(request.getParameter("monthly_payment"));
String inter=null, pri=null, ira,mpa;
DecimalFormat format = new DecimalFormat("#,##0.##");
//Payoff time in months calculation
double months=(Math.log10(mp)-Math.log10(mp-pr*(ir/100)/12))/(Math.log10(1+(ir/100)/12));
int a = (int) (months + 0.5);
Integer years=a/12;
Integer month=a%12;
//Total interest calculation
double interest=mp*months-pr;
//Format values
inter=format.format(interest);
pri="$"+format.format(pr);
ira = format.format(ir)+"%";
mpa="$"+format.format(mp);
HttpSession session=request.getSession();
session.setAttribute("y",years);
session.setAttribute("m",month);
session.setAttribute("i", inter);
session.setAttribute("pr", pri);
session.setAttribute("mp", mpa);
session.setAttribute("ir", ira);
RequestDispatcher dispatcher = request.getRequestDispatcher("index.jsp");
dispatcher.forward(request, response); }
}

JSP giving error: Requested resource not found

Just need a little help.
I tried to make a small test project but I'm stuck at this error. Having all my JAR files and JSPs well placed:
The requested resource (/LibrayManagement/list_of_books_available.jsp) is not available
Following is the jsp code :
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!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>Library</title>
</head>
<body>
<form action="Listofbooksaction" method="post">
<h3>List of books available</h3>
<c:forEach var = "list" items = "${requestScope.BooksList}">
<c:out value = "${list[0]}">
</c:out>
</c:forEach>
<input type= "submit" value = "get list">
</form>
</body>
</html>
Following is Action class code :
import java.sql.* ;
import java.io.IOException;
import java.sql.ResultSet;
import java.util.ArrayList;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
public class Listofbooksaction extends HttpServlet {
private static final long serialVersionUID = 1L;
String url = "list_of_books_available.jsp";
public Listofbooksaction() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ConnectionsList c = new ConnectionsList() ;
try {
Statement St = c.createconnection();
ResultSet Rs = St.executeQuery("Select * from books_list") ;
System.out.println(Rs);
ArrayList<String> Books_List = new ArrayList<String>();
while(Rs.next())
{
Books_List.add(Rs.getString(1));
}
request.setAttribute("BooksList", Books_List);
response.sendRedirect(url);
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Error Stacktrace:
java.lang.IllegalStateException org.apache.catalina.connector.ResponseFacade.sendRedirect(ResponseFacade.java:4‌​35) Listofbooksaction.doPost(Listofbooksaction.java:62) javax.servlet.http.HttpServlet.service(HttpServlet.java:637) javax.servlet.http.HttpServlet.service(HttpServlet.java:717)

How do I call an arrays methods from the JSP page in JSTL?

I stumbled upon servlets and I just love them compared to scriptlets since they perfectly divide logic and view. But I'm having trouble calling instance methods in my JSP page.
I have the following JSP page:
<%# page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!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>
<c:forEach items="${stringarray}">
${stringarray}
<br/>
</c:forEach>
</body>
</html>
And the following Servlet:
package controller;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class Servlet
*/
#WebServlet("/Servlet")
public class Servlet extends HttpServlet
{
private static final long serialVersionUID = 1L;
/**
* Default constructor.
*/
public Servlet()
{
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
String[] strarray = new String[5];
strarray[0] = "zero";
strarray[1] = "one";
strarray[2] = "two";
strarray[3] = "three";
strarray[4] = "four";
request.setAttribute("stringarray", strarray);
request.getRequestDispatcher("index.jsp").forward(request, response);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
// TODO Auto-generated method stub
}
}
Why can't I call the arrays methods with the dot separator in my JSP page?!
I think what you're looking for is the following:
<c:forEach var="stringElement" items="${stringarray}">
${stringElement}
<br/>
</c:forEach>
The c:forEach tag loops over each element in the ${stringarray}, but to access each item, you have to define a variable. See also the TLD docs

Categories

Resources