Servlet跳转

客户端跳转

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,添加如下代码:


    ClientRedirectDemo
    im.weitang.ClientRedirectDemo


    ClientRedirectDemo
    /ClientRedirectDemo

get_info.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>



    
    标题


    

username = <%=session.getAttribute("username") %>

age = <%=request.getAttribute("age") %>

服务器端跳转

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文件,添加如下代码:


    ServerRedirectDemo
    im.weitang.ServerRedirectDemo


    ServerRedirectDemo
    /ServerRedirectDemo

你可能感兴趣的:(Servlet跳转)