public class LoginServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String username = req.getParameter("username");
String password = req.getParameter("password");
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "123456");
String sql = "select * from t_user where username=? and password=?";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, username);
ps.setString(2, password);
ResultSet rs = ps.executeQuery();
UserInfo userInfo = null;
while (rs.next()) {
userInfo = new UserInfo();
userInfo.setId(rs.getInt("id"));
userInfo.setUsername(rs.getString("username"));
userInfo.setPassword(rs.getString("password"));
}
resp.setContentType("text/html;charset=utf-8");
if (userInfo != null) {
resp.getWriter().write("登录成功");
} else {
resp.getWriter().write("登录失败");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}