java web服务器跳转

来源:互联网 发布:阿里云专有网络怎么用 编辑:程序博客网 时间:2024/05/16 01:53
客户端跳转:response.sendRedirect("index.jsp");
example :
servlet.java
 
 
package org.lxh.servletdemo;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;public class ClientRedirectDemo extends HttpServlet { // 继承HttpServlet public void doGet(HttpServletRequest req, HttpServletResponse resp)   throws ServletException, java.io.IOException { // 处理服务  req.getSession().setAttribute("name", "李兴华") ; // 设置session属性  req.setAttribute("info", "MJAVA") ; // 设置request属性  resp.sendRedirect("index.jsp") ; // 页面跳转 } public void doPost(HttpServletRequest req, HttpServletResponse resp)   throws ServletException, java.io.IOException { // 处理服务  this.doGet(req, resp);    // 调用doGet() }}

 

index.jsp:

 

 

<%@ page contentType="text/html" pageEncoding="GBK"%>
<html>
<head><title>www.java.cn,高端Java培训</title></head>
 <% request.setCharacterEncoding("GBK") ;%>
<body>
 <h2>session属性:<%=session.getAttribute("name")%></h2>
 <h2>request属性:<%=request.getAttribute("info")%></h2>
</body>
</html>

 

 

服务器跳转:

 

在Servlet中没有像JSP中的“<jsp:forward>”指令,所以,如果要想执行服务器端跳转的话,就必须依靠RequestDispatcher接口完成,此接口中提供了如下的方法: public void forward (ServletRequest

request,ServletResponseresponse)

throws ServletException,IOException

使用RequestDispatcher接口的forward()方法就可以完成跳转功能的实现,但是如果要想使用此接口还需要使用ServletRequest接口提供的如下方法进行实例化 public RequestDispatcher getRequestDispatcher(String path)

 
example :
 
使用服务器端跳转
package org.lxh.servletdemo;import javax.servlet.RequestDispatcher;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;public class ServerRedirectDemo extends HttpServlet {  // 继承HttpServlet public void doGet(HttpServletRequest req, HttpServletResponse resp)   throws ServletException, java.io.IOException { // 处理服务  req.getSession().setAttribute("name", "李兴华") ; // 设置session属性  req.setAttribute("info", "MJAVA") ;  // 设置request属性  // 实例化RequestDispatcher对象,同时指定跳转路径  RequestDispatcher rd = req.getRequestDispatcher("index.jsp");  rd.forward(req, resp) ;    // 服务器跳转 } public void doPost(HttpServletRequest req, HttpServletResponse resp)   throws ServletException, java.io.IOException { // 处理服务  this.doGet(req, resp);    // 调用doGet() }}
 
index.jsp:
 
接收属性
 
<%@ page contentType="text/html" pageEncoding="GBK"%><html><head><title>www.java.cn,高端Java培训</title></head> <% request.setCharacterEncoding("GBK") ;%><body> <h2>session属性:<%=session.getAttribute("name")%></h2> <h2>request属性:<%=request.getAttribute("info")%></h2></body></html>