Struts2的异常处理机制

    首先,我们先来模拟一个环境:当你登录的时候,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>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值