首页 > 开发 > Java > 正文

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

2024-07-14 08:40:12
字体:
来源:转载
供稿:网友

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

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

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

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

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文件,内容为:

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

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


注:相关教程知识阅读请移步到JAVA教程频道。
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表