代码实现
package com.itheima.mapper; import com.itheima.pojo.User; import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Select; public interface UserMapper { @Select("select * from tb_user where username = #{username} and password =#{password}") User select(@Param("username") String username,@Param("password") String password); }
package com.itheima.pojo; public class User { private Integer id; private String username; private String password; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } @Override public String toString() { return "User{" + "id=" + id + ", username='" + username + '\'' + ", password='" + password + '\'' + '}'; } }
package com.itheima.web; import com.itheima.mapper.UserMapper; import com.itheima.pojo.User; 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 javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; @WebServlet("/loginServlet") public class LoginServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //1.接收用户名和密码 String username=request.getParameter("username"); String password=request.getParameter("password"); //2.调用MyBatis完成查询 //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 UserMapper = sqlSession.getMapper(UserMapper.class); //2.4 调用方法 User user = UserMapper.select(username, password); //2.5 释放资源 sqlSession.close(); //获取字符输出流writer,并设置content type response.setContentType("text/html;charset=utf-8"); PrintWriter writer = response.getWriter(); //3.判断user是否为null if (user != null){ //登录成功 使用write方法返回出字符 writer.write("登陆成功"); }else { //登录失败 使用write方法返回出字符 writer.write("登录失败"); } } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request,response); } }
标签:username,String,登录,代码,id,案例,import,password,public From: https://www.cnblogs.com/Karl-hut/p/17512416.html