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

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");%>

Related

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>

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

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.

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

How to call servlet on jsp page load [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>

How to call jsp page from java class without using any servlet

I just want to call jsp page from simple java class where i don' t have any request objects. without using any servlet. Just forward to jsp page from java class.
First to call a java class from JSP page:
you need to instantiate an instance from this class.
For example:
if you have a class called "myclass" and a JSP called "home.jsp"
then in your JSP page import the myclass ex, <# page import="yourpackagename.yourclassname">
then in the body part instantiate an instance from your class by typing my1.callyourfunction(); as follow:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1" import="yourpackagename.myclass"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>home.jsp</title>
</head>
<body>
<%
myclass my1 = new myclass();
my1.Openpage(response);
%>
</body>
</html>
Second to call a jsp from a java class:
you need to use HttpServletResponse such as the following:
package yourpackagename.myclass;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
public class myclass{
public void Openpage(HttpServletResponse res) throws IOException{
// here type your JSP page that you want to open
res.sendRedirect("To.jsp");
}
}
If i am not mis understood, you are looking for JSP page to be opened in a browser via java class?
if yes, you can use Desktop API.
You can also look into following answers:
Open local html page - java
Getting java gui to open a webpage in web browser
Also keep in mind that your JSP page should be placed in a web container(Tomcat etc.) and its running when invoked OR you will be stuck finding out Why JSP is not opening.

Categories