在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.
新闻热点
疑难解答
图片精选