首先,我们先来模拟一个环境:当你登录的时候,dao中根据username查询对象,如果没有查到该对象,service中抛出异常:用户不存在,如果查到了,该对象中封装了数据库中该对象的所有数据,在service中校验用户输入的密码与数据库中的密码,若密码不正确,抛出异常:密码错误,若校验通过,返回给action一个User对象
Dao:
/**
* 注入设置sessionFactory
*/
@Autowired
public void setSessionFacotry(SessionFactory sessionFacotry) {
super.setSessionFactory(sessionFacotry);
}
/**
* 根据用户名查询用户
*/
public User findUserByUserCode(String userCode) {
return super.getHibernateTemplate().execute(
new HibernateCallback<User>() {
public User doInHibernate(Session session)
throws HibernateException {
String hql = "from User where user_code=?";
Query query = session.createQuery(hql);
query.setParameter(0, userCode);
return (User) query.uniqueResult();
}
});
}
Service:
@Autowired
private UserDao userDao;
/**
* 用户登录
*/
public User userLogin(User user) {
User queryUser = userDao.findUserByUserCode(user.getUser_code());
if(queryUser == null) {
throw new RuntimeException("用户不存在");
}
if(!queryUser.getUser_password().equals(user.getUser_password())) {
throw new RuntimeException("密码错误");
}
return queryUser;
}
Action:
@Controller
@Scope("prototype")
public class UserAction extends ActionSupport implements ModelDriven<User> {
private User user = new User();
@Override
public User getModel() {
return user;
}
@Autowired
private UserService userService;
public String login() {
User queryUser = userService.userLogin(user);
ActionContext.getContext().getSession().put("user", queryUser);
return "toHome";
}
}
struts.xml:
<struts>
<!-- Spring管理Struts -->
<constant name="struts.objectFactory" value="spring"></constant>
<package name="user" namespace="/" extends="struts-default">
<!-- 全局异常处理 -->
<global-exception-mappings>
<exception-mapping result="error" exception="java.lang.RuntimeException"></exception-mapping>
</global-exception-mappings>
<action name="userAction_*" class="userAction" method="{1}">
<result name="toHome" type="redirect">/index.htm</result>
<result name="error">/login.jsp</result>
</action>
</package>
</struts>
在登录页面中使用struts的标签直接处理异常:
<TD style="HEIGHT: 18px" colspan="2" ><font color="red" ><s:property value="exception.message" /> </font></TD>