首先是新建一个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
servlet
Check
servlet.Check
Check
/Check
30
index.html
index.htm
index.jsp
default.html
default.htm
default.jsp
1.输入地址:http://localhost:8080/login,提交表格后,来到http://localhost:8080/Check,通过它找到映射文件内部的文件名Check
2.通过Check找到对应的Check
3.然后定位到这个servlet文件:servlet.Check.java