Session can't find a variable from previous sessions - java

I'm working with multiple files and servlets and I pass a variable as a flag in the following way :
managerPage.jsp :
<fieldset>
<legend>To open a new account</legend>
<form action="employeeTransaction1">
<input type="hidden" name="hdField" value="managerFlagOn" />
<input type="submit" value="Press here to continue" />
</form>
</fieldset>
Now I go to employeeTransaction1 servlet:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
HttpSession session = request.getSession();
synchronized(session)
{
String hiddenValue = request.getParameter("hdField");
// then the redirection was made from a Manager's page
if (hiddenValue.equals("managerFlagOn") == true)
{
session.setAttribute("managerQuery1", hiddenValue);
}
// forwards to the page employeeOpenNewAccount.jsp
request.getRequestDispatcher("/WEB-INF/results/employeeOpenNewAccount.jsp").forward(request, response);
}
}
Here I grab the hidden value and place it under the name managerQuery1 .
Then I'm being forwarded to employeeOpenNewAccount.jsp:
employeeOpenNewAccount.jsp:
<!-- EMPLOYEE OP 1 - open a new account -->
<!DOCTYPE html>
<html>
<head><title>Employee's transaction page - open a new account</title>
<link rel="stylesheet"
href="./css/styles.css"
type="text/css"/>
</head>
<body>
<h1>Employee's transaction page!</h1>
<h1>
Open a new Bank account
</h1>
<!-- from here redirecting to the servelet that's called "employeeOperation1" -->
<fieldset>
<legend>Please fill the followings</legend>
<form action="employeeOperation1">
First-name : <input type="text" name="firstName"><br>
Last-name : <input type="text" name="lastName"><br>
Address : <input type="text" name="address"><br>
ID-number : <input type="text" name="idNumber"><br>
User-name : <input type="text" name="userName"><br>
Password : <input type="text" name="password"><br>
<input type="submit" value="Register">
</form>
</fieldset>
</body></html>
And now I go to employeeOperation1 servlet :
employeeOperation1:
#WebServlet("/employeeOperation1")
public class EmployeeServlet1 extends HttpServlet {
private static final long serialVersionUID = 1L;
HttpSession session = request.getSession();
synchronized(session)
{
String manager = request.getParameter("managerQuery1"); // the value is null
...
...
}
}
And now the value of manager after grabbing managerQuery1 is null .
Why is it null ? I thought that session-variables are supposed to stay until the end of the program .
Thanks

You set the managerQuery1 in a session attribute, and try to fetch it from a request parameter.
fetch it from the session, and you're done.
String manager = session.getAttribute("managerQuery1");

String manager = session.getAttribute("managerQuery1");
I think you need to cast into String
String manager =(String) session.getAttribute("managerQuery1");
You can follow to get more idea.
javax.servlet.http.HttpSession session = request.getSession();
Once you have done that, you can set a session object like this:
session.setAttribute("name","value");
To retrieve the value, do this:
String foo = (String) session.getAttribute("name");

Related

How to run Servlet before running JSP page?

Goal:
I have only one page and when page loads, it should run the query from servlet and display all values on index.jsp page.
Existing problem:
when i am submitting the page from "Submit" button to another page, it works fine but when i load page index.jsp with values, its gives NullPointerException because servlet didn't run before the index.jsp page.
My Servelet:
public class GetStudentController extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
StudentDao sd = new StudentDao(); // model
StudentInfo si = sd.getInfo();
request.setAttribute("si", si);
RequestDispatcher rd = request.getRequestDispatcher("display.jsp");
rd.forward(request, response);
}
}
my JSP:
<body>
<form action="displayStud"> <--my servlet controller name -->
Student id <input type="text" name = "sid">
<button name="test" type="submit"">Primary Button</button>
</body>
</html>
<button type="submit" class="btn btn-primary" name="action" formaction="ddd" value="find">Test2</button>
<!-- <input type ="submit" value ="Submit"> -->
</form>
StudentDao has query in there
Again:
I just want it to run the same code on page load and all data should load(without click on submit)
Thanks for the help
You can use the value set in the request scope using jstl or expression language.
request.setAttribute("si", si);
Something like:
Student id <input type="text" name = "sid" value="${requestScope.si.id}">

How to get values from JSP to Servlet in <option> [duplicate]

This question already has answers here:
How to transfer data from JSP to servlet when submitting HTML form
(4 answers)
Closed 5 years ago.
I'm writing a jsp file code that creates dropdown menus dynamically; the entries on the menus are dinamically inserted after a query executed in dao.QueriesDAO java class. Additionally, there is a search bar.
I want all the selected voices from the menus, plus the string inserted in the search bar, are sent to the servlet SearchServelt.java, contained in src/controller/SearchServlet.java, after the Search button it's clicked.
JSP file (in WebContent/jsp/homeView.jsp):
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" import="java.util.List, java.util.Iterator" %>
<!DOCTYPE html>
<html>
<head></head>
<body>
<jsp:include page="_header.jsp"></jsp:include>
<jsp:include page="_menu.jsp"></jsp:include>
<div style = "text-align: center">
<form action="/Search" method="post">
Search <input name="search"> <input type="submit" value="Search"/>
</form>
</div>
<div style = "text-align: center">
<%-- select value brand from drop-downlist --%>
<div style = "display: inline-block">
<%
List<String> brands = dao.QueriesDAO.getBrands();
Iterator<String> iterBrands = brands.iterator();
%>
<form name="f1" method="post" action="/Search">
Select brand:
<select name="brand">
<option value="All">All</option>
<% while(iterBrands.hasNext()){ %>
<option><%= (String) iterBrands.next() %></option>
<% } %>
</select>
</form>
</div>
<%-- select value of instrument type from drop-downlist --%>
<div style = "display: inline-block">
<%
List<String> instrumentTypes = dao.QueriesDAO.getInstrumentType();
Iterator<String> iterInstrumentTypes = instrumentTypes.iterator();
%>
<form name="f2" method="post" action="/Search">
Select instrument type:
<select name="instrumentType">
<option value="All">All</option>
<% while(iterInstrumentTypes.hasNext()){ %>
<option><%= (String) iterInstrumentTypes.next() %></option>
<% } %>
</select>
</form>
</div>
<%-- select value used from drop-downlist --%>
<div style = "display: inline-block">
<form name="f3" method="post" action="/Search">
Select used status:
<select name="used">
<option value="0">All</option>
<option value="false">Not used</option>
<option value="true">used</option>
</select>
</form>
</div>
<%-- select value product type from drop-downlist --%>
<div style = "display: inline-block">
<form name="f4" method="post" action="/Search">
Select product type:
<select name="productType">
<option value="All">All</option>
<option value="2">Professional product</option>
<option value="1">Scholastic product</option>
<option value="0">Classic product</option>
</select>
</form>
</div>
</div>
<jsp:include page="_footer.jsp"></jsp:include>
</body>
</html>
Servlet file:
package 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;
#WebServlet(urlPatterns = { "/search"})
public class SearchServlet extends HttpServlet {
private static final long serialVersionUID = -1953084286713579746L;
public SearchServlet() {
super();
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String searchParameters= request.getParameter("search");
String brandSelected= request.getParameter("brand");
String selectedInstrumentType= request.getParameter("instrumentType");
String selectedUsedStatus= request.getParameter("used");
String selectedProductType= request.getParameter("productType");
System.out.println("Inserted: " + searchParameters + ", "
+ brandSelected + ", "
+ selectedInstrumentType + ", "
+ selectedUsedStatus + ", "
+ selectedProductType + ".");
}
}
I want to be able to work with the values from the servlet and then eventually call other java methods and/or jsp files.
I don't know what is wrong, because I've seen similar questions on stackoverflow and I utilized the solution proposed.
I'll like to know what do I do of wrong and what should be a good approach to a problem like this, thank you very much.
The homeView.jsp file is called from a different servlet, HomeServlet.java. Should I use that servlet instead of a new servlet SearchServlet.java? What is better?
EDIT:
I resolved with <form action="${pageContext.request.contextPath}/search" method="get"> in the JSP page (and modified in having a single form), and accordingly I changed the SearchServlet.java method from doPost to doGet.
You need to add a form to the search input
Search <input name="search"> <input type="submit" name="submit" value="Search"/>
When the user clicks on the search button, it gets submitted to the post request of the servlet "SearchServlet". There you get the "search" parameter name which will contain the input from the user.
<form action="SearchServlet" method="post">
Search <input name="search">
<input type="submit" value="Search"/>
// here you can add other inputs like brand selected, instrumentType, productType etc...
</form>
Then from the servlet you query the database with the user input and set the results.
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String brandSelected= request.getParameter("search");
//if you add more options in the form you can get those also
//query database and get arraylist of instrumentTypes by brand.
List<String> instrumentTypes = dao.QueriesDAO.getInstrumentType(brandSelected);
//set attribute for jsp
request.setAttribute("instrumentTypes", instrumentTypes);
//add the name of the jsp file you want to view the attribute you just set
RequestDispatcher rd = request.getRequestDispatcher("searchview.jsp");
rd.forward(request, response);
}
}
to view the attribute in JSP, do:
${instrumentTypes}

Predefined Form Fields from database

I am creating an online bank. On login, it created a session for that user. The user than has options to click on different transaction types.So when the user clicks on open an account button, it will go to openAccount.jsp page. I also have a form with a users first name, last name, and email in the openAccount.jsp. When the user clicks on the open account button and is redirected to the openAccount.jsp, I want the form to be prefilled from the database based. I am not sure how? Here is my code so far:
home-page.jsp
<div class="col-md-4">
<form name = "OpenAccount" action="open-account.jsp" id="openaccount">
<p>
<button type="submit" class="btn btn-primary btn-lg">Open Account</button>
</p>
</form>
</div>
open-account.jsp
<!DOCTYPE html>
<html>
<head>
<title>Open Account</title>
</head>
<body>
<h3>Please fill in the details</h3>
<form name="predifinedFields">
First Name: <input type="text" name="firstname" value= <%= request.getAttribute("firstname") %> > <br/><br/>
Last Name: <input type="text" name="lastname" value= <%= request.getAttribute("lastname") %>> <br/><br/>
Email: <input type="text" name="email" value= <%= request.getAttribute("email") %>> <br/><br/>
</form>
<form name="openAccount" action="OpenAccount" method="POST">
Select the type of account:
<select name="accounttype">
<option>Checking</option>
<option>Saving</option>
</select> <br/><br/>
Initial Deposit: $<input type="text" name="deposit"> <br/><br/>
Please check the box if everything above is complete:
Agree <input type="radio" name="agree" value="Agree">
Disagree <input type="radio" name="agree" value="Disagree">
<br/><br/>
<input type="submit" value="submit" name="Submit">
</form>
</body>
</html>
OpenAccount.java
public class OpenAccount extends HttpServlet
{
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
String username = "";
HttpSession session = request.getSession(false);
if(session != null)
{
username = (String) session.getAttribute("username");
Users users = new Users();
users = DBConnection.getUsers(username);
request.setAttribute("firstname", users.getFirstName());
request.setAttribute("lastname", users.getLastName());
request.setAttribute("email", users.getEmail());
//request.setAttribute("username", users.getUsername());
}
// String firstName = (String) request.getParameter("firstname");
// String lastname = (String) request.getParameter("lastname");
String email = (String) request.getParameter("email");
String accountType = (String) request.getParameter("accounttype");
String accept = (String) request.getParameter("agree");
String deposit = (String) request.getParameter("deposit");
if(accept.equals("Agree"))
{
if(accountType.equals("Checking"))
{
DBConnection.newCheckingAccount(email, deposit);
RequestDispatcher dispatcher = request.getRequestDispatcher("home-page.jsp");
dispatcher.forward(request, response);
}
else if(accountType.equals("Saving"))
{
DBConnection.newSavingAccount(email, deposit);
RequestDispatcher dispatcher = request.getRequestDispatcher("home-page.jsp");
dispatcher.forward(request, response);
}
}
else
{
System.out.println("Please modify the changes");
RequestDispatcher dispatcher = request.getRequestDispatcher("open-account.jsp");
dispatcher.forward(request, response);
}
}
}
Database.java
public static Users getUsers(String username)
{
Users user = new Users();
try
{
DBConnection.connectToDB();
String query = "SELECT * FROM userlogin where username=?";
stmt = DBConnection.conn.prepareStatement(query);
stmt.setString(1,username);
ResultSet rs = stmt.executeQuery();
while(rs.next())
{
user.setFirstName(rs.getString("firstname"));
user.setLastName(rs.getString("lastname"));
user.setEmail(rs.getString("email"));
user.setUsername(rs.getString("username"));
user.setPassword(rs.getString("password"));
}
}
catch(Exception e)
{
System.out.println(e);
}
return user;
}
In your case (basic servlet), you should follow this logic :
->browser
->servlet which loads and prepares required data from database into request attributes as you have done and finally forwards to open-account.jsp
->open-account.jsp use request attributes to render dynamically fields with your data retrieved from your database.
For other use cases, try to keep this simple logic :
->browser
->servlet processing ....
->jsp rendering ....
Your form in home-page.jsp should post to the servlet (controller) :
<div class="col-md-4">
<form name = "OpenAccount" action="/OpenAccount" id="openaccount">
<p>
<button type="submit" class="btn btn-primary btn-lg">Open Account</button>
</p>
</form>
</div>
You should rename OpenAccount to OpenAccountServlet (keeping conventions is better) and configure correctly the servlet of OpenAccountServlet in your web.xml (or with annotations).
If you use web.xml file for the servlet configuration, the url posted in the previous jsp (action="/OpenAccount") should match with the value in <url-pattern>/OpenAccount</url-pattern>
The forward should do like that :
getServletContext().getRequestDispatcher("yourRequiredPath/open-account.jsp ").forward(request, response);

Retrieve src data from jsp through form submit

In my jsp:
<form name="frmTest" action="test" method="post">
<input type="submit" value="sub" name="sub" />
<img id="cImg" name="cImg" src="${param.src}">
</form>
In my servlet:
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException{
String imgUrl = req.getParameter("cImg");
I want to retrieve the src data of my image in canvas. It will be in base 64 data URI format. The above will give me null value. How should I go about doing it, any helps will be appreciated.
No you cannot, You can get data with only name attribute.
What you can do is take a hidden variable ,add value to it and get in servlet.
Like
<form name="frmTest" action="test" method="post">
<input type="submit" value="sub" name="sub" />
<img id="cImg" name="cImg" src="${param.src}">
<input type="hidden" name="hiddenSrc" value="${param.src}" />
</form>
in servlet
String hiddenimgUrl = req.getParameter("hiddenSrc");

How to identify form action URI from processAction() method in Portlet class?

I created a form like;
<portlet:actionURL var="myFriendlyURI">
<portlet:param name="action" value="addUser"></portlet:param>
</portlet:actionURL>
<form id="userForm" name="userForm" action="${myFriendlyURI}" method="post">
Name :- <input type="text" name="userName">
<input type="submit">
</form>
In processAction(ActionRequest request, ActionResponse response) method, how can I identify the request URI based on myFriendlyURI?
request.getAttribute("javax.servlet.forward.request_uri").toString()) is giving only "/web/portal/Adduser-PageName".
I just want to check the request just like we are doing in Servlet class ;
if(request.getRequestURI().endsWith("user/add")) { // <form action="user/add" ..... >
System.out.println("Ends with : user/add ");
// do actions here
}
Use this
HttpServletRequest convertReq = PortalUtil.getHttpServletRequest(actionRequest);
HttpServletRequest originalReq = PortalUtil.getOriginalServletRequest(actionRequest);
PortalUtil.getCurrentCompleteURL();
Reference to the link has many examples

Categories

Resources