Servlet 重定向

·  阅读 39

重定向和请求转发的区别

  • 相同点:实现页面跳转
  • 不同点:请求转发url不变,重定向url改变。

代码

向浏览器输出图片

public class Servlet_1 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("image/jpeg");
        String path = "/WEB-INF/classes/img.png";
        OutputStream out = resp.getOutputStream();
        InputStream in = this.getServletContext().getResourceAsStream(path);
        int len;
        byte[] buffer = new byte[1024];
        while ((len = in.read(buffer))>0){
            out.write(buffer,0,len);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
复制代码

重定向

public class Redirect extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.sendRedirect("s1");
 //对该servlet的请求都会定向到s1,s1是<url-pattern>/s1</url-pattern>,在web.xml里,也就是另外一个servlet
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
复制代码
分类:
后端
标签:
分类:
后端
标签:
收藏成功!
已添加到「」, 点击更改