1 编写Servlet类
继承HttpServlet,重写父类中的doGet和doPost方法,就可以用来处理GET和POST请求的业务逻辑
public class ServletDemo5 extends HttpServlet {
@Override
protected void doGet(ServletRequest req, ServletResponse res) {
System.out.println("get...");
}
@Override
protected void doPost(ServletRequest req, ServletResponse res) {
System.out.println("post...");
}
}
配置url(使用xml或者注解的方式)
@WebServlet("/login")
public class ServletDemo5 extends MyHttpServlet {
@Override
protected void doGet(ServletRequest req, ServletResponse res) {
System.out.println("get...");
}
@Override
protected void doPost(ServletRequest req, ServletResponse res) {
System.out.println("post...");
}
}
2 获取用户输入数据
String username = request.getParameter("username");
String paw = request.getParameter("paw");
3调用查询方法查询数据库用户名和密码
//1接受用户名和密码
String username = request.getParameter("username");
String password = request.getParameter("paw");
//2调用mybatis完成查询
//获取sqlSessionFactory对象 使用工具类进行代码抽取
SqlSessionFactory sqlSessionFactory = SqlSessionFactorytest.getSqlSessionFactory();
//获取sqlSession对象
SqlSession sqlSession = sqlSessionFactory.openSession();
//获取mapper对象
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
//调用方法
User user = mapper.select(username, password);
//关闭资源
sqlSession.close();
4 判断有没有数据并设置响应
//获取对应的字符输出流 并设置中文格式
response.setContentType("text/html;charset=utf-8");
PrintWriter writer = response.getWriter();
//3判断是否为null
if (user!=null){
//登录成功
writer.write("登录成功");
}else {
//登录失败
writer.write("该用户不存在,请注册");
}
}
5 展示