URL rewriting in Servlet/JSP - java

I know that response.sendRedirect() destroys the request/response object and new request is sent to the resource. So how come request.getParameter("") fetches me the value if the earlier request/response object has already been destroyed.
NewFile.HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action ="MyServlet">
<label>Username</label>
<input type="text" name="textbox1"/><br>
<label>Password</label><input type="password" name="textbox2"/>
<input type="submit"/>
</form>
</body>
</html>
Servlet
/**
* Servlet implementation class MyServlet
*/
#WebServlet("/MyServlet")
public class MyServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String user = request.getParameter("textbox1");
String password = request.getParameter("textbox2");
if (user.equals("abc")&&password.equals("123"))
{
response.sendRedirect("NewFile.jsp?name="+user);
}
}
}
Newfile.jsp
<%= "hi there"+request.getParameter("name") %>

I repeated here the comment so you can mark your question as solved by this answer :D
If you are talking about your jsp getting parameter "name"... it's simply because you have put the request directly in the url (NewFile.jsp?name=xuser). If not, I didn't understand your question, please try to be clearer

It is because at very first request, you are getting the parameter, after that you are sending redirect response, if you will do same thing on redirected page or servlet, you will not able to get any thing. In your case, you are sending parameter name with value, so you will be able to get it.

Go to your "NewFile.jsp" page, in that page <%=request.getParameter("name")>.
It will simply get the value you passed in URL("NewFile.jsp?name="+user).

Related

Http404 error while click the submit button (Servlet question)

Guys! I am new to servlet. I tried to follow the step with book to create a servlet. It's just a login form where user enter the userid and password click the login, it should then display the input value in webpage. However, when I enter the userId and password, I get Http404 error.
I was wondering something maybe wrong with context.xml but I am not sure.
I also tried to mapping the servlet in xml, but still get the error.
here is my html
<!DOCTYPE html>
<html>
<head>
<title>USER LOGIN</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial- scale=1.0">
</head>
<body>
<form action="UserServlet" method="get">
<!-- Name text Field -->
<p>
<label>User ID</label>
<input type ="text" name="userId" size="30"/>
</p>
<p>
<label>User Password</label>
<input type ="text" name="userPassword" size="30"/>
</p>
<!--Button for submit -->
<input type ="submit" name="Login" value="LogIn"/>
<input type ="button" value="LogOut" onclick="self.close()"/>
</form>
</body>
here is my servlet.java
public class UserServlet extends HttpServlet
{
//process the HTTP GET REQUEST//
#Override
public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException
{
response.setContentType("text/html");
PrintWriter out=response.getWriter();
//get the data
String userId=request.getParameter("userId");
String passWord=request.getParameter("userPassWord");
//determine the input if user missing these two send back the message
if (userId.isEmpty()&&passWord.isEmpty())
{
out.println("UserId and passWord can not be empty.");
}
else
{
out.println("<p>your id is "+userId);
out.println("<br>your password is"+passWord);
out.println("<br>You entered the data successfully </p>");
}
}
}
here is my context.xml
<?xml version="1.0" encoding="UTF-8"?>
<Context path="/userLogin"/>
I didn't change any thing in context.xml
its working when I run the project, but once I click the button it just gives me
Type Status Report
Message /userLogin/UserServlet
Description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists.
can you check what is the servlet mapping provided in web.xml. I think the mapping would not be matching the request.
or you can post the web.xml

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>

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>

java.lang.IllegalStateException: Cannot forward after response has been committed

I know this has been discusses at least a million times here but every servlet was redirecting or flushing the output before calling forward(). I have the same problem but I am not doing anything with the output. My servlet just takes the request parameters and commits to the database and sets an attribute on the request. Then, it forwards the request to a jsp which them displays the attribute. I am using Servlet 3.0 on Tomcat 7. Here is my servlet doPost method followed byt the jsp that this is forwarding to:
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
super.doPost(req, resp);
DAOFactory daoFactory = DAOFactory.getFactory();
daoFactory.getCompanyDAO().beginTransaction();
Company company = new Company();
company.setName(req.getParameter("companyName"));
company.setContactEmail(req.getParameter("companyEmail"));
company.setContactPhone(new Long(req.getParameter("companyMobile")));
company.setAddressLine1(req.getParameter("companyAddressLine1"));
company.setAddressLine2(req.getParameter("companyAddressLine2"));
company.setCity(req.getParameter("companyCity"));
company.setZipcode(Integer.parseInt(req.getParameter("companyZip")));
company.setState(req.getParameter("companyState"));
company = daoFactory.getCompanyDAO().save(company);
daoFactory.getCompanyDAO().commitTransaction();
Employee owner = new Employee();
owner.setFirstname(req.getParameter("ownerFirstName"));
owner.setLastname(req.getParameter("ownerLastName"));
owner.setEmail(req.getParameter("ownerEmail"));
owner.setMobileNum(new Long(req.getParameter("ownerCellPhone")));
owner.setZipcode(Integer.parseInt(req.getParameter("ownerZip")));
owner.setRole("Employer");
owner.setCompany(company);
daoFactory.getEmployeeDAO().beginTransaction();
owner = daoFactory.getEmployeeDAO().save(owner);
daoFactory.getEmployeeDAO().commitTransaction();
company.addEmployee(owner);
company.setOwnerId(owner.getId());
daoFactory.getCompanyDAO().beginTransaction();
company = daoFactory.getCompanyDAO().save(company);
daoFactory.getCompanyDAO().commitTransaction();
req.setAttribute("company", company);
RequestDispatcher rd = getServletConfig().getServletContext().getRequestDispatcher("/jsp/companyConfirmation.jsp");
rd.forward(req, resp);
}
JSP:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!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>
<h3>The Company was saved successfully</h3>
<p>
Company name: ${company.name}
</p>
</body>
</html>
I am sure I may have missed something very trivial. I cannot figure out what it is especially when I am not writing anything to the output before forwarding the request.
PS: I also tried putting a return; statement after the forward but no change.
Thanks!
You should remove the super.doPost(req, resp) method call. The default implementation of doPost method from HTTPServlet returns HTTP 405 status code meaning "Method not supported" and that's the response which has been committed. Therefore, you can not forward your request to other jsp.
This is part of the RequestDispatcher.forward(ServletRequest req, ServletResponse resp) method description: "forward should be called before the response has been committed to the client (before response body output has been flushed). If the response already has been committed, this method throws an IllegalStateException. Uncommitted output in the response buffer is automatically cleared before the forward".

JSP form parameters disappear when I POST my form to another page

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

Categories