新建一個web項目;配置web.xml如下
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1"> <servlet> <servlet-name>test01</servlet-name> <!-- 指定servlet的類路徑 --> <servlet-class>com.cn.Demo1</servlet-class> <!-- 可以添加需要初始化的參數 --> <init-param> <param-name>arg0</param-name> <param-value>123</param-value> </init-param> </servlet> <!-- servlet的指定攔截請求 --> <servlet-mapping> <servlet-name>test01</servlet-name> <url-pattern>/test01.do</url-pattern> </servlet-mapping> </web-app>
新建一個java類,代碼如下
/** * 測試原生seervlet,新建一個類繼承HttpServlet * @author Lenovo * */ public class Demo1 extends HttpServlet { /** * 如果是get請求就重寫doget方法,如果是其他的也是一樣對應的 */ @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("測試-----------------------"); //可以獲取xml配置的初始參數 System.out.println(getInitParameter("arg0")); //重定向到另一個頁面,req.getContextPath()這個方法可以獲取項目的路徑 resp.sendRedirect(req.getContextPath()+"/index.jsp"); } }
然后進行測試,通過瀏覽器訪問