新建一个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"); } }
然后进行测试,通过浏览器访问