首先是新建一个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