IDEA配置Servlet

Step1: 在src目录下新建Servlet目录,在里面新建一个IndexServlet.class的Java文件。

Step2: 继承HttpServlet,实现 doGet()doPost() 方法,其中在 doGet() 里面调用 doPost() 方法,这样就默认使用post请求。

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    doPost(req, resp);
}

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String name = req.getParameter("name");
    String password = req.getParameter("password");
    System.out.println("你的名字:" + name);
    System.out.println("你的密码:" + password);
}

Step3: 在WEB-INF目录下的 wed.xml 文件中配置Servlet映射(注意:要写在 web-app 标签里面)。

<!--配置Servlet-->
<servlet>
    <!--给对应的Servlet请个名字-->
    <servlet-name>IndexServlet</servlet-name>
    <servlet-class>Servlet.IndexServlet</servlet-class>
</servlet>
<!--配置Servlet映射-->
<servlet-mapping>
    <!--找到对应的Servlet对应的名字-->
    <servlet-name>IndexServlet</servlet-name>
    <!--配置对应的url地址-->
    <url-pattern>/IndexServlet</url-pattern>
</servlet-mapping>

Step4: 在表单中的 aciton 配置相应的Servlet名称

<form method="post" action="IndexServlet">
    用户名:<input type="text" name="name">
    密码:<input type="password" name="password">
    <input type="submit" name="提交">
    <input type="reset" name="重置">
</form>

 


❤️ END ❤️
Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐