码迷,mamicode.com
首页 > 其他好文 > 详细

Servlet实现重定向的两种方式

时间:2016-06-27 19:46:13      阅读:148      评论:0      收藏:0      [点我收藏+]

标签:

使用Servlet实现请求重定向:两种方式

1.

response.setStatus(302);
response.setHeader("location", "/ResponseDemo/ResponseDemo13");

2.

response.sendRedirect("/ResponseDemo/ResponseDemo13");

 

被访问的代码:

package chensi.com;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet 使用response实现重定向
 */
@WebServlet("/ResponseDemo12")
public class ResponseDemo12 extends HttpServlet {
    private static final long serialVersionUID = 1L;
       
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        response.getWriter().write("这个是最开始访问的页面");
        /*response.setStatus(302);
        response.setHeader("location", "/ResponseDemo/ResponseDemo13");*/
        response.sendRedirect("/ResponseDemo/ResponseDemo13");
    
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

}

 

 

被重定向的Servlet的代码:

package chensi.com;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet 使用response实现重定向
 */
@WebServlet("/ResponseDemo12")
public class ResponseDemo12 extends HttpServlet {
    private static final long serialVersionUID = 1L;
       
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        response.getWriter().write("这个是最开始访问的页面");
        /*response.setStatus(302);
        response.setHeader("location", "/ResponseDemo/ResponseDemo13");*/
        response.sendRedirect("/ResponseDemo/ResponseDemo13");
    
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

}

 

Servlet实现重定向的两种方式

标签:

原文地址:http://www.cnblogs.com/zhanghaoliang/p/5620815.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!