客户端跳转
ClientRedirectDemo.java
package im.weitang;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ClientRedirectDemo extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.getSession().setAttribute("username", "张三");
request.setAttribute("age", 24);
response.sendRedirect("/get_info.jsp");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
}
修改web.xml,添加如下代码:
<servlet>
<servlet-name>ClientRedirectDemo</servlet-name>
<servlet-class>im.weitang.ClientRedirectDemo</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ClientRedirectDemo</servlet-name>
<url-pattern>/ClientRedirectDemo</url-pattern>
</servlet-mapping>
get_info.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>标题</title>
</head>
<body>
<h2>username = <%=session.getAttribute("username") %></h2>
<h2>age = <%=request.getAttribute("age") %></h2>
</body>
</html>
服务器端跳转
ServerRedirectDemo.java
package im.weitang;
import java.io.IOException;
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 {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.getSession().setAttribute("username", "张三");
request.setAttribute("age", 24);
// 实例化RequestDispatcher对象,同时指定跳转路径
RequestDispatcher rd = request.getRequestDispatcher("get_info.jsp");
rd.forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
}
修改web.xml文件,添加如下代码:
<servlet>
<servlet-name>ServerRedirectDemo</servlet-name>
<servlet-class>im.weitang.ServerRedirectDemo</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ServerRedirectDemo</servlet-name>
<url-pattern>/ServerRedirectDemo</url-pattern>
</servlet-mapping>
网友评论