Spring+Hibernate+Struts2整合之实现登录功能

时间:2023-03-09 07:33:32
Spring+Hibernate+Struts2整合之实现登录功能

前端代码:

<form id="loginForm" action="${ pageContext.request.contextPath }/user_login.action"  method="post" novalidate="novalidate">
<table>
<tbody><tr>
<th>
用户名:
</th>
<td>
<input type="text" id="username" name="username" class="text" maxlength="20" onclick="toggle('div1')";/><span><s:fielderror fieldName="username"/></span>
</td>
</tr>
<tr>
<th>
密  码:
</th>
<td>
<input type="password" id="password" name="password" class="text" maxlength="20" autocomplete="off" onclick="toggle('div1')";/><span><s:fielderror fieldName="password"/></span>
</td>
</tr>
  <tr>
<td>
<input type="submit" class="submit" value="登 录">
</td>
</tr>
</tbody></table>
</form>

  

登录的action:

//前台:登录功能
@InputConfig(resultName="loginInput")
public String login(){ User existUser = userService.login(user); if(existUser==null){ this.addActionMessage("用户名或密码错误或用户未激活!");
return "loginInput";
}else{
ServletActionContext.getRequest().getSession().setAttribute("existUser", existUser);return "loginSuccess";
}
}

登录的service:

//业务层登录方法
public User login(User user) {
// TODO Auto-generated method stub
System.out.println("用户名:"+user.getUsername()+" 密码:"+user.getPassword());
return userDAO.login(user);
}

登录的DAO:

@Override
public User login(User user) {
// TODO Auto-generated method stub
String queryString = "from User where username = ? and password = ?";
List<User> list = this.getHibernateTemplate().find(queryString,user.getUsername(),user.getPassword());
if(list.size()!=0){
return list.get(0);
}
return null;
}

配置struts.xml:

<!-- 配置用户的action -->
<action name="user_*" class="userAction" method="{1}">
<result name="loginInput">/WEB-INF/jsp/login.jsp</result>
<result name="loginSuccess type="redirectAction">index</result>
</action>

配置applicationContext.xml:

<!-- 配置action -->
<bean id="userAction" class="com.ansibee.shop.web.action.UserAction" scope="prototype">
<property name="userService" ref="userService"></property>
</bean> <!-- 配置service -->
<bean id="userService" class="com.ansibee.shop.service.UserService">
<property name="userDAO" ref="userDAOImpl"></property>
</bean> <!-- 配置Dao -->
<bean id="userDAOImpl" class="com.ansibee.shop.daoImpl.UserDAOImpl">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>