servlet not forwarding session attribute to jsp - java

Using embedded tomcat, this code works:
Servlet:
String test = "test";
request.setAttribute("test", test);
request.getRequestDispatcher("/index.jsp").forward(request, response);
JSP:
<%= request.getAttribute("test") %>
It sets the attribute test and then prints it out on the servlet /example's jsp page example.jsp.
However, if I try to set the attribute within the session then I don't get the same result, instead, I get a null when using this:
Servlet:
String test = "test";
request.getSession().setAttribute("test", test);
request.getRequestDispatcher("/index.jsp").forward(request, response);
JSP:
<%= session.getAttribute("test") %>

On the JSP side, you don't need to say request.getSession(), just session.getAttribute();And you had a problem in your Main.java when creating the servlet context (a trick of using embedded Tomcat); you were not getting the context created by adding the webapp to tomcat, you had some other context.
// File base = new File("src/main/webapp");
// context = tomcat.addContext("", base.getAbsolutePath());
// tomcat.addWebapp(null, "/", base.getAbsolutePath());
context = tomcat.addWebapp("/", new File("src/main/webapp").getAbsolutePath());
context.setSessionTimeout(10080);
I commented out your code and changed the context handling and now things work. And a new exception to be caught.
} catch (ServletException | InterruptedException | LifecycleException exception) {

You may want to compare the session id in the servlet and the jsp. If they are different maybe check your session and cookie configuration in tomcat

Related

retrive session attribute and sort it into String [duplicate]

This question already has answers here:
Show JDBC ResultSet in HTML in JSP page using MVC and DAO pattern
(6 answers)
Closed 7 years ago.
I've been a PHP developer but recently need to work on some project using Google App Engine (Java). In PHP I can do something like this (in term of MVC model):
// controllers/accounts.php
$accounts = getAccounts();
include "../views/accounts.php";
// views/accounts.php
print_r($accounts);
I take a look at some demos of Google App Engine Java using Servlet and JSP. What they're doing is this:
// In AccountsServlet.java
public class AccountsServlet extends HttpServlet {
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String action = req.getParameter("accountid");
// do something
// REDIRECT to an JSP page, manually passing QUERYSTRING along.
resp.sendRedirect("/namedcounter.jsp?name=" + req.getParameter("name"));
}
}
Basically in the Java case it's 2 different HTTP requests (the second one being automatically forced), right? So in JSP file I can't make use of the data calculated in the Servlet.
Is there some way I can do it similar to the PHP way?
You will need to set the data retrieved in the servlet in request scope so that the data is available in JSP
You will have following line in your servlets.
List<Account> accounts = getAccounts();
request.setAttribute("accountList",accounts);
Then in JSP you can access this data using the expression language like below
${accountList}
I would use request dispatches instead of the sendRedirect as follows
RequestDispatcher rd = sc.getRequestDispatcher(url);
rd.forward(req, res);
If you can use RequestDispatcher then you can store these values in request or session object and get in other JSP.
Is there any specific purpose of using request.sendRedirect?. If not use RequestDispatcher.
See this link for more details.
public class AccountServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
List<Account> accounts = getAccountListFromSomewhere();
String url="..."; //relative url for display jsp page
ServletContext sc = getServletContext();
RequestDispatcher rd = sc.getRequestDispatcher(url);
request.setAttribute("accountList", accounts );
rd.forward(request, response);
}
}
What you want to do is first define an object to represent the information from getAccounts() - something like AccountBean.
Then in your servlets doPost or doGet function, use the request info to populate your AccountBean object.
You can then store the AccountBean object either in the request, session, or servlet context by using the setAttribute method, and forward the request to the JSP page.
The AccountBean data in your jsp page is extracted using the and tags.
Here might be an example of your servlet:
protected void doPost(HttpServletRequest req, HttpServletResponse resp) {
// get data from request querystring
String accountId = req.getParameter("accountid");
// populate your object with it (you might want to check it's not null)
AccountBean accountBean = new AccountBean(accountId);
// store data in session
HttpSession session = req.getSession();
session.setAttribute("accountBean", accountBean);
// forward the request (not redirect)
RequestDispatcher dispatcher = req.getRequestDispatcher("account.jsp");
dispatcher.forward(req, resp);
}
Then your JSP page would have the following to display the account information:
<jsp:useBean id="accountBean" type="myBeans.AccountBean" />
Your account is <jsp:getProperty name="accountBean" property="status" />
Besides what's mentioned above about using expression lang, you can also pass attributes via request itself. In Servlet's doGet(), we write something like:
Account[] accounts = AccountManager.getAccountList();
request.setAttribute("accountList", accounts );
RequestDispatcher rd = req.getRequestDispatcher(nextJSPurl);
rd.forward(req, resp);
In JSP, we can retrieve the attribute from request:
<%
Account[] accounts= (Account[])request.getAttribute("accountList");
if (accounts.length>0) {
for (Account account: accounts) {
%>
<blockquote>account name: <%= account.getName() %></blockquote>
<%
}
}
%>
import javax.servlet.http.*;
public class AccountsServlet extends HttpServlet {
public void doGet (HttpServletRequest request, HttpServletResponse response) {
try {
// Set the attribute and Forward to hello.jsp
request.setAttribute ("somename", "someValue"); // to save your temporary calculations.
getServletConfig().getServletContext().getRequestDispatcher("/namedcounter.jsp?name=" + req.getParameter("name")).forward(request, response);
} catch (Exception ex) {
ex.printStackTrace ();
}
}
}
In the above code servlet will not create 2 different requests. It will forward, also will retain all data from original request.
request.setAttribute ("somename", "someValue"); // to save your temporary calculations.
This is my understanding of your question - you want to redirect or dispatch to a new JSP page along with the data calculated in Servlet, right? To do so you need to set request attributes before dispatching the request.
You can set attributes using HttpServletRequest object (req.setAttribute("attribute name", "attribute value")). Attribute value can be any Java object.
You can retrieve the value by req.getAttribute("attribute name"). You'll also need to type cast the object while user getAttribute() function.
You can set the data inside java beans and easily access that data onto jsp page when control goes to jsp. set the date in java beans using setters get access those data onto jsp page by including that bean into jsp.
<%#page contentType="text/html"%>
<jsp:useBean id="man" class="beans.Person"/>
<jsp:setProperty name="man" property="*"/>
First Name: <jsp:getProperty name="man" property="firstName"/>
like this you can access as many properties your bean class can have.

how to redirect another jsp page in controller using spring MVC?

in WEB-INF having a Jsp File pls see image I am using Spring mvc with Hibernate Database connection,in my controller having data from database in variable val now how can i redirect to another jsp page with data's
Controller Part:
#RequestMapping(value = "/EditShop" , method = RequestMethod.POST)
public String editShop(HttpServletRequest request,HttpServletResponse response) throws IOException
{
String id=request.getParameter("Id");
try
{
String val=shopService1.editShopinfo(id);
System.out.println("Edit Shop : "+val);
}
catch(Exception e)
{
System.out.println("Edit Shop : "+e );
}
return "redirect:/EditShop.jsp";
}
You can pass data from controller to UI(another JSP page) with the help of ModelAndView in Spring.
new ModelAndView("newJSPPage","aliasNameToBean",originalBean);
newJSPPage - replace with the new JSP file which you need to redirect from the controller.
aliasNameToBean - replace with the alias name which you can access bean data at redirected JSP page.
originalBean - replace with the original bean object name which you have the data.
return "redirect:/EditShop.jsp";
Insted of this you have return View Name like
return "EditShop";
In Spring Execution Flow InternalResourceViewResolver will Take Care to Call Jsp.
you have to set val to HttpSession Object like session.setAttribut("val",valueofField);
Then you get that value In your jsp
session.getAttribute("val");
I Hope it helps.

NullPointerException while retrieving data from the database

When I am trying to retrieve data from database it's showing NullPointerException.
Here is my servlet code:
public class displayData extends HttpServlet {
String query;
Connection conn;
Statement st;
ResultSet res;
ConnectionManager dbconn;
List lst= new ArrayList();
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try
{
dbconn= new ConnectionManager();
conn=dbconn.getConnection();
st=conn.createStatement();
query="select * from reg";
res=dbconn.getResultSet(query, conn);
System.out.println(res);
while(res.next())
{
lst.add(res.getString("uname"));
lst.add(res.getString("password"));
}
res.close();
}catch(Exception e)
{
RequestDispatcher rd= request.getRequestDispatcher("/error.jsp");
rd.forward(request, response);
}
finally
{
request.setAttribute("EmpData", lst);
response.sendRedirect("/success.jsp");
RequestDispatcher rd= request.getRequestDispatcher("/success.jsp");
rd.forward(request, response);
lst.clear();
out.close();
}
}
And Here is JSP Code for Retrieving Data from database using above servlet Code:
<body>
<h1>Employee List</h1>
<% Iterator itr;%>
<% List data = (List) request.getAttribute("EmpData");
for(itr=data.iterator(); itr.hasNext();)
{
%>
<tr>
<% String s= (String) itr.next();%>
<td><%=s%></td>
<td><%=itr.next()%></td>
<td><input type="submit" value="Edit" onclick="editRecord(<%=s%>;)"</td>
<td><input type="submit" value="Delete" onclick="deleteRecord(<%=s%>;)"</td>
<%}%>
</tr>
</body>
Please help me for solving this problem.
After seeing your Servlet code I found multiple issues,Lets go one by one
I am not sure whether you defined your servlet as a servlet or not.
Either do mapping in web.xml or add annotation like this
#WebServlet("/displayData") public class displayData extends
HttpServlet {
In the servlet you don't have doGet and doPost method. So your
method processRequest will not be invoked by the container. either
put doGet and call your service method or rename your service method
to doGet. Reference - Is it mandatory to have a doGet or doPost method?
The disaster you done in try catch finally block. finally will be always called so there is no use writing the redirection code there as it will executed after catch also. In addition to that finally blocks first four lines are causing serious issues. You should not call both sendRedirect and forward one followed by another. Either do sendRedirect or do forward but not both at the same time.
You will get this exception illegalstateexception-cannot-forward-after-response-has-been-committed Reference - java.lang.IllegalStateException: Cannot forward after response has been committed
What to do forward or sendRedirect at last, In this case you have to
use forward as its a server side action. Reference -
Request Attributes not available in jsp page when using sendRedirect from a servlet
Based on your path of jsp do forward. if your success and error
jsp's are directly under Webcontent then do like this
request.getRequestDispatcher("success.jsp");
Change these things and try again if not working let me know

Servlet-Servlet-Jsp redirecting

I'm developing an application in JAVA where a servlet is taking the inputs from a JSP page. After inserting the values in db it will redirect to another servlet. Then the 2nd servlet will dispatch a JSP page with an ArrayList. But I can't redirect from the 2nd servlet to the JSP page. The ArrayList is going to the JSP page but the page is not showing anything. I'm using NetBeans 6.8.
I'll be thankful if anyone can solve this problem.
Code for 1st Servlet:
RequestDispatcher dispatcher = request.getRequestDispatcher("/Servlet1?id="+id);
dispatcher.forward(request, response);
Code for 2nd Servlet:
request.setAttribute("list",list);
String url="test2.jsp";
RequestDispatcher v=request.getRequestDispatcher(""+url+"");
v.forward(request, response);
try this on 2nd servlet ..
request.setAttribute("list",list);
String url="test2.jsp";
RequestDispatcher v=request.getRequestDispatcher(url);
v.forward(request, response);
On jsp page ...
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<head>
<title></title>
</head>
<body>
<c:forEach items="${list}" var="item">
${item}<br>
</c:forEach>
</body>
</html>
public class MySqlConnection {
Connection c;
public Connection getConnection() throws ClassNotFoundException, SQLException {
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/";
String dbName = "ignite292";
String user = "root";
String password = "root";
Class.forName(driver); // You don't need to call it EVERYTIME btw. Once during application's startup is more than enough.
c = (Connection) DriverManager.getConnection(url + dbName, user, password);
return c;
}
public void closeConnection() {
try {
if (!c.isClosed()) {
c.close();
}
} catch (Exception e) {
}
}
}
First things, If you are using any redirect mechanism, It should not be in RequestScope. It must be in Session or Context Scope(Based on your Requirement). So , the resultant code for 2nd Servlet may as follow
request.getSession().setAttribute("list",list);
String url="/test2.jsp";
RequestDispatcher v=request.getRequestDispatcher(""+url+"");
v.forward(request, response);
Try with this Code.
Sankha,
You can add those objects into session object. and you can use that session obj in any jsp and servlet.
suppose you have an arrayList Obj which have some data objects. and you are trying redirecting your servlet to jsp OR servlet to servlet.
eg:-
RequestDispatcher dispatcher = request.getRequestDispatcher("/Servlet1?id="+id);
dispatcher.forward(request, response);
request.setAttribute("list",list); // **Insted of using request object use session implicit object**.
String url="test2.jsp";
RequestDispatcher v=request.getRequestDispatcher(""+url+"");
v.forward(request, response);
Please refer below code to sort out your problem.
RequestDispatcher dispatcher = request.getRequestDispatcher("/Servlet1?id="+id);
dispatcher.forward(request, response);
**session.setAttribute("list",list);**
String url="test2.jsp";
RequestDispatcher v=request.getRequestDispatcher(""+url+"");
v.forward(request, response);
And get this list object by using
List dataList = session.getAttribute("list");
Hope this will help you.

USERNAME PRINTING NULL; javabeans, jsp session

Username is printing NULL, what is the problem here in realtion to the servlet and jsp page. please note i am using javabean here too. i am using same session attribute twice with the bean db.
SERVLET ONE
if(userPassword!=null && userPassword.equals(password)) {
HttpSession session = request.getSession();
BookingBean db = (BookingBean)session.getAttribute("formData"); //use existing session
if(db == null) {
db = new BookingBean(); }
db.setUsername(username);
session.setAttribute("formData", db);
getServletContext().getRequestDispatcher("/BookingForm.jsp").forward(request, response);
} else ......
SERVLET TWO
HttpSession session = request.getSession();
if(!session.isNew()){
db = new BookingBean();
db.setRandom();
db.setAdult(adults);
db.setChildren(children);
db.setOap(oap);
db.setEmail(email);
db.setDate(date);
db.setLocation(loc);
db.setPromo(promo);
db.setTime(time);
db.setfirstName(firstName);
db.setsurName(surname);
db.setTotal();
session.setAttribute("formData", db);
}
JSP PAGE
<jsp:useBean id="formData" class="bean.BookingBean" scope ="session">
</jsp:useBean>
<%BookingBean username = (BookingBean)session.getAttribute("formData");
if(username==null) {
// if session is expired, forward it to login page
%>
<jsp:forward page="Login.jsp" />
<%}%>
<p>Confirmation of Booking for the following user: <%=formData.getUsername()%><p><br><br>
It looks like you are using two different object for your data. Make sure, that you are only using one object. Every servlet should check, if the attribute is already set with a BookingBean instance and use this instance.
Make sure, that you are synchronizing the session object:
synchronized (request.getSession().getId().intern()) {
//dosomething
}
Looks like both your servlets create a new BookingBean when invoked:
db = new BookingBean();
So, when you store it to the session under key "formData", the BookingBean stored by the other servlet gets overwritten. Instead, you need to first check if the session already contains the bean, and create a new one only if there's not one stored in the session.
Here's a simple way to check if the session already has this object:
BookingBean db = (BookingBean)session.getAttribute("formData");
//HttpSession will return null, if there is no object with the given key
if(db == null)
{
db = new BookingBean();
}
//Continue as before...

Categories

Resources