1. 程式人生 > >使用Mybatis實現登入

使用Mybatis實現登入

dao層介面 


public interface UserMapper {
    //登入
    public Users login(Users users);
}

UserMapper的xml對映 


<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.sms.dao.user.UserMapper">
	<!-- 登入 -->
	<select id="login" resultType="com.sms.pojo.Users">
		SELECT * FROM `smbms_user` WHERE userCode = #{userCode}
	</select>
</mapper>

Service實現 

    // 登入
	public Users login(Users users) {
		SqlSession sqlSession = null;
		try {
			// 開啟會話
			sqlSession = MyBatisUtil.openSqlsession();
			// 呼叫getMapper(UserMapper.class)執行Mapper介面方法
			users = sqlSession.getMapper(UserMapper.class).login(users);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			// 關閉會話
			MyBatisUtil.closeSqlsession(sqlSession);
		}
		return users;
	}

 Servlet

	public void login(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {

		HttpSession session = request.getSession();
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		// 絕對路徑
		String path = request.getContextPath();
		// 通過物件傳參
		Users users = new Users();
		// 設定使用者名稱
		users.setUserCode(username);
		// 設定密碼
		users.setUserPassword(password);
		// 例項化業務邏輯
		UserService service = new UserServiceImpl();
		// 呼叫登入介面
		users = service.login(users);
		if (users != null) {
			//判斷輸入使用者名稱是否正確
			if (!password.equals(users.getUserPassword())) {
				request.setAttribute("message", "密碼錯誤,請重新輸入");
				goTo("/login", request, response);
			} else {
				session.setAttribute(Conts.SESSION_NAME, users);
				session.setMaxInactiveInterval(30);
				redirect("/jsp/main", request, response);
			}
		} else {
			request.setAttribute("message", "使用者名稱不存在");
			goTo("/login", request, response);
		}
	}

在 MyBatis-conf.xml 中將SQL對映進行註冊  

<mappers>
	<!-- 將編寫好的sql對映檔案進行註冊 -->
		<mapper resource="com/sms/dao/user/UserMapper.xml" />
</mappers>