赞
踩
请求重定向有两种方案,但是强烈推荐第二种方案,代码简洁。
请求重定向的特点:
//设置响应码 302 表示重定向
resp.setStatus(302);
//设置响应头,并设置重定向的地址
resp.setHeader("Location","http://localhost:8080/06-servlet/response2");
public class Response1 extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("曾到此一游,Response1"); // 设置响应状态码 302 表示重定向,(已搬迁) resp.setStatus(302); // 设置响应头说明新的地址在哪 resp.setHeader("Location","http://localhost:8080/06-servlet/response2");* } } public class Response2 extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("text/html; Charset=UTF-8"); resp.getWriter().write("已请求重定向到response2,这是response2处理的业务代码"); } }
web.xml中的配置:
<servlet> <servlet-name>Response1</servlet-name> <servlet-class>com.servlet.Response1</servlet-class> </servlet> <servlet-mapping> <servlet-name>Response1</servlet-name> <url-pattern>/response1</url-pattern> </servlet-mapping> <servlet> <servlet-name>Response2</servlet-name> <servlet-class>com.servlet.Response2</servlet-class> </servlet> <servlet-mapping> <servlet-name>Response2</servlet-name> <url-pattern>/response2</url-pattern> </servlet-mapping>
//请求重定向
resp.sendRedirect("http://www.baidu.com");
例如:
public class Response1 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("曾到此一游,Response1");
//请求重定向
resp.sendRedirect("http://www.baidu.com");
}
}
web.xml中的配置:
<servlet>
<servlet-name>Response1</servlet-name>
<servlet-class>com.servlet.Response1</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Response1</servlet-name>
<url-pattern>/response1</url-pattern>
</servlet-mapping>
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。