Java Web學習(31): Servlet學習(四)
阿新 • • 發佈:2019-01-23
package com.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class TestServlet
*/
@WebServlet(name="TestServlet" ,urlPatterns={"/TestServlet"})
public class TestServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public TestServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see Servlet#init(ServletConfig)
*/
public void init(ServletConfig config) throws ServletException {
// TODO Auto-generated method stub
}
/**
* @see Servlet#destroy()
*/
public void destroy() {
// TODO Auto-generated method stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
//使用請求重定向方式跳轉到test.jsp頁面
/*
* 請求重定向,將方法中的地址引數傳遞給瀏覽器,讓瀏覽器重新發送請求,
* "/"代表(相對於)伺服器根目錄http://localhost:8000/
* 所以相當於瀏覽器重新請求了絕對路徑http://localhost:8000/專案名/test.jsp
*/
//使用request.getContextPath()獲取專案名
response.sendRedirect(request.getContextPath() +"/test.jsp");
//response.sendRedirect("/test.jsp");//錯誤的
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}