Illogical jsp error - java

I want to dispaly a result parameter which return from servlet to jsp after an event happen.
so when i add new user for example a result parameter returns with value that the user has been added successfully , and i want to display the result in jsp page.
i make like this in jsp page
<%String result = String.valueOf(request.getAttribute("result"));%>
<%if (result != null){%>
<%= result%>
<%}%>
THE PROBLEM is that every time i open the page for the first time result prints as null to the browser even i write if not null print result value, where is the problem ? can someone help/

String.valueOf(..) returns "null" (a String with length 4) if the argument is null. So your quick solution would be not to use String.valueOf(..) at all.
However, it is not advisable to use scriptlets and java code like that in your JSPs. Use JSTL and EL instead. Your code would look like this:
<c:if test="${result != null}">
${result}
</c:if>

Related

When do (jsp) scriptlets run their (Java) code?

I was working through a null pointer exception on code like the following:
<%
SessionData session = getSessionData(request);
Webpage webPage = null;
if (session!= null) {
webPage = session.getWebPage();
}
%>
<script type="text/javascript">
//NullPointer happens here, webPage is null when the session is lost
<tags:ComboBox
comboBox="<%=webPage.getComboBox()%>" />
</script>
I was surprised when I could move the ending of if (session!=null to after the javascript, which seems to ignore that code when the session was null.
<%
SessionData session = getSessionData(request);
Webpage webPage = null;
if (session!= null) {
webPage = session.getWebPage();
//} move this to below
%>
<script type="text/javascript">
//NullPointer happens here, webPage is null when the session is lost
<tags:ComboBox
comboBox="<%=webPage.getComboBox()%>" />
</script>
<% } %> //moved to here
Does the scriptlet for the ComboBox tag, inside the brackets, no longer run? I would think it would still try to get the combobox off the webpage, and still end up getting a null pointer. Am I incorrect in thinking that scriptlets all get their values before the code is actually ran?
(just thought I'd mention, there is an included script which redirects the page if there is no session. I get a NullPointer with the first section of code, and correctly redirect with the second section)
A JSP is compiled to a servlet on-the-fly by the servlet container.
This compilation is actually simple kind of inversion:
TEXT1
<% java code %>
TEXT2
<%= java expression %>
TEXT3
That is compiled to:
out.print("TEXT1");
java code
out.print("TEXT2");
out.print(java expression);
out.print("TEXT3");
So when you say:
TEXT1
<% if (true) { %>
TEXT2
<% } %>
TEXT3
You get:
out.print("TEXT1");
if (true) {
out.print("TEXT2");
}
out.print("TEXT3");
The above examples are minified for clarity, e.g. newlines are ignored, the boilerplate servlet setup is not included, and the complexity of tag library execution is not covered.
In short, you are incorrect as to the order in which tag libraries and scriptlets are processed; the JSP compiler first identifies JSP directives, then resolves and renders tag library output, and then converts everything not in a scriptlet into a bunch of static strings written to the page, before stitching the resulting Java file together around the existing scriptlet code, looking something like this:
// start of class and _jspService method declaration omitted for brevity
out.write("<html>\n");
out.write("\t<head>\n");
out.write("\t<title>Example Static HTML</title>\n");
// comment inside a scriptlet block
int x = request.getParameter("x");
pageContext.setParameter("x", x);
out.write("\t</head>\n");
The problem here stems from the fact that Tag Libraries are resolved first, and the code which isolates and evaluates them doesn't care about either scriptlet blocks or the DOM. In your case, the <tags:ComboBox> tag just thinks the scriptlet is a regular string.
What you should be doing instead is exposing the value in your scriptlet to the accessible scope used by the tag library; in the case of JSTL, for example, you need to add it into the page context via pageContext.setAttribute("varName", value).
Check this answer for more details.

is it possible to set page content type on a condition in jsp or to set different content type for a single jsp

I want to display JSON & XML using a single jsp page.
at a time only one attribute will come from the java class.
My code something look like this.
<%
String json = (String) request.getAttribute("userRequestedJsonById");
if (!StringUtility.isNullOrEmpty(json)) {%>
<%=json%>
<% } else { %>
<%
String xml = (String) request.getAttribute("searcherRespondedXmlById");
if(!StringUtility.isNullOrEmpty(xml)) {%>
<%#page contentType="text/xml"%>
<%=xml%>
<%}%>
<%}%>
I am having a plugin called JSONVIEW to display the json properly.which doesn't work if it finds content type xml.
Content type is set only on the condition,jsp is including this content type even condition is not satisfied.
I don't know much how jsp set content type works,is there any other way to do this or to restrict to set content type xml on a particular condition.
Thanks.
Setting the content type needs to be done before printing anything out, so you need to get rid of the pointless opening and closing of tags that causes whitespace to be printed. Then you will use response.setContentType():
<%
String json = (String) request.getAttribute("userRequestedJsonById");
if (!StringUtility.isNullOrEmpty(json))
{
response.setContentType("application/json");
out.print(json);
}
else
{
String xml = (String) request.getAttribute("searcherRespondedXmlById");
if(!StringUtility.isNullOrEmpty(xml))
{
response.setContentType("text/xml");
out.print(xml);
}
}
%>
Its also just cleaner if you're going to use Scriptlets to just keep your code block open and use out.print() rather than opening, closing, and then <%=var%>, and opening again. That's just so unreadable.

how to get a quote value in jsp

Hi i am getting a attribute value using check box dynamically in java server pages.If check box is checked then it give value no-follow else null.
but i want if my value is null then rel also not show in anchor tag. how can i achieve this
my code is
<% String relAttribute = properties.get("./relAttribute","false");
String relAttributeValue=relAttribute.equals("true")?"nofollow":"";%>
<a class="play" title="Play video" target="_top" href="<%=appURL%>" rel="<%=relAttributeValue%>" >
you can check your attribute with JSTL and place the content in the body of the c:if tag
<c:if test="${relAttribute is not empty)">

java if statement to check if object is empty

hi I am new to java and I am creating a jsp and I am using scriplet code. I would like to be able to have my object to not display on the screen when it is empty.
<% if (webApp.getInfo != null) { %> <h6><%=webApp.getInfo()%> <% } %>
Currently it is checking if the object is null but it is still displaying a line on the page when I run the JSP. How can I check to see if webApp.getInfo is empty and not have a line display or test display for those headers?
<c:if test="${!empty str}">
<h6>...</h6>
</c:if>
Note that:
this is meaningful only for strings, not for any object
this is JSTL, which is preferred to scriptlets (from your example)
your objects needs to be set as request attribute.
you only need this if you have additional tags inside the if-clause. If it is only the string that you want to output, there is no need to check - as BalusC noted this is not displayed.
you can trim whitepsaces from the jsp output using configurations provided by your servlet container, or if using servlet 3.0 - via <trim-directive-whitespaces> in web.xml

Getting null values while using request.setAttribute and get

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.)

Categories