<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/
Related
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);
I have a servlet and a jsp page. The jsp page contains a form which the end user will fill out.
<html>
<head>
<title>Please log in to your profile</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/login_servlet" method="post">
Email: <input type="text" size="5" name="email"/>
Password: <input type="text" size="5" name="password"/>
<input type="submit" value="Sign In" />
</form>
</body>
</html>
I will then use a doPost() method in the servlet because the form has a post method. I get the parameters in the servlet so I can print then out to the console.
#WebServlet("/login_servlet")
public class LoginServlet extends HttpServlet {
#Override
public void doPost(HttpServletRequest req,
HttpServletResponse resp) throws ServletException, IOException {
String email = req.getParameter("email");
String password = req.getParameter("password");
System.out.println("Email: " + email);
System.out.println("Password: " + password);
}
}
When I try visit the URL which is http://localhost:8080/StudentPortal/login_servlet I get this error; HTTP Status 405 - HTTP method GET is not supported by this URL with the description that "The specified HTTP method is not allowed for the requested resource."
I'm close to being blocked from asking anymore questions. So please before this is marked as duplicate, I want you to know that I have looked at similar questions and have followed the advice given to no avail.
I have to learn servlets because I'm been put on a Spring project for work soon.
When you visit your url, you are using get method.
And in your servlet you have declared only doPost method.
Try to use postman extension for chrome to use other http methods.
*Try to access directly to your jsp page: localhost:8080/StudentPortal/pathToYourJspPage
*You can also add doGet method in your servlet and call redirect from there to jsp page: response.sendRedirect(location) or request.getRequestDispatcher(location).forward(request,response)
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.
I'm writing a web app that uses a servlet to maintain an ArrayList of VideoData objects (these just contain basic information about movies like the title, type of movie, etc).
The servlet puts this List in the request's scope and forwards both the request and response to a jsp (only part of the servlet code is shown here):
public class VideoServlet extends HttpServlet {
private ArrayList<VideoData> library = new ArrayList<VideoData>();
public void doGet(HttpServletRequest request,
HttpServletResponse response) {
try {
// put ArrayList in Request's scope
request.setAttribute("the_table", library);
request.getRequestDispatcher("/listvideos.jsp").forward(request,
response);
...
The listvideos.jsp is shown below. I'm getting a Tomcat error stating that the uri for the JSTL cannot be resolved. I've used EL in other parts of my jsp code without having to have any special import line like this, and I'm not sure if JSTL is still the preferred way to solve this type of problem while still trying to adhere to MVC2 and keeping all the Java code in the Servlet. Can anyone point me in the right direction here? Ideally I'd like a pure EL solution, if that's possible.
<!DOCTYPE HTML PUBLIC '-//W3C//DTD HTML 4.01 Transitional//EN'
'http://www.w3.org/TR/html4/loose.dtd'>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<head>
<title>Cattle Drive Assignment Servlets-4: Videos</title>
</head>
<body>
<h1>Cattle Drive Assignment Servlets-4: Videos</h1>
<form method='post' action='/videos/VideoServlet'>
Add a video
<br>
<br>
<table border="1">
<tr>
<th>Title</th>
<th>Star</th>
<th>Type</th>
<th>VHS</th>
<th>DVD</th>
<th>Description</th>
</tr>
<c:forEach items="${the_table}" var="movie">
<tr>
<td>${movie.getTitle()}</td>
<td>${movie.getStar()}</td>
<td>${movie.getType()}</td>
<td>${movie.inVHS()}</td>
<td>${movie.inDVD()}</td>
<td>${movie.getDesc()}</td>
</tr>
</c:forEach>
</table>
</form>
</body>
</html>
Your code looks basically correct. Looks like the error you're seeing indicates that the JSTL taglibs cannot be found in the classpath. Please make sure that jstl.jar and standard.jar are in your war's WEB-INF/lib folder.