基于servlet的登录实现
1.连接数据库
- public static Connection getConnection() throws ClassNotFoundException, SQLException {
Class.forName(“com.mysql.jdbc.Driver”);
Connection conn = DriverManager.getConnection(“jdbc:mysql://localhost:3306/asd”,“用户名”,“密码”);
return conn;
} - 结束时释放资源
re.close();
stmt.close();
conn.close();
2.查询操作
conn = util.getConnection();
ps = conn.prepareStatement(“select * from user where name = ?”);
ps.setString(1,name);
rs = ps.executeQuery();
while(rs.next()){
user.setId(rs.getInt(1));
user.setName(rs.getString(2));
user.setPassword(rs.getString(3));
user.setAge(rs.getString(4));
在dao里写入查询语句,将查询的结果存放的rs中,在将里面存储提取出来并返回。
3.界面和调用
4.数据对比
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String name = req.getParameter(“name”);
//获取到的数据被编码成iso8859-1,先解码
byte[] buf = name.getBytes(“iso8859-1”);
//重新编码
name= new String(buf,“utf-8”);
String password = req.getParameter(“password”);
User user = userService.selectByName(name);
if(password.equals(user.getPassword()))
{
resp.getWriter().write(“success”);
}else {
resp.getWriter().write(“failed”);
}
}
将网页上输入的密码与数据库中的相对比,如果相同就显示成功
5.运行结果与数据库
这样就成功通过servlet完成登录功能了。
配置相关
jdk为1.8,webapp项目,服务器为tomcat8.0.27