servlet连接数据库实现简单网页登陆
实体类user
public class User {
public User() {
}
public User(int id, String username, String password) {
this.id = id;
this.username = username;
this.password = password;
}
public User(String username, String password) {
this.username = username;
this.password = password;
}
private int id;
private String username;
private String password;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
'}';
}
}
UserDao类
public class UserDao {
public User getOneUserByUsername(String username) {
Connection connection = null;
PreparedStatement statement = null;
ResultSet resultSet = null;
User user = new User();
try {
connection = DBUtil.getConnection();
String sql = “select * from tb_user where username = ?”;
statement = connection.prepareStatement(sql);
statement.setString(1, username);
resultSet = statement.executeQuery();
while (resultSet.next()) {
user.setId(resultSet.getInt(1));
user.setUsername(resultSet.getString(2));
user.setPassword(resultSet.getString(3));
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException throwables) {
throwables.printStackTrace();
} finally {
try {
DBUtil.closeAll(resultSet, statement, connection);
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
return user;
}
创建dbutil
public class DBUtil {
public static Connection getConnection() throws ClassNotFoundException, SQLException {
Class.forName(“com.mysql.jdbc.Driver”);
Connection connection = DriverManager.getConnection(“jdbc:mysql://localhost:3306/wzsxy”,“root”,“123456”);
return connection;
}
public static void closeAll(ResultSet resultSet, Statement statement,Connection connection) throws SQLException {
if (resultSet!=null){
resultSet.close();
}
if (statement!=null){
statement.close();
}
if (connection!=null){
connection.close();
}
}
}
LoginServlet类
public class LoginServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
String username = req.getParameter(“username”);
String password = req.getParameter(“password”);
UserDao userDao = new UserDao();
if (username != null && password.equals(userDao.getOneUserByUsername(username).getPassword())) {
resp.getWriter().write(“Pass”);
} else {
resp.getWriter().write(“Fail”);
}
}
}
index.jsp
<%@ page contentType=“text/html;charset=UTF-8” language=“java” %>
web.xml
LoginServlet com.zr.servlet.LoginServlet LoginServlet /login