从ActionSupport继承,按照约定写好方法add等,用Domain Model接收参数,需要访问session用IOC访问
- Helloworld~
- copy struts.xml → src
- add (类库 .jar 文件) → lib
- 配置web.xml
- action执行过程
- struts2作用是把请求和视图分开
- struts2永不会有线程同步的问题,每次访问action都会自动new一个新对象
- namespace
- 决定了action的访问路径,默认为"",可以接收所有路径的actionnamespace可以写为/,或者/xxx,或者/xxx/yyy,对应的action访问路径为/index.action,/xxx/index.action,或者/xxx/yyy/index.action.namespace最好也用模块来进行命名
- 具体视图的返回由用户自己定义的action来决定。具体的手段是根据返回的字符串找到对应的配置项,来决定视图的内容。具体action的实现可以使一个普通的java类,里面有public String execute方法即可,或者实现action接口。不过最常用的是从actionsupport继承,好处在于可以直接使用Struts2封装好的方法。
- struts中的路径问题
- 是根据action的路径而不是jsp路径来确定,尽量不要使用相对路径index.jsp。解决方法统一使用绝对路径(在jsp中用request.getContextRoot方式拿到webapp的路径)或指定basePath。String path = request.getContextPath();//取得webapplication项目路径 。String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";//取得http、localhost、8080、path字符串,获得绝对路径http://localhost:8080/webapp/
- 实现action最常用的方法,从ActionSupport继承 。
- 1)如果你的Action类是继承自ActionSupport的话,确切的说是重写了execute方法,ActionSupport里的默认实现就是返回"success"视图。因此,你可以不实现execute方法,只要你的struts.xml里有"success"对应的result即可。2)如果你的Action类没有继承ActionSupport,而你又没有在struts.xml中对应<action>标签中用method属性指定你自己的方法的话,默认就要找execute方法,这时是必须要实现execute方法的,否则Struts2会找不到对应的方法而报错。不过,大部分情况下都是继承ActionSupport的(比如输入验证、文件上传等功能就要求必须继承)。还有,不管你写没写execute方法,还是可以用<action>标签的method属性指定其他方法的。
- action执行时不一定要执行execute方法,可以在配置文件中配置action是用method=来指定执行那个方法,也可以在url地址中动态指定(动态方法调用DMI 推荐),叹号!调用action的方法。例:http://localhost:8080/struts2_user/user/user!add
- 开发模式: 在struts.xml中设置 <constant name="struts.devMode" value="true" />
- 对于请求,action先匹配最精确的,包括*的则看action前后位置
- 通配符:将配置量降到最低,约定优于配置
- <action name="*_*" class="com.bjsxt.struts2.action.{1}Action" method="{2}"> <result>/{1}_{2}_success.jsp</result> </action>
- 接收参数:
- action属性接收 例: http://localhost:8080/struts2_user/user/user!add?name=a&age=8
- Domain Model → DTO数据传输对象 最常用 Private User user;getUser,setUser
- Model Driven → MVC(M:model→User V:view→.jsp C:control→action)
- 简单参数验证 this.addFieldError("name","value");
- 调用struts2标签库 <%@taglib uri="/struts-tags" prefix="s"%> (uri指定taglib在什么位置,prefix指定标签前缀)
- 不常用标签 <s:fielderror fieldName="name"/> 固定xhtml为展现标签的默认主题
- 常用标签 <s: property value="errors.name[0]"/> (取得action属性中value stack的内容)
- 常用debug标签 <s:debug></s:debug>
- 访问web元素
- 取得Map类型(request,session,application) 依靠struts容器 或 Ioc(inverse of control)
- <s:property value="#request.r1"/> (取得action属性中stack context的内容,需要加#)
- 取得真实类型 (HttpRequest,HttpSession,ServletContext)
- 包含文件配置 <include file="login.xml"/>
- 默认action <default-action-ref name="index"></。。。>