JSP and Java Servlet not passing parameter to JSP file [duplicate] - java

This question already has answers here:
Calling a servlet from JSP file on page load
(4 answers)
Closed 6 years ago.
I didn't have trouble with this before, and I actually have a working implementation with a different class. But for some reason, this example fails.
I have a class called InfoServlet.java:
#WebServlet("/info_servlet")
public class InfoServlet extends HttpServlet {
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setAttribute("test", "hello world.");
request.getRequestDispatcher("info_servlet.jsp").forward(request, response);
}
}
And my jsp page info_servlet.jsp
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Test</title>
</head>
<body>
<h1>HELLO</h1>
<p><c:out value="${test}" /></p>
</body>
</html>
Now when I go to localhost:8080/MySite/info_servlet.jsp my output is only
HELLO
For reference, I'm using tomcat 7 and servlet 3.0 in java. I didn't have trouble passing in an object so I'm unsure why all the sudden it won't let me display the value in info_servlet.jsp

Everything works as expected. You are setting the "test" attribute within the servlet: if you go directly to the .jsp, bypassing the servlet, the attribute simply won't be set. Its value therefore will be null and the expression language will silently ignore it.

Related

Java Dynamic Web Project index.html doesn't show anything when opened in browser [duplicate]

This question already has answers here:
Generate an HTML Response in a Java Servlet
(3 answers)
Closed 3 years ago.
I'm trying to make a web application using Java Servlets, Tomcat and HTML on Eclipse. My problem is that after I created my Dynamic Web Project, along with my web.xml and my index.html files, the index.html page doesn't show anything.
Servlet:
#WebServlet("/index.html")
public class AppServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final String HTML_START = "<html><body>";
private static final String HTML_END = "</body></html>";
public AppServlet() {
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
index.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<link rel="stylesheet" type="text/css" href="styling.css">
<title>Test page</title>
</head>
<body>
<h1 style="text-align:center;">Example text</h1>
<div align="center">
<textarea rows="12" cols="120" style="border-radius: 5px"></textarea>
</div>
</body>
</html>
The html page shows up just fine when I open it directly (when I double click on the file in a directory), but when I start up the server from Eclipse and it redirects me to localhost:8080/MyProject/index.html, nothing shows up.
Each URL can be processed by a single component: Either your URL is resolved to the file index.html or to a servlet. In your case servlet has higher priority and this servlet (not the file index.html) creates the result. Your servlet doesn't create any contents in the doGet method. SO it is naturally that the response is empty.
If you want that this URL is resolved to the file index.html, then use some other URL mapping in the servlet, like #WebServlet("/bla"). Then when you call .../MyProject/index.html, you will get the contents of the file index.html.
You grab that PrintWriter but you don't do anything with it. With the first line of your snippet, you've told the Server that you are going to manage /index.html with code, and therefore it shouldn't go get it from the static content. Then your code produces nothing, so you are correctly seeing what your code produces.
Try adding this after PrintWriter out = response.getWriter();
out.println(HTML_START);
out.println("Hello World!");
out.println(HTML_END);

Getting null on sending values from Servlet to Client-side JSP [duplicate]

This question already has answers here:
Value passed with request.setAttribute() is not available by request.getParameter()
(2 answers)
Difference between getAttribute() and getParameter()
(10 answers)
Closed 4 years ago.
I am trying a simple example of sending values from a servlet Servlet1.java to client-side JSP page client1.jsp.
But I am getting null
Here is the code Server1.java:
import java.io.*;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.util.*;
#WebServlet("/server1")
public class Server1 extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
String name="Rahul";
request.setAttribute("myname",name);
//Servlet JSP communication
RequestDispatcher reqDispatcher = getServletConfig().getServletContext().getRequestDispatcher("/client1.jsp");
reqDispatcher.forward(request,response);
}
}
Code for client1.jsp:
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<% String s=request.getParameter("myname");%>
Hello friends <%=s%>
</body>
</html>
What you do is bad.
First you are mixing attributes and parameters. They are different animals. Parameters is what comes from the client and are set once by the servlet container. Attributes are objects that are used by cooperating elements (filters, servlets and JSP pages) for passing data.
So you should at least read the attributes in JSP:
<% String (String) s=request.getAttribute("myname");%>
You must cast the attribute to String because getAttribute returns an Object.
But that's not all. Scriptlets are deprecated for decades, and should only be used for very special use cases, if any. Here, assuming you have a decent servlet container, you could simply use the ${} JSTL automatic attribute:
<body>
Hello friends ${myname}
</body>
It is shorter, cleaner and less error prone.
After your comments, there is another possible problem. You only show the override of doPost in your servlet code, when common requests (unless you post from a form) are GET requests and are processed in doGet. If you use a GET request and only set the attribute in doPost your JSP will not find it...
"myname" you are setting to request.setAttribute
so, you can retrieve as below:
<% String s=(String) request.getAttribute("myname");%>

JSP page becomes separated from tag output [duplicate]

This question already has answers here:
Difference between JspWriter and PrintWriter in Java EE?
(2 answers)
Closed 6 years ago.
I am getting split output from my JSP page, with writer.write() output first and second the JSP with tags omittted.
I have the following simple JSP page
<%# page import="com.AAA.SiteTemplate.RenderPageInterface" %>
<%# page import="java.io.Writer" %>
<%# page import="java.io.IOException" %>
<%# page import="com.NatureRelaxation.SiteTemplate.RenderPageInterfaceNull" %><%--
Created by IntelliJ IDEA.
User:
--%>
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<%
RenderPageInterface obj = (RenderPageInterface) request.getAttribute("renderPageInterface");
if (obj == null){
obj = new RenderPageInterfaceNull();
}
%>
<title><% response.getWriter().write(obj.getTitle()); %></title>
<style type="text/css">
</style>
</head>
<body>
<%
obj.renderHTML(response.getWriter());
%>
</body>
</html>
and I include it via this small function:
public static void doRequest(HttpServletRequest req, HttpServletResponse res, RenderPageInterface renderPageInterface) throws ServletException, IOException{
req.setAttribute("renderPageInterface", renderPageInterface);
RequestDispatcher rd = req.getRequestDispatcher("/WEB-INF/templates/header.jsp");
rd.include(req, res);
}
The response that I am getting now is
My page titleMypagebody....
<html>
<head>
<title></title>
etc. There are 4 newlines in the middle. I'm thinking it must be a compiler error, but clearing caches (IntelliJ) and restarting, redeploying to Tomcat 8 doesn't fix it. All worked as normal until server was restarted, but nothing fixes it now. I even run the debugger on the JSP and all goes in order.
Update:
It runs fine without this tag "<% response.getWriter().write(obj.getTitle()); %>", but when the tag is there, both the body and the title get written at the top and the template at the bottom. getTitle() returns a String.
I figured it out fast enough, but it was quite tricky. "response.getWriter()" and JSP's "out" variable (which I did not know about), are not the same thing.
It is by coincidence that my code previously worked.
I also had to include jsp.api.jar before I could use the "out" (JSPWriter) variable.
Relevant info here:
Difference between JspWriter and PrintWriter in Java EE?
what is difference between JspWriter and PrintWriter?

How to call servlet when loading jsp page? [duplicate]

This question already has answers here:
How to call servlet through a JSP page
(6 answers)
Closed 6 years ago.
I want to call a servlet latest_products on load of index.jsp page.This servlet has records in List. I want to pass this List<products> to index.jsp. But I don't want to display the name of servlet in url. Is there any way by which I can do this.
Solution 1
Steps to follow:
use jsp:include to call the Servlet from the JSP that will include the response of the Servlet in the JSP at runtime
set the attribute in the request in Servlet and then simply read it in JSP
Sample code:
JSP:
<body>
<jsp:include page="/latest_products.jsp" />
<c:out value="${message }"></c:out>
</body>
Servlet:
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setAttribute("message", "hello");
}
EDIT
but i don't want to display the name of servlet in url.
Simply define a different and meaningful url-pattern for the Servlet in the web.xml such as as shown below that look like a JSP page but internally it's a Servlet.
web.xml:
<servlet>
<servlet-name>LatestProductsServlet</servlet-name>
<servlet-class>com.x.y.LatestProductsServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LatestProductsServlet</servlet-name>
<url-pattern>/latest_products.jsp</url-pattern>
</servlet-mapping>
Solution 2
Steps to follow:
first call to the the Servlet
process the latest products
set the list in the request attribute
forward the request to the JSP where it can be accessed easily in JSP using JSTL
Sample code:
Servlet:
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setAttribute("message", "hello");
RequestDispatcher view=request.getRequestDispatcher("index.jsp");
view.forward(request,response);
}
index.jsp:
<body>
<c:out value="${message }"></c:out>
</body>
hit the URL: scheme://domain:port/latest_products.jsp that will call the Servlet's doGet() method.
(...) but I don't want to display the name of servlet in url.
You don't need to use the Servlet name at all when accessing to a Servlet. In fact, you can create your servlet to point to the desired URL by defining the right URL pattern:
#WebServlet("/index.jsp")
public class LatestProductServlet extends HttpServlet {
#Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
List<Product> productList = ...
//all the necessary code to obtain the list of products
//store it as request attribute
request.setAttribute("productList", productLlist);
//forward to the desired view
//this is the real JSP that has the content to display to user
request.getRequestDispatcher("/WEB-INF/index.jsp").forward(request, response);
}
}
Then, you will have a folder structure like this
- <root folder>
- WEB-INF
+ index.jsp
+ web.xml
And in WEB-INF/index.jsp:
<!DOCTYPE html>
<html lang="es">
<body>
<!--
Display the data accordingly.
Basic quick start example
-->
<c:forEach items="${productList}" var="product">
${product.name} <br />
</c:forEach>
</body>
</html>
Note that your clients will access to http://<yourWebServer>:<port>/<yourApplication>/index.jsp and will get the desired content. And you don't need to fire two GET requests to retrieve the content for your specific page.
Note that you can go further with this approach: Since the pattern is now defined in servlet, you may choose to not use index.jsp for your clients, but index.html to access to your page. Just change the URL pattern in the Servlet:
#WebServlet("/index.html")
public class LatestProductServlet extends HttpServlet {
//implementation...
}
And the clients will access to http://<yourWebServer>:<port>/<yourApplication>/index.html, which will show the results in WEB-INF/index.jsp. Now both your clients and you will be happy: clients will get their data and you won't show that ugly servlet name in your URL.
Additional
If you have index.jsp as your welcome page in web.xml, this approach won't work because application servlet expects that a real file index.jsp exists. To solve this issue, just create an empty file named index.jsp:
- <root folder>
- index.jsp <-- fake empty file to trick the application server
- WEB-INF
+ index.jsp
+ web.xml
And when accessing to http://<yourWebServer>:<port>/<yourApplication>/, will work as shown above.
Thanks to +Braj, I am able to make an answer using Expression Language. Apparently, this is supposed to be better than jsp scripting/tags.
Servlet -
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ProductList extends HttpServlet {
private static final long serialVersionUID = 1L;
public ProductList() {
super();
// TODO Auto-generated constructor stub
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
List<String> products = new ArrayList<String>();
products.add("Car");
products.add("Gun");
products.add("Shades");
request.setAttribute("productsList", products);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
JSP -
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%#taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<c:import url="/ProductList" />
<c:set var="myProducts" value="${requestScope.productsList}" />
<h1>List of products from servlet</h1>
<c:forEach var="product" items= "${myProducts}" varStatus="i">
${product}<br>
</c:forEach>
</body>
</html>

Java - Servlet post parameters bad encoding [duplicate]

This question already has answers here:
How to pass Unicode characters as JSP/Servlet request.getParameter?
(5 answers)
Closed 7 years ago.
I was working normally on my netbeans project. I sent post parameters from html forms to servlets and then capture them with request.getParameter... and all worked fine. But some hours ago, I don't know what happened with netbeans because all new servlets that I create, the requested post parameters are not encoded well. I mean that if I send "tílde" or "ñ" it will be received as "tílde" or "ñ". The old servlets still work fine, receiving well the post parameters.
With GET parameters works fine, but with POST parameters always the same with new servlets. Old servlets work fine post parameters.
I tested receiving parameters with php and they are correctly formated, so I discart the posibility of being the jsp encoding.
I think may be netbeans error, but I really dont know.
Here some code and images:
The servlet
public class TestParameters extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
System.out.println("> Ñ,ñ, tílde. Parámetros: " + request.getParameter("name"));
}
The JSP:
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<form method="post" action="/TestParameters">
<input type="text" name="name">
<button type="submit">Enviar</button>
</form>
</body>
</html>
Html input:
NetBeans console with POST parámeters:
Netbeans console with GET parámeters:
And receiving with php, works well:
echo $_POST['name'];
Php html echo:
Finally I have resolved my problem. I have implemented a filter that encode all requests. But this only work for POST parameters that is what I need. That's because for POST parameters Tomcat's default encoding is iso-8859-1 and I was ignoring that. For GET parameters the way is
Encoding filter for java web application

Categories