Getting null values while using request.setAttribute and get - java

I need to pass a variable from Admin.java file to index.jsp. I get the value when I print it in Admin.java. I need to pass that value to another variable which needs to be sent to index.jsp. This new variable gets null value.
The code in Admin.java is
public string static rest;
protected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException
{
SemanticSearch semsearch = new SemanticSearch(request.getSession());
semsearch.loadData(REALPATH + RDFDATASOURCEFILE1);
String res=semsearch.searchForUser(userName, password);
System.out.println("The value of res been passed is "+res);
request.setAttribute("rest", res);
System.out.println("The value of rest is "+rest);
request.getRequestDispatcher("index.jsp").forward(request, response);
if(res != null)
{
request.getSession().setAttribute("access", true);
System.out.println("Admin:doGet:login:true");
response.getWriter().write("existsnoadmin");
return;
}
Output:
The value of res been passed is C Language.
The value of rest is null.
As per the questions asked in stack overflow we need to use forward or redirect when we need to send the value to jsp page. But in my case, I am trying to return value from a function so I do not know whether the way I am trying to do in the above code is right or not.
The code in index.jsp is:
if(response=="existsnoadmin")
{
alert(response);
alert("The value obtained by the admin.java is " +request.getAttribute("rest"));
out.println("The value obtained by the admin.java is " +request.getAttribute("rest"));
alert("we have done in index.jsp");
}
The output is that I am getting the alert box which says "existsnoadmin".
But I am not able to get the value of rest here nor in Admin.java.
What is the mistake I have done here? Please help.
Regards,
Archana.

You say that the code in the JSP is this:
if(response=="existsnoadmin")
{
alert(response);
alert("The value obtained by the admin.java is " +request.getAttribute("rest"));
out.println("The value obtained by the admin.java is " +request.getAttribute("rest"));
alert("we have done in index.jsp");
}
I'm having problems understanding what this really means.
If the above code is Java code that appears inside scriptlet tags <% ... %>, then I don't understand how alert(response); is showing you anything. In fact, it should give you a compilation error in the JSP.
On the other hand, if the above is Javascript code that is embedded in the page that the JSP generates, then
request.getAttribute("rest") cannot possibly work ... because the request object that you set the attribute on does not exist in the web browser, and
out.println(...) cannot work because the JspWriter does not exist in the web browser.
Either you have not transcribed the JSP excerpt accurately, or your Java and/or Javascript doesn't make sense.
Based on your comment, I think you need the following.
if(response=="existsnoadmin")
{
alert(response);
alert('The value obtained by the admin.java is ' +
'<% request.getAttribute("rest") %>');
// The value obtained by the admin.java is <% request.getAttribute("rest") %>
}
Or if you want to get rid of the scriplet stuff ...
if(response=="existsnoadmin")
{
alert(response);
alert('The value obtained by the admin.java is ' +
'${requestScope.rest"}');
// The value obtained by the admin.java is ${requestScope.rest"}
}
If you want the stuff that I've turned into a // JS comment to be visible on the page, you been to move it to some content part of the HTML. Currently it is (I assume) inside a <script> element, and therefore won't be displayed.
The key to all of this black magic is understanding what parts of a JSP are seen/evaluated by what:
JSP directives e.g. <# import ...> are evaluated by the JSP compiler.
Stuff inside scriptlet tags e.g. <% ... %>, EL expressions e.g. ${...} or JSTL tags e.g. <c:out ...\> gets evaluated when the JSP is "run".
Anything generated by the JSP (HTML content, embedded Javascript) is displayed / executed in the user's browser after the HTTP response has been received.
Now is it neccessary to use the request.dispatcher....forward command in admin.java.
Your primary servlet can do one of two things.
It can use the request dispatcher to forward the request to your JSP. If it does this it can forward additional values by setting request attributes.
It can open the response output stream and write stuff to it.
It should not attempt to do both! (I'm not sure exactly what will happen, but it is likely to result in a 500 Internal Error.)

Related

How to keep page position after returning a JSP in Spring/MVC

I am working on a platform, with comments, messages etc...
Surprisingly, I can't find the answer anywhere!
I'm trying to keep the same position of the page after a post method, and when I return a jsp from the controller.
The problem is, whenever I send a message for an example, or post a comment, the page returns, but returns in the top position which is annoying and ineffective.
How can I keep the page and scroll at the same position after returning or redirecting from the controller?
I'll post some example code:
#RequestMapping(value = "/{recipient}", method = RequestMethod.POST)
public String chatPost(#PathVariable("recipient") String recipient, #ModelAttribute("message") Message message, Model model, Principal principal) {
Date date = new Date();
message.setCreationDate(date);
Profile recipientObj = profileService.getProfileByUsername(recipient);
messageService.sendMessageTo(message, recipientObj);
return "redirect:/message/" + recipient;
}
I am assuming that the button click is doing an HTTP post to the server. In order to avoid the full page load, you will need to use Javascript on the web page so that the communication to the server is done asynchronously. Based on the response from the server, your javascript code will need to update the page appropriately. This should not affect the positioning of the web page as technically you never left the page.
Before you send the request, save the current scroll position in session storage using js. Then, when the view reloads, use js to retrieve the value from session storage and assign it to the scrollTop property of the document or body/div element.
Note that if you load this js code when the whole document is ready you'll probably see the initial state (scrollTop = 0) before the retrieved value is setted. So, this block of js code must be executed as soon as the element to be scrolled exists.
I cobbled together a js script that maintains page position and does so per page. I jus take the full location href, strip out colons and slashes for good measure, then use that as part of the key in session storage.
<script>
$(window).scroll(function () {
let pageName = location.href.replaceAll('/','').replaceAll(':','');
// console.log('scrolled ' + pageName);
sessionStorage[pageName + '_scrollTop'] = $(this).scrollTop();
});
$(document).ready(function () {
let pageName = location.href.replaceAll('/','').replaceAll(':','');
if (sessionStorage[pageName + '_scrollTop'] != "undefined") {
// console.log('restored ' + pageName);
$(window).scrollTop(sessionStorage[pageName + '_scrollTop']);
}
});
</script>
Use anchor links and redirect the post back to "mypage.jsp#myAnchor"
<a name="myAnchor">Important Section</a>
<section class="important">Javscript is cool!</section>

Servlet not sending parameter to .jsp file

So, I have this Servlet that should send a parameter to a .jsp file:
request.setAttribute("parameter1", new BigDecimal(50));
RequestDispatcher requestDispatcher = request.getRequestDispatcher("/WEB/pages/page1.jsp");
requestDispatcher.forward(request, response);
However, when I try to alert this parameter with some javascript code inside the jsp, I get an empty message. Also, if I print the attribute to the console with Java using JSP Expression, I'm getting null.. So, I think I'm not correctly sending the parameter in this servlet, can someone help me here?
There are two ways you can accomplish this.
Using a JSP expression you would use <%= %> as (notice no ; at the end)
data : [<%= parameter1 %>, Y, Z]
The second and preferred way is to use JSP EL syntax and reference the request attribute directly using ${ } as
data : [${parameter1}, Y, Z]
The first option requires you to pull the attribute out of its scope first. The second doesn't.
BigDecimal parameter1 = (BigDecimal) request.getAttribute("parameter1");
SOLUTION:
I can't really see the difference, but just changing from:
request.setAttribute("parameter1", new BigDecimal(50));
RequestDispatcher requestDispatcher = request.getRequestDispatcher("/WEB/pages/page1.jsp");
requestDispatcher.forward(request, response);
to:
request.setAttribute("parameter1", new BigDecimal(50));
request.getRequestDispatcher("/WEB/pages/page1.jsp").forward(request, response);
allowed the alert(${parameter1}); to display the actual value that I passed, however, I still got null when reading the parameter with java. Also, some javascript code I had to display a chart stopped working.
So, I've tried to pass the parameters by session:
request.getSession().setAttribute("parameter1", new BigDecimal(50));
request.sendRedirect("/WEB/pages/page1.jsp");
This worked fine, now I can get my parameters both with javascript and java in the .jsp file.
It seems that redirecting to a new request using sendRedirect doesn't crash the javascript code in the .jsp file, however, I don't really know why this approach is working face the others, so I apologize for this poor answer, I've never really worked much with servlets and Jsp's but I really appreciate a more conclusive answer than mine, so I get to learn more too.

Get data from servlet to JSP without forward?

I need a double value from my servlet to markup in my JSP. My doGet() is sending back formatted HTML tables with values from an ArrayList, so after I got that working I decided to tackle this part.
Servlet:
//Code getting the tables I need
//Send back the result, this all works good
response.setContentType("text/html");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(returnAsHTML.toString());
What I added to try and get the double value
//Send back the result
double test = 20;
request.setAttribute("Test",test);
response.setContentType("text/html");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(returnAsHTML.toString());
getServletContext().getRequestDispatcher("index.jsp").forward(request,response);
In JSP:
<!-- This variable is unresolved -->
<small>Test : ${Test}</small>
The forwarding seems to crash the whole party. I am new to JSP, I'm sure I am missing something small. I need to keep the response.getWriter() stuff there, it gets a lot of the information I need. Now I just don't know how to get my double values I need as well, because they will be displayed on a whole different part of the page.
You cannot write output to the servletOutputStream and redirect at the same time.
What do you expect from the browser: to display content or to navigate to another page? If the first, don't redirect. If the second, don't display HTML content.
Try using httpsession. Encapsulate whatever object you have using session.setAttribiute().
Then forward it using the sendRedirect() method.
Might be of this kind
HttpSession session=request.getSession();
double test = 20;
session.setAttribute("Test",test);
response.sendRedirect("Index.jsp");
On the JSP page
String s=(String)session.getAttribite("Test");
double d=Double.parseDouble(s);

How do I pass a New line character to JavaScript from my Servlet?

I'm setting the following in the request attribute:
confirmMsg = "REf No: \n 112";
req.setAttribute("confirmMsg", confirmMsg);
I need the above to be displayed like(in alert box) :
Ref No:
112
I'm using the following onload function in my JavaScript to show the message on loading the page.
function onLoad() {
var msg = "${confirmMsg}";
if(msg != null && msg != "") {
alert(msg);
}
}
The above throws a script error? How do I pass the newline character?
The \n needs to be JavaScript-escaped to be put in a JavaScript string literal.
Use commons-lang StringEscapeUtils.escapeECMAScript() to eascape the message, and pass this escaped message to your JSP.
As I mentioned, do not confuse JSP with JavaScript.
What you want to do is output a string message from your JSP/Servlet (JSP is a Servlet) to be used in a JavaScript code block.
To do this your message needs to be encoded for JavaScript, such as using the StringEscapeUtils.escapeECMAScript method described by JB Nizet.
Then you need, in your jsp or servlet creating the response, to output the variable where you want it for the javascript to act upon, for this you do
<%= confirmMsg %>
and not ${} as that is an expression language which is not always available in every jsp.
In short, change from "${confirmMsg}" to <%= confirmMsg %> or <%= (String)request.getParameter("confirmMsg") %> // or request.getAttribute and so on

jsp to servlet communication with parameters from URL, not a form

I'm using netbeans to create a web application that allows a cell phone user to scan a QR code and retrieve a journal's previous/next title information. The take home point is that there's no form that the user will input data into. The QR code will contain the search string at the end of the URL and I want the search to start on page load and output a page with the search results. For now (due to simplicity), my model is simply parsing an XML file of a small sample of MARC records. Oh, to top it off...I'm brand new to programming in java and using netbeans. I have no clue about what javabeans are, or any of the more advance techniques. So, with that background explanation here's my question.
I have created a java class (main method) that parses my xml and retrieves the results correctly. I have an index.jsp with my html in it. Within the index.jsp, I have no problem using get to get the title information from my URL. But I have no clue how I would get those parameters to a servlet that contains my java code. If I manage to get the search string to the servlet, then I have no idea how to send that data back to the index.jsp to display in the browser.
So far every example I've seen has assumed you're getting form data, but I need parameters found, processed and returned on page load...IOW, with no user input.
Thanks for any advice.
Ceci
Just put the necessary preprocessing code in doGet() method of the servlet:
String foo = request.getParameter("foo");
// ...
request.getRequestDispatcher("/WEB-INF/page.jsp").forward(request, response);
And call the URL of the servlet instead of the JSP one e.g. http://example.com/page?foo=bar instead of http://example.com/page.jsp?foo=bar in combination with a servlet mapping on an URL pattern of /page/*.
You can get the url parameter in servlet using request.getParameter("paramName");
and you can pass the attribute to page from servlet using forwarding request from servlet to jsp.
See Also
Servlet wiki page
Bear in mind that your JSP page will compile internally to a servlet. So you can retrieve the string and print it back in the same JSP. For instance assuming you get the string in a parameter called param you would have something like this in your JSP:
<%
String param = request.getParameter( "param" );
out.println( "String passed in was " + param );
%>
One last thing, you mentioned the main method -- that only gets executed for stand alone applications -- whereas you're talking web/JSP :O

Categories