使用IDEA 建立簡單servlet表單專案例項
阿新 • • 發佈:2020-11-14
選擇new->project,如圖
命名mypro
在WEB-INF檔案下建立classes和lib兩個資料夾
更改專案輸出為剛才建立的classes
在web上右鍵新建register.jst,建立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
在瀏覽器輸入測試地址: