首先是新建一個servlet,servlet中有dopost和doget方法
一般的表格提交都是用post方法,故在dopost里面寫入邏輯代碼
下面是其邏輯代碼Check.java
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //獲取表單提供的數據 String name=request.getParameter("username"); String pwd=request.getParameter("password"); //數據庫相關參數 String url="jdbc:mysql://localhost:3306/office?useSSL=false&serverTimezone=Hongkong&characterEncoding=utf-8&autoReconnect=true"; String username="root"; String password="123456"; //執行的sql語句 String sql="select username,password from user where username=? and password=?"; //jdbc的三個接口 Connection con=null;
//預處理 PreparedStatement stmt=null; ResultSet res=null; try { //加載驅動
Class.forName("com.mysql.cj.jdbc.Driver");
//建立連接 con=DriverManager.getConnection(url,username,password);
//預編譯 stmt=con.prepareStatement(sql);
//向sql中傳入參數 stmt.setString(1,name ); stmt.setString(2, pwd);
//執行查詢 res=stmt.executeQuery();
//遍歷結果集 while(res.next()) {
//在結果集中查找列數據 String username1=res.getString("username"); String password1=res.getString("password");
//邏輯判斷 if(name.equals(username1)&&pwd.equals(password1)) {
//重定向 RequestDispatcher rd=request.getRequestDispatcher("success.jsp"); rd.forward(request, response); return; }else { RequestDispatcher rd1=request.getRequestDispatcher("faile.jsp"); System.out.println(username1); System.out.println(password1); rd1.forward(request, response); return; } } res.close(); stmt.close(); con.close(); } catch (ClassNotFoundException | SQLException e) { e.printStackTrace(); } }
其次,我們是通過form的action進行服務端校驗的,所以需要配置servlet,讓程序找到我們的servlet
<?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_4_0.xsd" version="4.0"> <display-name>servlet</display-name> <!--配置Servlet--> <servlet> <!-- Servlet應用名 --> <servlet-name>Check</servlet-name> <!-- 對應的servlet的類 --> <servlet-class>servlet.Check</servlet-class> </servlet> <!-- 地址映射 --> <servlet-mapping> <!-- 設置的servlet應用名 --> <servlet-name>Check</servlet-name> <!-- 地址名 --> <url-pattern>/Check</url-pattern> </servlet-mapping> <session-config> <session-timeout>30</session-timeout> </session-config> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file>default.html</welcome-file> <welcome-file>default.htm</welcome-file> <welcome-file>default.jsp</welcome-file> </welcome-file-list> </web-app>
1.輸入地址:http://localhost:8080/login,提交表格后,來到http://localhost:8080/Check,通過它找到映射文件內部的文件名Check
2.通過Check找到對應的<servlet-name>Check</servlet-name>
3.然后定位到這個servlet文件:servlet.Check.java