jsp页面中获取servlet请求中的参数的办法详解

时间:2022-09-22 13:01:17

在JAVA WEB应用中,如何获取servlet请求中的参数,并传递给跳转的JSP页面?例如访问http://localhost:8088/bbs?id=1

当执行这个bbs servlet时,将url参数id的值传递给bbs.jsp页面?

1.首先要配置web.xml,见下面的配置:

?
1
2
3
4
5
6
7
8
9
10
<servlet>
 <servlet-name>bbs</servlet-name>
 <servlet-class>
  org.openjweb.core.servlet.BBSServlet
 </servlet-class>
 </servlet>
 <servlet-mapping>
 <servlet-name>bbs</servlet-name>
 <url-pattern>/bbs</url-pattern>
 </servlet-mapping>

2.编写servlet类:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
package org.openjweb.core.servlet;
 
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
public class BBSServlet extends HttpServlet
{
 private static final long serialVersionUID = 1L;
  public BBSServlet()
  {
    super();
    // TODO Auto-generated constructor stub
  }
  
 protected void doGet(HttpServletRequest request, HttpServletResponse response)
 throws ServletException, IOException
 {
  //http://bbs.csdn.net/topics/90438353
   request.setCharacterEncoding("UTF-8");  //设置编码
   String id = request.getParameter("id");
   request.setAttribute("id", id);
   request.getRequestDispatcher("/bbs.jsp").forward(request, response);
 }
 
 protected void doPost(HttpServletRequest request, HttpServletResponse response)
 throws ServletException, IOException
 {
 doGet(request, response);
 
 }
}

在应用根目录创建bbs.jsp文件,内容为:

?
1
2
3
4
5
<%@ page contentType="text/html;charset=UTF-8"%>
 <%
out.println(request.getAttribute("id"));
 
 %>

注意很多人传递参数不成功是因为是在doGet方法中调用doPost,这里doGet方法不要调用doPost.