javaWeb中servlet开发(4)——servlet跳转

servlet跳转

1、跳转类型

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

服务器端跳转:地址栏不改变,可以传递request范围内属性,属于无条件跳转,只要执行到了,就立即执行跳转操作,语法是:<jsp:forward></jsp:forward>

2、servlet跳转

javaWeb中servlet开发(4)——servlet跳转

2.1 客户端跳转

servlet 中也是可以完成跳转的,servlet本身已经存在HttpServletResponse对象,所有可以直接通过此对象完成sendRedirect跳转操作。

javaWeb中servlet开发(4)——servlet跳转

代码如下:

public class ClientRedirectDemo extends HttpServlet {
public void doGet(HttpServletRequest req,HttpServletResponse resp) throws ServletException,IOException{
req.getSession().setAttribute("name","李李") ;
req.setAttribute("info","JAVA") ;
resp.sendRedirect("get_info.jsp") ;
}
public void doPost(HttpServletRequest req,HttpServletResponse resp) throws ServletException,IOException{
this.doGet(req,resp) ;
}
}

xml配置:

<servlet>
<servlet-name>client</servlet-name>
<servlet-class>
com.alice.servletdemo.ClientRedirectDemo
</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>client</servlet-name>
<url-pattern>/forward/ClientRedirectDemo</url-pattern>
</servlet-mapping>

get—info.jsp

<body>
<% request.setCharacterEncoding("GBK") ; %>
<h2>sesion属性:<%=session.getAttribute("name")%></h2>
<h2>request属性:<%=request.getAttribute("info")%></h2>
</body>

2.2 服务器端跳转

javaWeb中servlet开发(4)——servlet跳转

代码实现:

public class ServerRedirectDemo extends HttpServlet {
public void doGet(HttpServletRequest req,HttpServletResponse resp) throws ServletException,IOException{
req.getSession().setAttribute("name","李兴华") ;
req.setAttribute("info","MLDNJAVA") ;
RequestDispatcher rd = req.getRequestDispatcher("get_info.jsp") ; // 准备好了跳转操作
rd.forward(req,resp) ; // 完成跳转
}
public void doPost(HttpServletRequest req,HttpServletResponse resp) throws ServletException,IOException{
this.doGet(req,resp) ;
}
}

xml配置:

<servlet>
<servlet-name>server</servlet-name>
<servlet-class>
com.alice.servletdemo.ServerRedirectDemo
</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>server</servlet-name>
<url-pattern>/forward/ServerRedirectDemo</url-pattern>
</servlet-mapping>
上一篇:centos7下安装docker(15.6docker跨主机网络---Weave)


下一篇:Fragment和Activity之间通过广播的方式传递数据