- 选择new->project,如图
- 命名mypro
- 在WEB-INF文件下创建classes和lib两个文件夹
- 更改项目输出为刚才创建的classes
- 在web上右键新建register.jsp,创建jsp表单提交页面
<%-- Created by IntelliJ IDEA. User: TOM Date: 2020/11/14 Time: 19:14 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>post表单提交</title> </head> <body> <form action="RegServlet" method="post"> 请输入信息: <table> <tr> <td>客户名:</td> <td><input type="text" name="uname" id="uname"/></td> </tr> <tr> <td>邮箱地址:</td> <td><input type="text" name="email" id="email"/></td> </tr> <tr> <td>电话:</td> <td><input type="text" name="mobile" id="mobile"/></td> </tr> </table> <input type="submit" value="确定"/> <input type="reset" value="重置"/> </form> </body> </html>
- 在src上右键,新创建servlet类
package com.howdy; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; @WebServlet(name = "RegServlet") public class RegServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); response.setContentType("text/html;charset=utf-8"); PrintWriter out =response.getWriter(); String uname=request.getParameter("uname"); String email=request.getParameter("email"); String mobile=request.getParameter("mobile"); out.println("<html>"); out.println("<body>"); out.println("<h3>您的名字是:"+uname+" </h3>"); out.println("<h3>您的email是:"+email+" </h3>"); out.println("<h3>您的电话是:"+mobile+" </h3>"); out.println("</body>"); out.println("</html>"); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } }
- 在web中的web.xml添加如下配置
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" version="4.0"> <servlet> <servlet-name>RegServlet</servlet-name> <servlet-class>com.howdy.RegServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>RegServlet</servlet-name> <url-pattern>/RegServlet</url-pattern> </servlet-mapping> <!-- <servlet-mapping>--> <!-- <servlet-name>RegServlet</servlet-name>--> <!-- <url-pattern>/mypro/RegServlet</url-pattern>--> <!-- </servlet-mapping>--> </web-app>
注意此地方是两种写法:
<url-pattern>/mypro/RegServlet</url-pattern> --->form的action应该是mypro/RegServlet <url-pattern>/RegServlet</url-pattern> --->form的action应该是RegServlet
- 运行项目时,单击edit configuration
- 在浏览器输入测试地址: