实现用户登录和用户注册,并通过MyBatics数据库判断输入的内容是否正确
步骤:
准备工作:
1、根据已经学过的数据库命令创建一个新表,并进行添加、查询等操作;
2、创建一个关于persons的实体类,里面存放persons的各个属性;
3、将需要用到的MyBatis等相关导包导入到.xml文件中,如图所示:(即导入MyBatis依赖坐标和MYSQL依赖坐标)
4、创建mybatis-config.xml核心配置文件,UserMapper.xml映射文件,UserMapper接口
可以在这个网址直接将获取sqlSession对象的代码复制粘贴到程序中:https://mybatis.net.cn/
LoginServlet.java,代码仅供参考,仅仅提供一个相关内容的模板,具体操作实现还需要加以修改:
package org.example.web;
import jakarta.servlet.*;
import jakarta.servlet.http.*;
import jakarta.servlet.annotation.*;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.example.mapper.UserMapper;
import org.example.pojo.User;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
@WebServlet("/registerServlet")
public class RegisterServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 接收用户输入的数据
String username = request.getParameter("username");
String password = request.getParameter("password");
// 封装用户对象
User user = new User();
user.setUsername(username);
user.setPassword(password);
// 调用MyBatis完成查询
// 获取SqlSessionFactory对象
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
// 获取SqlSession对象
SqlSession sqlSession = sqlSessionFactory.openSession();
// 获取Mapper
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
// 获取字节输出流
response.setContentType("text/html");
PrintWriter writer = response.getWriter();
// 查询用户名是否存在
if (userMapper.selectByUsername(username) != null) {
// 用户名已存在
writer.write("用户名已存在");
} else {
// 不用户名不存在,添加数据
userMapper.add(user);
// 提交事务
sqlSession.commit();
}
// 释放资源
sqlSession.close();
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
}
标签:登录,request,UserMapper,实用,案例,sqlSession,import,org,response
From: https://www.cnblogs.com/liuzijin/p/16727972.html