javaweb重定向

人生若崇仁厚德發表於2018-05-03

若伺服器狀態碼返回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 {
}


}

    

 

相關文章