1. 程式人生 > >javaweb登陸,登出功能實現的一般步奏

javaweb登陸,登出功能實現的一般步奏

1.在UserAction中新增三個方法,如下:

   /** 登陸頁面 */
public String loginUI() throws Exception {
return "loginUI";
}

/** 登陸*/
public String login() throws Exception {
User user=userService.findByLoginNameAndPassword(model.getLoginName(),model.getPassword()); //注意,此方法需要在service層實現,具體程式碼在步驟2

if(user==null){
//登陸失敗,提示相關訊息
addFieldError("login", "使用者名稱或密碼錯誤");
return "loginUI";
}else{
//登陸成功
ActionContext.getContext().getSession().put("user", user);
}
return "toIndex";
}

/** 登出 */
public String logout() throws Exception {
ActionContext.getContext().getSession().remove("user");
return "logout";
}

2.

在UserService新增

 User findByLoginNameAndPassword(String loginName, String password);

在UserServiceImpl中實現

public User findByLoginNameAndPassword(String loginName, String password) {
return (User) getSession().createQuery(//
"from User u where u.loginName=? and u.password=?")//
.setParameter(0, loginName)//
.setParameter(1, DigestUtils.md5Hex(password))//
.uniqueResult();
}

3.配置struts.xml

  <!-- 使用者管理 -->
<action name="userAction_*" class="userAction" method="{1}">
<result name="list">/WEB-INF/jsp/userAction/list.jsp</result>
<result name="addUI">/WEB-INF/jsp/userAction/addUI.jsp</result>
<result name="editUI">/WEB-INF/jsp/userAction/editUI.jsp</result>
<result name="loginUI">/WEB-INF/jsp/userAction/loginUI.jsp</result>
<result name="login" type="redirect">index.jsp</result>
<result name="logout">/WEB-INF/jsp/userAction/logout.jsp</result>
<result name="toList" type="redirectAction">userAction_list</result>
</action>

4.新增相應的頁面,執行即可