Session attribute not reflected in JSP - java

So I have jsp one that loads some request params as a session which I access in my second jsp .
My jsp 1 code is :
<jsp:useBean id="Emails" scope="request" class="java.lang.String" />
<%
String email = Emails;
session.setAttribute( "allEmail",email);
%>
<p style="display:block" ><%= session.getAttribute( "allEmail" )%></p>
My jsp 2 code is :
<p style="display:block" ><%= session.getAttribute( "allEmail" )%></p>
Now I can see the <p> in the first jsp populated properly with the data but the paragraph in my second jsp just blank
when I change session.setAttribute( "allEmail",email); to something like session.setAttribute( "allEmail","hello world); I can see the correct value reflected in both paragraphs .
What am I doing wrong ?
the servlet that populates jsp1 has the following request dispatcher
RequestDispatcher dispatch = request.getRequestDispatcher("jsp1");
I think the issue is both the jsp's are initialised at the same time so the session in the second jsp has no value .

As per the above scenario. Since request will hold the session object for sure.
You can try this :-
<p style="display:block" >
<%(String)request.getSession().getAttribute("allEmails"); %>
</p>

What you want to pass here is a String into session scope.
1) You don't require a jsp useBean for this. You can directly set in session scope with scriptlet you currently have.
To use jsp useBean tag, the component class should be of type JavaBean. You are using String class which is immutable.
And so you cannot set any property for String to be used in useBean.
Unfortunately scriptlet error was not captured/not thrown (don't know) when you are assigning with
String email = Emails;
Why it was working when you are setting?
session.setAttribute( "allEmail","hello world");
This is as good as setting:
<%
String email = "hello world";
session.setAttribute( "allEmail",email);
%>
If you want to pass some String property along with other properties if required, define like:
public class YourBean implements java.io.Serializable
{
private String propertyName = null;
public String getPropertyName(){
return propertyName;
}
public void setPropertyName(String propertyName){
this.propertyName = propertyName;
}
}
and then set property as:
<jsp:useBean id="yourBean" class="package.YourBean" scope="bean scope">
<jsp:setProperty name="yourBean" property="propertyName" value="value"/>
...........
</jsp:useBean>

Related

JSTL iterate list

I have this class:
public class Orders{
private Integer id;
private String name;
//getters/setters
}
In controller I pass a List<Orders> to jsp:
#RequestMapping(value = "/orders")
public ModelAndView orders(){
List<Orders> orders = ...//get list from db
//print list in console
orders.forEach(e -> System.out.println(e.getId() + " - " + e.getName()));
//print -> 1 - name1 ; 2 - name2
return new ModelAndView("orders", "orders", orders);
}
In jsp use it like this:
${orders.size()}
<c:forEach items="${orders}" var="order">
<c:out value="${order.getId()}"></c:out>
</c:forEach>
In browser at inspect(html code) looks like this:
"2"
<c:foreach items="[com.web.entity.Orders#21e16dd6,
com.web.entity.Orders#52a33913]" var="order">
<c:out value=""></c:out>
</c:foreach>
I tested in controller by printing list in console and everything is right.
Why in jsp is not printed?
Could you please provide more details (controller code, html page tags ...).
Still I've some point to share with you :
Use always a toString method in your Entity/POJO.
Use order.id instead of order.getId()
Make sure you have JSTL core tag in the top of your HTML page :
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
Try to have a simple c:out tag:
<c:out value="${order.id}"/>

how to get some value from url using jstl

I have two forms those have same-url for action, the following form is on page http://www.domain.com/pre-foo-url, which is
<form:form commandName="some" class="form" action="/app/same-url">
<form:input path="title"/>
<input type="hidden" name="redirect" value="foo"/>
<button>OK</button>
</form:form>
and the other form is on http://www.domain.com/bar/{id}
<form:form commandName="some" class="form" action="/app/same-url">
<form:input path="tile"/>
<input type="hidden" name="redirect" value="bar"/>
<button>OK</button>
</form:form>
two methods in my controller, one for deciding to redirect to
#RequestMapping(value = "/same-url", method = RequestMethod.POST)
public String handleRedirect(#RequestParam("redirect") String redirect) {
if (redirect.equals("foo")) {
return "redirect:/foo";
} else {
return "redirect:/bar/{id}"; // this {id} must get the value from http://www.domain.com/bar/{id}<-- Here
}
}
other method for getting the value of id from return "redirect:/bar/{id}"; and goto /bar/{id} request mapping
#RequestMapping(value = "/bar/{id}", method = RequestMethod.GET)
public String handleBar(#PathVariable Integer id) {
// some logic here
return "go-any-where";
}
Now how can I get value from http://www.domain.com/bar/{id} and set that when I redirect it to redirect:/bar/{id},
I have a solution for your need, first I must point out your need then I will write my answer.
First:
-You need to get the /{id} from http://www.domain.com/bar/{id}, it means you want to get the value of last part of url.
you can get that value adding following code on page http://www.domain.com/bar/{id}
<c:set var="currentPage" value="${requestScope['javax.servlet.forward.request_uri']}"/> <!--This will give you the path to current page eg- http://www.domain.com/bar/360 -->
<c:set var="splitURI" value="${fn:split(currentPage, '/')}"/> <!--This will split the path of current page -->
<c:set var="lastValue" value="${splitURI[fn:length(splitURI)-1]}"/><!--This will give you the last value of url "360" in this case -->
<c:out value="${lastValue}"></c:out> <!--use this to make sure you are getting correct value(for testing only) -->
Scond:
-You have to pass value of /{id} which is got from http://www.domain.com/bar/{id}.
pass this using the form as.
<form:form commandName="some" class="form" action="/app/same-url">
<form:input path="title"/>
<input type="hidden" name="redirect" value="bar"/>
<input type="hidden" name="path-var" value="${lastValue}"/>
<button>OK</button>
<form:form>
At Last:
-You want to be redirected to redirect:/bar/{id}".
this could be done using the method below.
#RequestMapping(value = "/add-category", method = RequestMethod.POST)
public String handleRedirect(#RequestParam("redirect") String redirect, #RequestParam("path-var") String pathVar) {
if (redirect.equals("foo")) {
return "redirect:/foo";
} else {
return "redirect:/bar/" + pathVar;
}
}
Important
This is not the Last/Best solution for the problem above.
there may be other/better solutions to this one.
Add this tag lib <%# taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn"%>, when using any jstl function just as fn:length().
Hope this will work for you.

How to pass parameters from java servlet to html form without the use of jsp [duplicate]

This question already has answers here:
Generate an HTML Response in a Java Servlet
(3 answers)
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 2 years ago.
I want to pass some parameters from my java servlet to my html form to be shown. I have read some things about jsp but I was wondering if I can do it directly, using something like this :
<script> var temp = "${param['CookieServlet0.First_Name']}"; </script>
<input type = "text" name = "First_Name" id = "First_Name" value = "temp" > <br>
where First_Name is a parameter of my servlet CookieServlet0. I know that the code example is wrong, is there a way to fix it so that I won't have to use jsp?
EDIT : ok since there is no way around I am starting with jsp, I've checked what you guys sent about JSTL and I do not need the extras that it offers so I am trying to keep it simple since I am just starting. So I have written the code below but I get java.lang.NullPointerException. It must be something really obvious but I cannot see what I do wrong...all the tutorials I have seen use the exact same commands...
java servlet :
public void doGet( HttpServletRequest request, // reaction to the reception of GET
HttpServletResponse response )
throws ServletException, IOException
{
String First_Name = request.getParameter("First_Name");
String Last_Name = request.getParameter("Last_Name");
String Phone_Number = request.getParameter("Phone_Number");
String Address = request.getParameter("Address");
PrintWriter output;
Cookie cookies[];
cookies = request.getCookies(); // get client's cookies
if ( cookies.length != 0 ) {
String departure = cookies[0].getValue();
String destination = cookies[1].getValue();
}
request.setAttribute("First_Name",First_Name);
String strViewPage="formB.jsp";
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(strViewPage);
dispatcher.forward(request, response);
}
formB.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>
<label for = "First Name"> First Name </label>
<input type = "text" name = "First_Name" id = "First1_Name" value = "${First_Name}"
"> <br>
</body>
</html>
No, you can't do it directly, unless you write your own parser/injector.
However, using beans gets as close as you can get. Just use the <jsp:useBean> and replace the html with the values of the bean's attributes.
A quick google search yielded this site which contains examples on how to use the beans and jsp: http://www.roseindia.net/jsp/simple-jsp-example/UsingBeanScopeApplication.shtml
If you want to use JSTL, as Luiggi mentioned, here is a good website: http://www.journaldev.com/2090/jstl-tutorial-with-examples-jstl-core-tags
Try Using:
RequestDispatcher dispatcher = request.getRequestDispatcher(strViewPage);
Instead of:
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(strViewPage);

Passing servlet values into <div>

on my Java Servlet I have something like this,
request.setAttribute("InfoLog", info);
RequestDispatcher rd = request.getRequestDispatcher("gc.jsp");
and on my jsp page I have a <div>
<div id="box"></div>
Now using Javascript I want to get the servlet values InfoLog and populate that into my div tag, the purpose of this is that I am verifying some conditions in my Javascript function.
How do I get servlet values in Javascript?
In the jsp, you get the value from Servlet as below,
<% String infoLog = (String)request.getAttribute("InfoLog"); %>
and use this infoLog variable in the div as
<div id="box"><%=infoLog%></div>
and in the javascript function particulary in that if condition you can have below code
if(val == "InfoLog")
{
var infoLog = '<%=infoLog%>';
}
Thanks,
Balaji
You can simply get your attribute in your gc.jsp
<div id="box"> <%=request.getAttribute("InfoLog")%> </div>
Then, if you want to get this value in javascript you can write -
var val = document.getElementById("box").innerHTML;

How to translate JSP servlet which calls an object method into JSTL?

I just started to use JSTL for my project, but sorry to say it's really confusing to me.
I originally used Number.java
package com.mycompany
public class Number {
private int total;
public static int add (int x, int y) {
return total;
}
And in showNumber.jsp i could just use
<%#page import= "com.mycompany.Number" %>
and inline use <%= Number.add(5,6) %>
How can I rewrite this part in JSTL?
Is that also possible to import the class Number.java?
I tried so many different things, e.g. <c:out value="${Number}.add(5,6)" />, but still cannot find a solution. Thanks.
Edited:
I use #Victor's approach, and it does work. In my case, I need to reuse other's variable from spring framework, say NumberTwo.java and totalTwo as private variable inside. And added "100" to this totalTwo.
For the src where i need to use it is <spring:param name="secondNumber" value ="${NumberTwo.totalTwo}" />.
However, intutively i used (int) pageContext.getAttribute("NumberTwo.totalTwo"), it always returned me null.
The other workaround is
first <c:set var="result" value="${NumberTwo.totalTwo}" />
then <% String result = (String) pageContext.getAttribute("result"); %>
and then <%= Number.add(result, 100) %>
Unfortunately it's not possible to arbitrarily call methods with JSTL, the function capabilities of JSTL are very limited: http://docs.oracle.com/javaee/5/tutorial/doc/bnalg.html . But it's still possible to use your Number class. Here the workaround:
<%#page import= "com.mycompany.Number" %>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%
pageContext.setAttribute("addResult", Number.add(7, 8));
%>
<html>
<body>
JSP 1.x: Result is: <c:out value="${addResult}" /><br/>
JSP 2.x: Result is: ${addResult}
</body>
</html>
With pageContext.setAttribute() the method result is stored in the page context, and the JSTL tags can access values (attributes) stored in that context.
Note: the second output line "Result is: ${result}" works only with JSP 2 afaik.
You can use the 'usebean' tag as in the following example:
<?xml version="1.0"?>
<jsp:root xmlns:jsp="http://java.sun.com/JSP/Page" version="1.2">
<!-- UseBean.jsp
Copyright (c) 2002 by Dr. Herong Yang
-->
<html><body>
<jsp:directive.page import="CacheBean"/>
<jsp:useBean id="b" class="CacheBean"/>
<jsp:setProperty name="b" property="text" value="Hello world!"/>
Property from my Bean:
<jsp:getProperty name="b" property="text"/>
<br/>
Info from my Bean:
<jsp:expression>b.getInfo()</jsp:expression>
</body></html>
</jsp:root>
Where:
/**
* CacheBean.java
* Copyright (c) 2002 by Dr. Herong Yang. All rights reserved.
*/
public class CacheBean {
private String text = "null";
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public String getInfo() {
return "My JavaBean - Version 1.00"
}
}
CREDIT TO: http://www.herongyang.com/jsp/usebean.html
Please look at EL functions in BalusC's answer at
Hidden features of JSP/Servlet
also
look at "Using Custom Methods in EL" at
http://www.roseindia.net/jstl/jstl-el.shtml
look at Functions at
http://docs.oracle.com/javaee/5/tutorial/doc/bnahq.html

Categories

Resources