其他分享
首页 > 其他分享> > ServletContext应用(二)——请求转发

ServletContext应用(二)——请求转发

作者:互联网

请求转发就是请求的是路径a,访问的是路径b的内容

具体操作如下

先建立一个类ServletDemo002

 1 package com.jms.servlet;
 2 
 3 import java.io.IOException;
 4 
 5 import javax.servlet.ServletContext;
 6 import javax.servlet.ServletException;
 7 import javax.servlet.http.HttpServlet;
 8 import javax.servlet.http.HttpServletRequest;
 9 import javax.servlet.http.HttpServletResponse;
10 
11 public class ServletDemo002 extends HttpServlet{
12 
13     @Override
14     protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
15         
16         ServletContext context = this.getServletContext();//获取ServletContext对象
17         context.getRequestDispatcher("/demo001").forward(req, resp);//其中为请求转发的路径,调用foward方法进行请求转发
18     }
19 
20     @Override
21     protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
22         doGet(req, resp);
23     }
24     
25 }

 修改web.xml文件注册servlet

    <servlet>
        <servlet-name>demo002</servlet-name>
        <servlet-class>com.jms.servlet.ServletDemo002</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>demo002</servlet-name>
        <url-pattern>/demo002</url-pattern>
    </servlet-mapping>

进行测试

 

 虽然我访问的是/demo002,但出现的却是/demo001的内容,由此可见进行了请求转发

/demo001具体配置请见:ServletContext应用(一)——获取初始化参数 - 谁知道水烫不烫 - 博客园 (cnblogs.com)

 

(本文仅作个人学习记录用,如有纰漏,敬请指正)

标签:请求,resp,req,ServletContext,转发,import,servlet,javax
来源: https://www.cnblogs.com/jmsstudy/p/16514038.html