Request attributes not available on jsp page when using sendRedirect from servlet

I am new to jsp and servlet. My scenario is as follows

I have a jsp page in which there is a form. with two fields. The code script on the jsp page is as follows.

File MyFirstJSP.jsp

<body> <h1> This is my first jsp and servlet project</h1> <% //System.out.println(request.getAttribute("fname")); if(request.getAttribute("fname")!=null){ System.out.println(request.getAttribute("fname")); }else{ System.out.println("No request "); } %> <form action="MyFirstServlet" method="get"> First Name<input type="text" name="fname" value= ${fname}><br> Last Name<input type="text" name="lname" value= ${lname}> <input type="submit" value="Send"> </form> </body> 

When I submit this form, MyFirstServlet is called, which validates the name entered by the user. If the first name is "abc", then the servlet sets the attribute for requesting the object and sends its redirection to the jsp page of the calling messages above. Which will receive the value from the request object and fill it in the corresponding field of the form. I also have Java Expression for the same effect.

Here is my snipet code for the servlet file MyFirstServlet.java

 /** * Servlet implementation class MyFirstServlet */ public class MyFirstServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public MyFirstServlet() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub String firstname=request.getParameter("fname"); if(firstname.equalsIgnoreCase("abc")){ System.out.println("Setting attributes"); request.setAttribute("fname",firstname); request.setAttribute("lname",request.getParameter("lname")); response.sendRedirect("MyFirstJSP.jsp"); }else{ System.out.Println("No problem"); } } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub PrintWriter p=response.getWriter(); p.println("Success!"); doGet(request,response); } } 

But when I execute the code, the servlet redirects to the jsp page, but does not populate the form fields with the appropriate values. To find the reason, I added if-else-block to find out the reason, and I find out that the attribute of the request objects is not available here.

If I use the query manager in this case, then the values ​​become available and the form is populated with values, but the URL in the address bar does not change and always shows the URL of the servlet.

So my request

** 1) Why the request object is not available on the jsp page using sendRedirect.

2) Is there any other way to show my form on a jsp page filled with values ​​entered by the user if the servlet has sent links to the calling jsp so that the user cannot re-enter the data in the form. **

Please tell your friends about this problem. Thank you!

+4
source share
2 answers

You need to forward to the jsp page on the server side, since redirection is an action on the client side (check location header 1 ) request attributes are lost.

replace

 response.sendRedirect("MyFirstJSP.jsp"); 

with

 request.getRequestDispatcher("MyFirstJSP.jsp").forward(request, response); 

Edit: Sorry, I skipped this part

If I use the query manager in this case, then the values ​​become available and the form is populated with values, but the URL in the address bar does not change and always shows the URL of the servlet.

however, you cannot pass request attributes to jsp when redirecting (as I mentioned above, this is a client action)

I suggest doing the following:

  • Implement doGet only to display the page containing the form
  • Implement doPost to process submitted form data
  • use POST instead of GET in the HTML form to submit the form

In both cases, doGet and doPost use forward to display the * .jsp page.

GET / MyFirstServlet → go to MyFirstJSP.jsp

POST / MyFirstServlet → go to MyFirstJSP.jsp

This is the most commonly used and cleanest approach.

EDIT 2: Simple Example

SimpleFormServlet.java

 public class SimpleFormServlet extends HttpServlet { private static final long serialVersionUID = 1L; private static final String VIEW_NAME = "/WEB-INF/jsp/simpleForm.jsp"; private static final String MODEL_NAME = "form"; public SimpleFormServlet() { super(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setAttribute(MODEL_NAME, new SimpleForm()); request.getRequestDispatcher(VIEW_NAME).forward(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { final SimpleForm form = map(request); if(form.getfName().equalsIgnoreCase("abc")){ request.setAttribute(MODEL_NAME, form); // put additional attributes on the request // eg validation errors,... request.getRequestDispatcher(VIEW_NAME).forward(request, response); }else{ System.out.println("No problem"); response.sendRedirect("/SuccessServlet"); } } private SimpleForm map(final HttpServletRequest request) { SimpleForm form = new SimpleForm(); form.setfName(request.getParameter("fName")); form.setlName(request.getParameter("lName")); return form; } public static class SimpleForm implements Serializable { private static final long serialVersionUID = -2756917543012439177L; private String fName; private String lName; public String getfName() { return fName; } public void setfName(String fName) { this.fName = fName; } public String getlName() { return lName; } public void setlName(String lName) { this.lName = lName; } } } 

/WEB-INF/jsp/simpleForm.jsp

 <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> </head> <body> <form method="POST"> First Name<input type="text" name="fName" value="${form.fName}"><br> Last Name<input type="text" name="lName" value="${form.lName}"> <input type="submit" value="Send"> </form> </body> </html> 
  • GET / SimpleFormServlet
  • doGet () prepares the form model (SimpleForm) and adds it as a request attribute called 'form'
  • go to simpleForm.jsp
  • access model values ​​and fill out the form: $ {form.fName} and $ {form.lName}
  • the browser still shows / SimpleFormServlet (and we like it ;-))
  • POST form relative to / SimpleFormSerlvet (you do not need to explicitly set the action attribute of the form element)
  • doPost () maps query parameters to SimpleForm.
  • process the request and do whatever you want (validation)
  • then you can either forward the file simpleForm.jsp (for example, when the check is completed), or redirect to another servlet (for example, SuccessServlet)
+16
source

I know it's too late to answer, but that would be helpful to someone. redirection is a client-side action, so we cannot getAttribute , but we can solve it using the concept of URL Rewriting .

 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub String firstname=request.getParameter("fname"); if(firstname.equalsIgnoreCase("abc")){ //System.out.println("Setting attributes"); response.sendRedirect("MyFirstJSP.jsp?fname="+firstname+"&lname="+request.getParameter("lname")+""); } else{ System.out.Println("No problem"); } } 

then use request.getParameter () to extract the values ​​as a string in MyFirstJSP.jsp.

+4
source

Source: https://habr.com/ru/post/1433348/


All Articles