jdbc mysql登录_Servlet+Jdbc+mysql实现登陆功能

首先是新建一个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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值