Struts2学习笔记三(异常处理、模型驱动和属性驱动、servlet接口、Preparable接口)

来源:互联网 发布:rsc数据库 编辑:程序博客网 时间:2024/04/19 08:05

1、自定义异常:

       public class UsernameException extends Exception

public String execute() throws Exception {if(!"123".equals(username)){throw new UsernameException("username invalid");}if(!"123".equals(password)){throw new PasswordException("password invalid");}return SUCCESS;}

2、接受异常,然后跳转。

<action name="login" class="com.yanlei.struts2.LoginAction"><result name="success">/result.jsp</result><span style="color:#ff0000;"><exception-mapping result="</span><span style="color:#00cccc;">usernameInvild</span><span style="color:#ff0000;">" exception="com.yanlei.exception.UsernameException"></exception-mapping><exception-mapping result="passwordInvild" exception="com.yanlei.exception.PasswordException"></exception-mapping><result name="</span><span style="color:#00cccc;">usernameInvild</span><span style="color:#ff0000;">">/usernameInvild.jsp</result><result name="passwordInvild">/passwordInvild.jsp</result></span></action>
3、也可定义在全局内,可以被所有action共用。

<global-results><result name="usernameInvalid">/usernameInvalid.jsp</result><result name="passwordInvalid">/passwordInvalid.jsp</result></global-results><global-exception-mappings><exception-mapping result="usernameInvalid" exception="com.shengsiyuan.exception.UsernameException"></exception-mapping><exception-mapping result="passwordInvalid" exception="com.shengsiyuan.exception.PasswordException"></exception-mapping></global-exception-mappings>
  但局部总是优先于全局的。


4、模型驱动如写个User类,实现modelDriven<Uset>,重写public User getMedel(){return user;}

      但一般都使用属性驱动的模式。直接写属性,不用写类。。

5、Servlet两种方式

HttpServletRequest request=ServletActionContext.getRequest();
HttpSession session=request.getSession();
session.setAttribute("hello", "struts");


ActionContext actionContext=ActionContext.getContext();
Map<String, Object> map=actionContext.getSession();
Object o=map.get("hello");

6、在传值之前做准备,action实现Preparable接口。

0 0