从Servlet使用sendRedirect时,jsp页面中的请求属性不可用 [英] Request Attributes not available in jsp page when using sendRedirect from a servlet

查看:120
本文介绍了从Servlet使用sendRedirect时,jsp页面中的请求属性不可用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是jsp和servlet的新手.我的情况如下

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

我有一个jsp页面,其中包含一个表单.有两个领域. jsp页面的代码片段如下.

I have a jsp page which have a form in it. with two fields. The code snipet of the jsp page is as follows.

MyFirstJSP.jsp文件

MyFirstJSP.jsp file

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

当我提交此表单时,将调用MyFirstServlet,它检查用户输入的名字.如果名字等于"abc",则servlet将属性设置为请求对象,然后将其发送到调用jsp页面(即上一页).它将从请求对象获取值并将其填写到表单的相应字段中. 我也有Java Expression语言,以达到相同的效果.

When I submit this form the MyFirstServlet is called which checks the first name entered by user. If the first name is equals to "abc" then servlet sets the attribute to request object and send redirect it to the callsing jsp page i.e. above page. Which will get the value from request object and fill it in to respective field of form. I have Java Expression language too for same effect.

这是MyFirstServlet.java servlet文件的代码片段

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

/**
 * 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);
}
}

但是,当我执行代码时,servlet会重定向到jsp页面,但不会用相应的值填充表单字段. 为了找到原因,我添加了if-else-block来了解原因,并且我知道请求对象属性在这里不可用.

But when I execute the code the servlet redirects to the jsp page but not fills the form fields with the respective values. As to find the cause I have added the if-else-block to know the cause and I get to know that the request objects attribute is not available here.

如果在这种情况下使用请求分配器,则可以使用这些值,并且使用这些值填充表单,但是地址栏中的url不会改变并且始终显示servlet的URL.

If I use the request dispatcher in this case then the values are gets available and the form is gets filled with the values but the url in the address bar does not chage and always shows the url to the servlet.

所以我的查询是

** 1)为什么使用sendRedirect不能将请求对象用于jsp页面.

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

2)如果Servlet将重定向到调用jsp的sendredirect重定向到用户,那么还有什么其他方法可以在jsp页面中显示由用户输入的值的表单,从而使用户无需在表单中重新输入数据.**

2)Is thre any other way to show my form in jsp page prefilled with the values entered by user if the servlet sendredirects to the calling jsp so that user need not to reenter the data in to form.**

请指导我的朋友解决这个问题 谢谢!

Please guide me friends in this problem Thank You!

推荐答案

您需要转发到服务器端的jsp页面,因为 redirect 是客户端操作(请检查位置标头 1 ),请求属性会丢失.

You need to forward to the jsp page on server side, as a redirect is a client side action (check out the location header 1) the request attributes get lost.

替换

response.sendRedirect("MyFirstJSP.jsp");

使用

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

对不起,我跳过了这一部分

sorry, I skipped this part

如果在这种情况下使用请求分配器,则可以使用这些值,并且使用这些值填充表单,但是地址栏中的url不会改变并且始终显示servlet的URL.

If I use the request dispatcher in this case then the values are gets available and the form is gets filled with the values but the url in the address bar does not chage and always shows the url to the servlet.

不过,重定向时您不能将请求属性传递给jsp(因为我已经在上面提到过,这是一个客户端操作)

nevertheless, you cannot pass request attributes to your jsp when redirecting (as i've already mentioned above it's a clientside action)

我建议您执行以下操作:

I'd suggest doing the following:

  • 实施doGet仅用于呈现包含表单的页面
  • 实施doPost以处理提交的表单数据
  • 在HTML表单中使用POST而不是GET提交表单

在doGet和doPost中,都使用转发呈现* .jsp页面.

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

GET/MyFirstServlet->转发到MyFirstJSP.jsp

GET /MyFirstServlet -> forward to MyFirstJSP.jsp

POST/MyFirstServlet->转发到MyFirstJSP.jsp

POST /MyFirstServlet -> forward to MyFirstJSP.jsp

这是最常用和最干净的方法.

this is the most commonly used and clean approach.

简单示例

SimpleFormServlet.java

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
        // e.g. 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

/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> 

  1. 获取/SimpleFormServlet
  2. doGet()准备表单模型(SimpleForm)并将其添加为名为"form"的请求属性
  3. 前进到simpleForm.jsp
  4. 访问模型值并预填写以下表单:$ {form.fName}和$ {form.lName}
  5. 浏览器仍然显示/SimpleFormServlet(我们喜欢它;-))
  6. POST 相对于/SimpleFormSerlvet的表单(您不必显式设置form元素的action属性)
  7. doPost()将请求参数映射到SimpleForm.
  8. 处理请求并执行您想做的任何事情(验证)
  9. 然后,您可以转发到simpleForm.jsp(例如,验证失败时),也可以重定向到另一个Servlet(例如,/SuccessServlet)
  1. GET /SimpleFormServlet
  2. doGet() prepares the form model (SimpleForm) and adds it as a request attribute named 'form'
  3. forward to the simpleForm.jsp
  4. access the model values and prefill the form: ${form.fName} and ${form.lName}
  5. the browser still shows /SimpleFormServlet (and we like it ;-))
  6. POST the form relatively to /SimpleFormSerlvet (you don't have to set the action attribute of the form element explicitly)
  7. doPost() maps the request parameters to the SimpleForm.
  8. process the request and do whatever you want to do (validation)
  9. then you can either forward to the simpleForm.jsp (like when validation fails) or redirect to another servlet (/SuccessServlet for example)

这篇关于从Servlet使用sendRedirect时,jsp页面中的请求属性不可用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆