最简单的Servlet继承HttpServlet查询数据库登录验证
<%-- Created by IntelliJ IDEA. User: yunqing Date: 2017-12-06 Time: 9:11 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>login</title> </head> <body> <form action="/LoginFromMysql" method="post"> 用户名:<input type="text" name="username"> 密码:<input type="password" name="password"> <input type="submit" value="submit"> </form> </body> </html>
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_3_1.xsd" version="3.1"> <!-- 从数据库查询登录--> <servlet> <servlet-name>fromMysql</servlet-name> <servlet-class>com.yunqing.servlet.LoginFromMysql</servlet-class> </servlet> <servlet-mapping> <servlet-name>fromMysql</servlet-name> <url-pattern>/LoginFromMysql</url-pattern> </servlet-mapping> </web-app>
LoginFromMysql.java
package com.yunqing.servlet; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.sql.*; public class LoginFromMysql extends HttpServlet { public static final String url = "jdbc:mysql://localhost:3306/mybatis"; public static final String name = "root"; public static final String pass = "5678"; Connection conn = null; PreparedStatement ps = null; ResultSet rs = null; @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//获取前端表单中的数据 String username = req.getParameter("username"); String password = req.getParameter("password"); try { //需要添加mysql-connector-java-xxx-bin.jar(在idea中需要把jar包放到TomCAT的lib目录中) Class.forName("com.mysql.jdbc.Driver"); conn = DriverManager.getConnection(url,name,pass); String sql = "SELECT COUNT(id) FROM t_user t WHERE t.name = ? AND t.gender = ?"; ps = conn.prepareStatement(sql); ps.setString(1,username); ps.setString(2,password); rs = ps.executeQuery(); while (rs.next()) { int count = rs.getInt(1); if (count > 0) { resp.getWriter().print("Success=" + username); } else { resp.getWriter().print("Error=" + username + "BCZ"); } } } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } finally { try { if (rs != null) { rs.close(); } if (ps != null) { ps.close(); } if (conn != null) { conn.close(); } } catch (SQLException e) { e.printStackTrace(); } } } }