javaweb重定向

若服务器状态码返回302,则浏览器进行重定向,访问指定的servlet。

    相应的代码如下:

                    response.setStatus(302);

                    response.setHeader("location", "URL");

完整代码:

(1)package com.wc.response;


import java.io.IOException;
import java.io.PrintWriter;


import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class ServletDemo7 extends HttpServlet {


public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {


System.out.println("我要借钱");
System.out.println("我没有找8借去");
//告诉客户端要重新定向
response.setStatus(302);
response.setHeader("location", "/day09/servlet/ServletDemo8");
System.out.println("我去找8借去");
}



public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}

 

}

 

(2)package com.wc.response;


import java.io.IOException;
import java.io.PrintWriter;


import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class ServletDemo8 extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("8:我有钱,我借给你");
}



public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}


}

    

 

你可能感兴趣的:(javaweb重定向)