How to use session in JSP pages to get information? - java

I have a JSP page used for editing some user's info. When a user logins to the website, I keep the information in the session, then in my edit page I try the following:
<%! String username=session.getAttribute("username"); %>
<form action="editinfo" method="post">
<table>
<tr>
<td>Username: </td><td> <input type="text" value="<%=username %>" /> </td>
</tr>
</table>
</form>
but it gives error saying session cannot be resolved. What can I do about it?

JSP implicit objects likes session, request etc. are not available inside JSP declaration <%! %> tags.
You could use it directly in your expression as
<td>Username: </td>
<td><input type="text" value="<%= session.getAttribute("username") %>" /></td>
On other note, using scriptlets in JSP has been long deprecated. Use of EL (expression language) and JSTL tags is highly recommended. For example, here you could use EL as
<td>Username: </td>
<td><input type="text" value="${username}" /></td>
The best part is that scope resolution is done automatically. So, here username could come from page, or request, or session, or application scopes in that order. If for a particular instance you need to override this because of a name collision you can explicitly specify the scope as
<td><input type="text" value="${requestScope.username}" /></td> or,
<td><input type="text" value="${sessionScope.username}" /></td> or,
<td><input type="text" value="${applicationScope.username}" /></td>

Use
<% String username = (String)request.getSession().getAttribute(...); %>
Note that your use of <%! ... %> is translated to class-level, but request is only available in the service() method of the translated servlet.
See how JSP code is translated to a servlet.

The reason why you are getting the compilation error is, you are trying to access the session in declaration block (<%! %>) where it is not available. All the implicit objects of jsp are available in service method only. Code of declarative blocks goes outside the service method.
I'd advice you to use EL. It is a simplified approach.
${sessionScope.username} would give you the desired output.

Suppose you want to use, say ID in any other webpage then you can do it by following code snippet :
String id=(String)session.getAttribute("uid");
Here uid is the attribute in which you have stored the ID earlier. You can set it by:
session.setAttribute("uid",id);

<%! String username=(String)session.getAttribute("username"); %>
form action="editinfo" method="post">
<table>
<tr>
<td>Username: </td><td> <input type="text" value="<%=username %>" /> </td>
</tr>
</table>
add <%! String username=(String)session.getAttribute("username"); %>

You can directly use (String)session.getAttribute("username"); inside scriptlet tag ie <% %>.

form action="editinfo" method="post">
<table>
<tr>
<td>Username:</td>
<td>
<input type="text" value="<%if( request.getSession().getAttribute(" parameter_whatever_you_passed ") != null
{
request.getSession().getAttribute("parameter_whatever_you_passed ").toString();
}
%>" />
</td>
</tr>
</table>
</form>

Related

jsp form,servlet doesn't get parameters

I have form in jsp
<table border="1">
<c:forEach items="${sessionScope.proizvodList}" var="proiz">
<tr>
<td>${proiz.sifra}</td>
<td> ${proiz.naziv}</td>
<td>${proiz.boja}</td>
<td>${proiz.dimenzije}</td>
<td>${proiz.tezina}</td>
<td><form action="KupiServlet" method="get">
<input type="text" name="kolicina"/>
<input type="hidden" name="id" value="${proiz.sifra}"/>
<input type="submit" value="Kupi"/>
</form>
</td>
</tr>
and in servlet in doGet method,i have
String id=request.getParameter("id");
String kol=request.getParameter("kolicina");
When I run this,i got error that both id and kol are null,so i guess servlet doesn't get these parameters..but i think that my form looks good..Does someone have idea why this happens?Thanks in advance!
Check this link - you cannot have a form inside a form.
Is it valid to have a html form inside another html form?

On refreshing jsp page got submited again

I have created simple jsp servlet project on that when i submitting jsp form it insert data to specified table but after that when i refersh same jsp form get submitted and same data inserted to table..
ItemUnit.jsp
<form method="POST" action='ItemUnitHandler' name="frmAddUser">
<input type="hidden" name="action" value="insert" />
<table style="width:95%;margin-top:70px;" align="center">
<tr>
<td style="width:10%"> </td>
<td style="width:30%" align="right">Item Unit :</td>
<td style="width:2%"> </td>
<td style="width:40%" align="left"><input type="text" name="itemUnitName" style="width:200px;" /></td>
<td style="width:18%"> </td>
</tr>
<tr><td colspan="5"> </td></tr>
<tr>
<td colspan="5" align="center">
<input type="submit" class="button-2" value="Insert"></input>
<input type="reset" class="button-2" value="Reset"></input>
</td>
</tr>
</table>
</form>
Servlet post method code..
String action = request.getParameter("action");
System.out.println("action :action action : "+action);
if(action == null)
{
redirect = "ItemUnit.jsp";
}
else if(action.equalsIgnoreCase("insert"))
{
ItemUnit objItemUnit = new ItemUnit();
// System.out.println("request.getParameter : "+request.getParameter("itemUnitName"));
objItemUnit.setItemUnit(request.getParameter("itemUnitName"));
dao.addItemUnit(objItemUnit);
redirect = "ItemUnit.jsp";
}
please help me out from this problem...
Ideally, you should land on a static result page, instead of displaying the input form again. The idea is to force the browser to switch to a new URL so that a refresh will not re-trigger another data update. This is the simplest fix.
But if you prefer to use the same screen, you should use a hidden token. You must record some state since you want to differentiate 2 requests from one another: first and second request (the refresh).
Within your logic, plant a token the first time you display the input form. On any incoming request from the same session, check if you have used the token already and use it to determine if this is a second-time request. The diagram below will illustrate it further.
Setup
Processing

How to edit fields of a table?

I have a table to show a long list of items, I am wondering how I can edit the fields and submit the form to update them?
<form name="edit" method="POST" action="edit">
<table border="4">
<tbody>
<c:forEach items="${basket.items}" var="item">
<tr>
<td>
<input name="item.id" value="${item.id}"/>
</td>
<td>
<input label="Price" value="${item.product.price}"/>
<br/>
</td>
</tr>
</c:forEach>
</tbody>
</table>
this is a new one
<input id="edit" type="submit" name="edit" value="Edit"/>
</form>
You are using Struts2, with JSTL and EL instead of Struts Tags and OGNL... is there a particular reason that forces you to drop most of the framework mechanics ?
That said, your inputs aren't valid (no type specified) and the "this is a new one" sentence in the HTML seems to indicate the willing to insert a new row, instead of editing the existing entres. Your description and your code seem to ask two different things... to insert a new one, just make a call to another method of the action (or another action) called "add" instead of "edit", sending one single element and adding it to the collection. No need to use AJAX here...
If instead, the question is really:
how I can edit the fields and submit the form to update them ?
this is the way:
<s:form method="POST" action="edit">
<table border="4">
<tbody>
<s:iterator value="basket.items" var="item" status="ctr">
<tr>
<td>
<s:textfield name="item[%{#ctr.index}].id" />
</td>
<td>
<s:textfield name="item[%{#ctr.index}].product.price" />
</td>
</tr>
</s:iterator>
</tbody>
</table>
<s:submit value="Edit"/>
</form>
I would suggest you make an AJAX call using jquery to update the new one. And then in the success handler you can append the new line to the existing table. Before doing that you need to give your table proper ids so that its easier to use JQUERY.
var newLine = document.createElement("tr");
var cellName = document.createElement("td");
$(cellName).text("itemId");
$(newLine).append(cellName);
// similarly create other td's
$("#modelTable").append(newLine);// replace modelTable by the id of your table

Spring MVC - Submit an Object from JSP

I have a JSP that presents a list of customers (ArrayList searchResults). I want to be able to pick one of those, and submit it to a Spring MVC controller. However, it appears that I cannot pass the selected object, only a property of it, such as customerId. I really need to pass the entire object.
Is there a standard way to do this in Spring 3.x?
<c:forEach items="${searchResults}" var="searchResult">
<tr>
<td><c:out value="${searchResult.customerId}" /></td>
<td><c:out value="${searchResult.firstName}" /></td>
<td><c:out value="${searchResult.lastName}" /></td>
<td>
<form method="POST" ACTION="./customercare">
<input type="SUBMIT" value="Select This Customer"/>
<input type="hidden" name ="searchResult" value="${searchResult}"/>
</form>
</td>
</tr>
</c:forEach>
You can use Spring's form taglib instead of plain <form> to post back to a Spring MVC Controller and then it will Bind the values back to the model you specify.
<form:form method="post" action="addContact.html">
<table>
<tr>
<td><form:label path="firstname">First Name</form:label></td>
<td><form:input path="firstname" /></td>
</tr>
...
#RequestMapping(value = "/addContact", method = RequestMethod.POST)
public String addContact(#ModelAttribute("contact")
Contact contact, BindingResult result) {
See this Post: http://viralpatel.net/blogs/spring-3-mvc-handling-forms/
You might want to consider giving id to each and nested tags to differentiate between row that you want to POST
<c:forEach items="${searchResults}" var="searchResult">
<tr>
....
<form:form id="${searchResults.key}-form" method="POST" ACTION="./customercare">
<form:input id="${searchResults.key}-btn" type="SUBMIT" value="Select This Customer"/>
<form:input id="${searchResults.key}-hidden" type="hidden" name ="${searchResults.key}" value="searchResult['${searchResults.key}']"/>
</form:form>
</tr>
On the backend side you will have to write the controller as suggested by #PatBurke
You could have 1 form per customer with a lot of hidden inputs in. When that customer is selected you can POST that form. Spring can then bind all the hidden inputs to your customer object.
(Generally, I would just send the id only and load the customer info, as an entity, from a Database. However, I assume you must have a good reason for not wanting to do this)

In tag <td></td> DOUBLE_WHITESPCE in query href

I have a very strange problem.
<table border ="1">
<tbody>
<c:forEach var="question" items="${questions}">
<tr>
<td>
${question.getQuestion()}
</td>
<td>
<c:forEach var="answer" items="${question.getAnswers()}">
<input type="checkbox" name ="user_answer" value="${answer.getAnswer()}">
${answer.getAnswer()}
<br />
</c:forEach>
</td>
<td>
<a href="/TutorWebApp/controller?command=edit_qestion&question=${question}">
Edit
</a>
</td>
</tr>
</c:forEach>
</tbody>
</table>
But If I use in I get next error
But if I don't use tag <a> in <td> it's OK. I don't have any ideas.
Thanks
I think this is just a bug/limitation of your editor. Try deploying your JSP and see if it works as expected or not.
That said, if your question contains characters that must be URL and/or HTML escaped, your HTML code will be invalid. You should use the c:url tag to avoid that:
<c:url var="editQuestionUrl" value="/TutorWebApp/controller">
<c:param name="command" value="edit_question"/>
<c:param name="question" value="${question}"/>
</c:url>
<%-- now the params are url-encoded --%>
Edit
<%-- now the query string is HTML-escaped --%>
You need to encode your question text (or whole URL) here by calling URLEncoder#encode()
You can look at this Q&A on how to encode a URL in JSTL.
Alternatively you can try calling JSTL's escapeXml function on your question text.
try replacing this line
<a href="/TutorWebApp/controller?command=edit_qestion&question=${question}">
with
<a href="/TutorWebApp/controller?command=edit_qestion&question='${question}'">

Categories