做练习的Jsp 连接 MySql 小实例

public class LoginServlet extends HttpServlet {


public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
doPost(request, response);
}


public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
String name = request.getParameter("username");
String passwd=request.getParameter("passwd");
boolean correctTF = false;
String DriverName = "com.mysql.jdbc.Driver";
String DBuser = "root";
String DBpasswd = "root";
String DBUrl = "jdbc:mysql://localhost:3306/appuser";


try {
// 加载驱动
Class.forName(DriverName);
// 创建与数据库链接
Connection conn = (Connection) DriverManager.getConnection(DBUrl,DBuser, DBpasswd);
// 创建语句对象
Statement stmt = (Statement) conn.createStatement();
// 创建SQL查询
String sql = "select * from `user` WHERE username='" + name + "' and `password`='"+passwd+"' ";
// 执行语句
ResultSet rs = stmt.executeQuery(sql);

if (rs.next()) {
correctTF = true;
//设置Session
HttpSession session=request.getSession();
session.setAttribute("User", name);
rs.close();
stmt.close();
conn.close();
} else {
correctTF = false;
rs.close();
stmt.close();
conn.close();
}// 没有记录关闭链接


} catch (Exception e) {
e.printStackTrace();
}
if (correctTF == true) {
RequestDispatcher reqD = request.getRequestDispatcher("Index.jsp");
reqD.forward(request, response);
} else {
response.sendRedirect("LoginError.jsp");
}
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值