使用者登入模組 - 1 基本的登陸功能
阿新 • • 發佈:2020-12-06
使用者登入模組 - 1 基本的登陸功能
-
基本流程
-
webapp/login.jsp
- form表單提交的action路徑
- /system/user?operation=login
- form表單提交的action路徑
-
UserServlet - login方法
-
UserService + UserServiceImpl
- login方法
-
UserDao - findByEmailAndPwd方法
-
UserDao.xml - findByEmailAndPwd查詢
-
(1)找到專案webapp/login.jsp
登陸頁面,修改form表單提交的action路徑
<form action="${pageContext.request.contextPath}/login?operation=login" method="post"> </form>
(2)在後臺UserServlet
新增登陸的方法
private void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String email = request.getParameter("email"); String pwd = request.getParameter("password"); User user = userService.login(email,pwd); if(user != null) { request.getSession().setAttribute("loginUser", user); //跳轉頁面 request.getRequestDispatcher("/WEB-INF/pages/home/main.jsp").forward(request, response); }else{ response.sendRedirect(request.getContextPath()+"/login.jsp"); } }
(3)在因為層介面UserService
中新增登陸的方法
/**
* 根據郵箱和密碼登入
* @param email
* @param pwd
* @return
*/
User login(String email, String pwd);
(4)在對應的實現類中去實現登陸方法
@Override public User login(String email, String pwd) { SqlSession sqlSession = null; try{ //1.獲取SqlSession sqlSession = MapperFactory.getSqlSession(); //2.獲取Dao UserDao userDao = MapperFactory.getMapper(sqlSession,UserDao.class); //3.呼叫Dao層操作 pwd = MD5Util.md5(pwd); return userDao.findByEmailAndPwd(email,pwd); }catch (Exception e){ throw new RuntimeException(e); //記錄日誌 }finally { try { TransactionUtil.close(sqlSession); }catch (Exception e){ e.printStackTrace(); } } }
(5)在UserDao
介面中新增查詢方法
User findByEmailAndPwd(@Param("email")String email, @Param("password")String pwd);
(6)在UserDao.xml
中新增查詢
<select id="findByEmailAndPwd" parameterType="map" resultMap="BaseResultMap">
select
<include refid="Base_Column_List"/>
from ss_user
where email = #{email,jdbcType=VARCHAR} and password = #{password,jdbcType=VARCHAR}
</select>
(7)將原本在webapp/pages/home
下的所有頁面統一挪到/WEB-INF/pages
下,注意是連同home
目錄一起挪
(8)修改/WEB-INF/pages/home/main.jsp
內容區的路徑
<!-- 內容區域 -->
<div class="content-wrapper">
<iframe id="iframe" name="iframe"
style="overflow:visible;"
scrolling="auto"
frameborder="no" height="100%" width="100%"
src="${ctx}/system/user?operation=home"></iframe>
</div>
(9)在後臺UserServlet
中新增方法
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String operation = request.getParameter("operation");
if("list".equals(operation)){
this.list(request,response);
}
//中間省略
else if("home".equals(operation)){
this.home(request,response);
}
}
private void home(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.getRequestDispatcher("/WEB-INF/pages/home/home.jsp").forward(request, response);
}