public interface UserMapper {
@Select("select * from tb_user where username = #{username} and password = #{password}")
User select(@Param("username") String username, @Param("password") String password);
/**
* 根据用户名查询用户对象
* @param username
* @return
*/
@Select("select * from tb_user where username=#{username}")
User selectByUsername(String username);
/**
* 添加用户
* @param user
*/
@Insert("insert into tb_user values(null,#{username},#{password})")
void add(User user);
}
RegisterServlet:
@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);
//2.调用Mapper 根据用户名查询用户对象
//2.1获取sqlSessionFactory对象
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//2.2接收sqlSession对象
SqlSession sqlSession = sqlSessionFactory.openSession();
//2.3获取Mapper
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
//2.4调用方法
User u = mapper.selectByUsername(username);
// 判断用户对象是否为null
if (u == null){
//用户名不存在 可以注册
mapper.add(user);
//提交事务
sqlSession.commit(true);
//释放资源
sqlSession.close();
}else {
//用户名已存在
response.setContentType("text/html;charset=utf-8");
PrintWriter writer = response.getWriter();
writer.write("用户名已存在");
}
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
}