I have a JSP page which is not seeing any of the request parameter values when displayed. Originally I tried with passing the parameters from a Servlet, which did not work. Just as a test I also tried calling that JSP from a form on an html page.
What I do in Servlet:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String sampleValue = sampleModel.getMyValue();
request.setAttribute("param", sampleValue);
RequestDispatcher view = request.getRequestDispatcher("samplePage.jsp");
view.forward(request, response);
}
How I call JSP from an HTML page through a form with hidden fields:
<div>
<form action="samplePage.jsp" method="post">
<input name="param" type="hidden" value="sampleValue"/>
<input type="submit" value="Update">
</form>
</div>
Finally what I have on the JSP:
<body>
<p>Some info: ${param}</p>
</body>
As I said the problem is the value of the request attribute "param" which is lets say "sampleValue", does not get rendered on the page.
I have seen lots of examples how this is done and I think my code is correct. Is there any other reason why this may not be working? I am running a maven project with Tomcat 8.5.
EDIT: What I have found out so far is that the problem is not that the Expression language is not working. The request attribute just has no value when it arrives at the JSP.
Please ensure that isELIgnored is false in your jsp page.use bellow tag at the top of your jsp.
<%# page isELIgnored="false" %>
also you can ensure this by ${2 * 4} output is print as 8 on JSP.
Your form is using method=post. Your Servlet code should be located on the doPost method instead of doGet.
For Servlet case, replace ${param} in your samplePage.jsp with
<%=request.getAttribute("param")%>
For JSP case, replace ${param} in your samplePage.jsp with
<%=request.getParameter("param")%>
First, check whether variable sampleValue is capturing the string that you are passing from JSP like below
String sampleValue = sampleModel.getMyValue();
System.out.println(sampleValue);
Related
In my Liferay 6 app I'm able to pass parameter from java to jsp via:
final PortletRequestDispatcher rd = getPortletContext().getRequestDispatcher("view");
request.setAttribute("description", "some description");
rd.include(request, response);
Then I want user to change the description and pass it back to back-end:
<form method="POST" action="${addItem}">
<input name="description"
type="text"
value="${description}"/>
<button type="submit">UPDATE</button>
</form>
Nevertheless when I call then System.out.println("request.getAttribute("description")); , I'm getting null. What am I doing wrong?
Youre passing in the parameter but checking the request attribute (assuming that the outer quotes are a question typo). Based on the information you provided, the initial request attribute was only available in the JSP but not any subsequent servlet. Try
System.out.println(request.getParameter("description"));
<body>
<form action="testServlet.java">
<TABLE border="0" align="center">
<TR height="40">
<TD width="40"><a href="Hoda/testServlet?direction=b"><img
src=<%=request.getAttribute("imgSrc")%> width="40" height="40" /></a>
</TD>
</form>
</body>
SERVLET:
#WebServlet("/testServlet")
public class testServlet extends HttpServlet {
String imgSrc = "red.png";
protected void service(HttpServletRequest reques,HttpServletResponse response) throws ServletException, IOException {
String str = request.getParameter("direction");
if (str.startsWith("b")) {
imgSrc = "black.png";
}
request.setAttribute("imgSrc", imgSrc);
}
}
In my JSP page, I created a cell whose image source I want to get from servlet. I put the link tag to ask servlet for imgSrc, but it does not work . Please show me how to change the imgSrc in JSP page using servlet. I want the JSP to merely show the result, not a dispatch to another page.
here is my code :
You'll have to use the Servlet API's RequestDispatcher to forward from the Servlet to the JSP so that the processing occurs on the same request, otherwise the attribute won't be set. You could probably also use some custom include logic, but typically you'd use the servlet as a "front" and then use the JSP to render the content. Hopefully this makes sense, you should be able to track the APIs down in the Servlet JavaDoc.
Please refer this post may be can help you.
http://ajax911.com/dynamically-display-images-java-servlet-tomcat/
i have a jsp. which calls a servlet on jsp load and display the results in same jsp as below.
Some.jsp
<html>
<jsp:include page="/HelloWorld"/>
<%Iterator itr;%>
<% List data= (List)request.getAttribute("results");
for (itr=data.iterator(); itr.hasNext(); )
{
%>
<TABLE align="center" cellpadding="15" border="1" style="background-color: #ffffcc;">
<TR>
<TD align="center"><%=itr.next()%></TD>
</TR>
</TABLE>
<%}%>
</body>
</html>
in servlet i am storing results in request and using requestdispatcher to invoke the jsp as below.
public class SomeServlet extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException,IOException{
List<String> list = new ArrayList<String>();
//some logic to populate list
request.setAttribute("results", list);
request.getRequestDispatcher("/WEB-INF/Some.jsp").forward(request, response);
}
}
But i am getting below exception while displaying results in jsp:
java.io.IOException: Stream closed
at org.apache.jasper.runtime.JspWriterImpl.ensureOpen(JspWriterImpl.java:202)
at org.apache.jasper.runtime.JspWriterImpl.clearBuffer(JspWriterImpl.java:157)
Please help me..
The JSP includes the servlet, which forwards to the JSP, which includes the servlet, which forwards to the JSP, which includes the servlet, which forwards to the JSP, which includes the servlet, which forwards to the JSP, which includes the servlet, which forwards to the JSP, which includes the servlet, which forwards to the JSP, which includes the servlet, which forwards to the JSP...
You have a serious design issue here. Adopt the MVC principles: all requests go to a servlet (Controller), which loads the Model, and dispatches to the appropriate JSP (View). A view should not include a servlet, and certainly not in a recursive way like this.
You can not give servlet url pattern in jsp:iclude tag. The reason is, it doesnt know whther to call get method or ost method. You should give only jsp path.
This is my first Portlet. I am not getting values inside my servlet. Please, see the program. Inside my custom portlet Java class doView() method, I show a JSP page
public void doView(RenderRequest renderRequest, RenderResponse renderResponse)
throws IOException, PortletException {
include(viewJSP, renderRequest, renderResponse);
}
Inside the view.jsp page, I refer to a servlet to receive the values:
<form action="formServlet" method="post">
<h1>Please Login</h1>
Login: <input type="text" name="login"><br>
Password: <input type="password" name="password"><br>
<input type=submit value="Login">
</form>
Inside web.xml file:
<servlet>
<servlet-name>formServlet</servlet-name>
<servlet-class>FormServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>formServlet</servlet-name>
<url-pattern>formServlet</url-pattern>
</servlet-mapping>
Inside my servlet
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String name = (String)request.getParameter("login");
System.out.println("The Name is "+name);
}
But I don't know why the servlet is not being called.
NOTE: This is an answer to a somewhat complicated question. If you are trying to learn the basics of portlet creation, I posted a better answer in another question.
You are submitting a form using the POST method but your servlet just implements doGet(), which serves the GET method. You should either submit your form using GET or implement the doPost() method (which would be preferable in other situations).
Also, it is necessary to precede the <url-pattern> content by a slash if it is an absolute pattern. That is, it should be
<url-pattern>/formServlet</url-pattern>
instead of
<url-pattern>formServlet</url-pattern>
That said, forget servlets now!
You are doing it in one of the worst ways. It is really a bad idea to write a portlet which calls a servlet. After a long time working with Liferay I can imagine situations where it would be more or less reasonable, but it is not here and will not be most of the times.
So, what should you do? You should submit your form to an action URL. To do it, first include the portlet taglib in your JSP:
<%# taglib uri="http://java.sun.com/portlet" prefix="portlet" %>
Now, replace the action of your form by the <portlet:actionURL />. This tag will be replaced by a special URL generated by the portal. Also, precede each input name with the tag <portlet:namespace />; your <input type="text" name="login"> should become <input type="text" name="<portlet:namespace />login"> then. This tag will be replaced by a string which is associated with only your portlet; since you can have a lot of portlets in a page, each input should specify from what portlet it comes from. This is the final result:
<form action="<portlet:actionURL />" method="post">
<h1>Please Login</h1>
Login: <input type="text" name="<portlet:namespace />login"><br>
Password: <input type="password" name="<portlet:namespace />password"><br>
<input type=submit value="Login">
</form>
Now you are going to submit your data correctly - but how to get the submitted data? It certainly is not necessary to use a servlet! Instead, add to your custom portlet class a method called processAction(). This method should return void and receive two parameters, of the time javax.portlet.ActionRequest and javax.portlet.ActionResponse. This is an example of an empty processAction():
public void processAction(ActionRequest request, ActionResponse response) {
// Nothing to be done for now.
}
When a request to an action URL (as the one generated by <portlet:actionURL />) is sent to the server, it is firstly processed by the processAction() method and then by doView(). Therefore, the code you would write in your servlet should be put in your processAction(). The result should be then:
public void processAction(ActionRequest request, ActionResponse response) {
String name = (String)request.getParameter("login");
System.out.println("The Name is "+name);
}
Try it and you will see that it will work well.
yyy - Here's the answer to your comment:
In your JSP page you'll need to add the following for each of the actions you want that portlet to perform:
<portlet:actionURL var="addUserURL">
<portlet:param name="<%= ActionRequest.ACTION_NAME %>" value="addUser" />
</portlet:actionURL>
<form method="post" action="<%= addUserURL %>">
Then in your com.test.Greeting portlet you'd have for each of these:
public void addUser (ActionRequest actionRequest, ActionResponse actionResponse) {}
Does this answer your question?
Also it's usually best to start a new question rather than adding a comment.
If I leave the action attribute out of my form so it posts back to the same JSP I have no trouble reading the request parameters. However when I add an action attribute to handle the form with a separate JSP, the request parameters are null. Here's a short example (FormTest.jsp) that illustrates how I'm reading the request.
<HTML>
<HEAD>
<TITLE>FormTest.jsp</TITLE>
</HEAD>
<BODY>
<H3>Using a Single Form</H3>
<%
String command = request.getParameter("submit");
%>
You clicked <%= command %>
<FORM NAME="form1" METHOD="POST">
<INPUT TYPE="SUBMIT" NAME="submit" VALUE="First">
<INPUT TYPE="SUBMIT" NAME="submit" VALUE="Second">
<INPUT TYPE="SUBMIT" NAME="submit" VALUE="Third">
</FORM>
</BODY>
</HTML>
The above page works as expected. Initially the page prints You clicked null along with the form. Clicking any of the three buttons changes the message to You clicked First, etc.
Now I change just one line in the page above to add the action attribute:
<FORM NAME="form1" METHOD="POST" ACTION="FormHandler.jsp">
I added a separate JSP to my project to read the request parameter as follows:
<HTML>
<HEAD>
<TITLE>FormHandler.jsp</TITLE>
</HEAD>
<BODY>
<H3>Form Handler</H3>
<%
String command = request.getParameter("submit");
%>
You clicked <%= command %>
</BODY>
</HTML>
I expected the new FormHandler.jsp to just print out which button was pressed on the other page, but it seems the request parameter is always null.
What could be interfering with the request parameters being sent to a separate JSP?
Update:
This project has a JSF configuration file as well. I changed the action attribute to ACTION="FormHandler.faces" and the code above works but I don't quite understand why yet. Here's the method that's redirecting requests that end in .jsp.
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws ServletException, IOException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
String uri = request.getRequestURI();
if (uri.endsWith(".jsp")) {
int length = uri.length();
String newAddress = uri.substring(0, length - 3) + ".faces";
response.sendRedirect(newAddress);
}
else { //Address ended in "/"
response.sendRedirect("login.faces");
}
}
Now I guess I need to know 1) how to figure out if this is the source of the problem, and 2) is there a way to preserve the request parameters when the response is redirected?
There's also an entry in the web.xml configuration file for this project that sets a filter mapping.
<filter-mapping>
<filter-name>faces-redirect-filter</filter-name>
<url-pattern>*.jsp</url-pattern>
</filter-mapping>
I suppose (but it's probably clear by now that I'm new to JSF, so someone correct me if I'm wrong) that using the .faces extension in my action attribute bypasses this filter.
POST parameters are lost because sendRedirect() sends a 302 Moved Temporarily redirect, which instructs the browser to load the specified page with GET request.
To retain parameters you need to use 307 Temporary Redirect instead - it instructs the browser to repeat a POST request to the specifed URI:
response.setHeader("Location", newAddress);
response.setStatus(HttpServletResponse.SC_TEMPORARY_REDIRECT);