Welcome

首页 / 网页编程 / JSP / Servlet开发入门(7) Servlet两种跳转

Servlet开发入门(7) Servlet两种跳转2013-07-05回顾: 关于跳转之前就强调过有两种:

1. 客户端跳转: 地址栏跳转之后改变,而且无法传递request范围的属性,是在所有的操作执行完毕之后才发生跳转的操作,语法:request.sendRedirect()

2.服务器端跳转:  地址栏不改变,而且可以传递request范围的属性,属于无条件跳转,只要执行到了,则立刻执行跳转的操作。 语法:<jsp:forward>

Servlet之中也是可以完成跳转的,而且既然Servlet本身已经存在了HttpServeltResponse对象,所以直接通过此对象的sendRedirect()方法可以完成跳转操作。

客户端跳转

package ServletDemo;import java.io.IOException;import javax.print.attribute.standard.Sides;import javax.servlet.*;import javax.servlet.http.*;public class kehuduanTiaozhuan extends HttpServlet { //继承HttpServletpublic void doGet(HttpServletRequest req,HttpServletResponse resp) throws ServletException,IOException{ //处理服务 req.getSession().setAttribute("name", "赵玉强"); req.setAttribute("info","zhaoyuqiang.blog.51cto.com");//设置属性 resp.sendRedirect("get_info.jsp");//设置跳转的页面} public void doPost(HttpServletRequest req,HttpServletResponse resp) throws ServletException,IOException{ //处理POST请求this.doGet(req, resp); //调用doGet()方法 }}
get_info.jsp<%@ page language="java" contentType="text/html" pageEncoding="utf-8"%><html><head><title>WEB开发</title></head><body><% request.setCharacterEncoding("utf-8");%><h2>session属性:<%=session.getAttribute("name") %></h2><h2>request属性:<%=request.getAttribute("info") %></h2></body></html>