Show session history - java

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); }
}

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"));
}
}

Using objects in Session with Servlets and JSP

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.*"%>

J2ee The requested resource is unavailable

Hello I know That this question has been asked before But unfortuanetly I didn t find among the answers proposed the one suitable for me
I m still new with J2ee lookin' forward for ur help
This is my code
login.jsp
<!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>
<form action="" method="post"/>
<br> UserId: <input type="text" name="userId"/>
<br> password<input type="password" name="password"/>
<br><input type="submit"/>
</form>
</body>
</html>
LoginServlet.java
package org.islem.login;
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 org.islem.login.service.LoginService;
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String userId,password;
userId= request.getParameter("userId");
System.out.println(userId);
password= request.getParameter("password");
LoginService loginService= new LoginService();
boolean result= loginService.authenticate(userId, password);
if (result)
{
response.sendRedirect("home.jsp");
return;
}
else
{
response.sendRedirect("login.jsp");
return;
}
}
}
LoginService.java
package org.islem.login.service;
public class LoginService {
public boolean authenticate (String userId,String password)
{
if (password ==null || password.trim() =="") {
return false;
}
else return true;
}
}
Your form action is empty, you should fill it your servlet name in your case it should be like:
<form action="LoginServlet" method="post"/>
I assume you already define your servlet name at your web.xml
You need to specify some controller name within the action:
<form action="LoginServlet " method="post"/>
<br> UserId: <input type="text" name="userId"/>
<br> password<input type="password" name="password"/>
<br> <input type="submit"/>
</form>
Remember: This action specifies where the data submitted by the form will be received.

Problem with jsp/servlet page

I want to create a simple JSP page. I have an EJB, in this there is a session bean.
I have a JSP page and a Servlet, but I have a strange situation.
When I click execute on my page, this turns in a white page and don't give me the result.
I post here my code, can you help me please.
Servlet:
package web;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import javax.naming.*;
import javax.servlet.*;
import javax.servlet.*;
import javax.servlet.http.*;
import ejb.calc;
/**
* Servlet implementation class calcServlet
*/
public class calcServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public calcServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session=request.getSession(true);
RequestDispatcher rd=this.getServletContext().getRequestDispatcher("/index.jsp");
float a=Float.parseFloat(request.getParameter("n1"));
float b=Float.parseFloat(request.getParameter("n2"));
char oper=request.getParameter("oper").charAt(0);
float result=0;
try {
Context ctx=new InitialContext();
// call the calcImpl class of the SimpleCalculator EJB with the mappedName
calc cl=(calc) ctx.lookup("Firstcalc");
switch(oper){
case '+': result=cl.sum(a, b); break;
case '-': result =cl.minus(a, b); break;
case '*': result =cl.mult(a, b); break;
case '/': result =cl.div(a, b); break;
}
session.setAttribute("result",result);
request.setAttribute("a", a);
request.setAttribute("b", b);
}
catch(NamingException e)
{session.setAttribute("erreur: ",e.getMessage());
}rd.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
}
}
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>
<h2> <b> Hello World To The Simple Calculator </b> </h2> <% float a=2,b=1; if (request.getAttribute("a")!=null) a=Float.parseFloat(request.getAttribute("a").toString()); if( request.getAttribute("b")!=null) b=Float.parseFloat(request.getAttribute("b").toString()); %> <form method="post" action="calcServlet"> <b>Number 1:</b><input type='text' name='n1' value="<%=a%>" /> <br/>
<b>Number 2:</b><input type='text' name='n2' value="<%=b%>" /> <br/>
<u><b>Options:</b></u> <br/>
<ul>
<li><b>+</b><input type='radio' name="oper" value='+' checked /></li>
<li><b> -</b><input type='radio' name="oper" value='-' /></li>
<li><b>*</b><input type='radio' name="oper" value='*' /></li>
<li> <b>/</b><input type='radio' name="oper" value='/' /></li> </ul>
<b>-------------------------------------------</b> <br/>
<input type="submit" value="Executer" /> </form>
<font color='blue'><b>Result is: </b> <%=session.getAttribute("result")%> </font> <br/> <font color='red' >Error: <%=session.getAttribute("error")%></font>
</body>
</html>
A JSP will blank out when you use old fashioned scriptlets (those <% %> things) and one of such a scriptlet has thrown an exception while the response has already been committed. It's too late then to display the error page. The browser ends up with a halfbaked HTML page (the HTML generated by JSP is incomplete and the browser will usually go blank). You should read the server logs for the exception and fix the code accordingly.
Unrelated to the actual problem, your approach is pretty clumsy. You don't need scriptlets at all. Just use EL (those ${} things). It has instant access to request parameters. E.g.
<input type="text" name="n1" value="${param.n1}" />
(for extra course points: use JSTL fn:escapeXml() to prevent XSS)
You don't even need to duplicate them as request attributes in the servlet. You should also not store the result as session attribute (it would be shared among all browser windows/tabs in the same session, you don't want to have this for a request based variable). Store it as request attribute
request.setAttribute("result", result);
and access it by EL as follows, it has instant access to page/request/session/application scoped attributes by just its name:
<b>Result is: </b> ${result}
Related questions:
Simple calculator in JSP/Servlet (with optional Ajax)
How to avoid Java code in JSP files

Categories

Resources