struts框架知识点总结<一>
来源:互联网 发布:win7如何卸载软件 编辑:程序博客网 时间:2024/04/30 13:56
第一部分 Struts2基础
1.Struts2的工作原理
1.Struts工作流程
1.用户发送一个HttpServletRequest请求
2.请求会经过一系列的过滤器来传递
3.调用filterdispatcher,询问actionMapper是否需要调用某个action,如果需要就把请求转交给actionproxy
4.actionproxy会根据配置文件struts.xml文件找到具体的action
5.actionproxy会在actionivocation的前后,调用action有关的拦截器interceptor
6.action执行完,根据配置文件struts.xml找到具体的返回结果
7.最后,httpServletreponse响应通过web.xml文件中配置的过滤器返回
2.从MVC角度理解struts框架
1.filterDispatcher—控制层:
负责根据用户提交的URL和struts.xml中的配置,来选择合适的动作action,让这个action来处理用户的请求
2.Action—模型层:
负责把用户请求中的参数组装成合适 的数据模型,并调用相应的业务逻辑进行真正的处理,然后产生一个视图展示所需要的数据
3.Result—视图层:
视图层主要与用户进行交互,将控制层的数据以合适的形式展示给用户
第二部分 Struts2 核心文件
1.web.xml文件
2.struts.properties文件
3.struts.xml文件
4.action类文件
1.web.xml
web.xml主要用来配置filterdispatcher过滤器,截取web程序的http请求
1.配置欢迎页面<welcome-file-list> <welcome-file>index.jsp</welcome-file></welcome-file-list>2.声明一个过滤器<filter> <filter-name>struts2</filter-name> <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class></filter>声明拦截的URL<filter-mapping> <filter-name>struts2</filter-name> <url-pattern>/*</url-pattern></filter-mapping>3.指定错误异常页面<error-page> <error-code>404</error-code> <location>/error.jsp</location></error-page><error-page> <exception-type>java.lang.Exception</exception-type> <location>/error.jsp</location></error-page>4.注册一个监听器类<listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class></listener>5.指定会话时间<session-config><session-timeout>30</session-timeout></session-config>6.配置常量<init> <param-name>struts.il8n.encoding</param-name> <param-value>UTF-8</param-value></init>
2.struts.properties
struts.properties文件是一个key-value文件,用来管理框架中大量的常量
### 设置设置默认的编码集struts.il8n.encoding=UTF-8###设置使用开发模式struts.devMode=true###设置local为en_USstruts.local=en_USstruts.properties关键元素分析struts.il8n.encoding 指定web程序的默认编码集,一般设置为UTF-8struts.devMode 指定struts2是否使用开发模式 默认falsestruts.configuaration 指定Struts2框架的配置管理器 默认falsestruts.locale 指定该web应用的默认Locale,默认是en_USstruts.action.lotension 由Struts2处理的请求后缀 默认的后缀是actionstruts.tag.altSyntax 指定是否在Struts2标签中使用表达式语法 一般设置为truestruts.ui.theme 指定视图中Struts2标签的默认主题,默认是xhtmlstruts.custom.il8n.resources 指定web程序所需要的国际化资源文件struts.custom.properties 指定加载附加的配置文件位置struts.enable.DynamicMethodInvocation 指定Struts2框架是否支持动态方法调用,默认是truestruts.il8n.reload 指定国际化信息是否自动加载 默认是truestruts.http.port 指定web应用的端口
3.struts.xml
struts.xml文件的主要作用是配置action和http请求的对应关系,配置常量,导入其他配置文件等等
1.package元素主要用来配置包,包是一个独立的单位属性如下:name 必须属性,标识包的名字,方便被引用namesapce 可选属性 用来声明此包下的action的访问路径extends 可选属性 指定继承自其他包abstract 可选属性 指定该包为抽象包,抽象包不能定义action<package name="default" namespace="/" extends="struts-default"></package>2.action元素action对象用来处理http请求属性如下:name 必选属性 标识action ,指定了该action所处理的请求的URLclass 可选属性 指定action对象的实现类method 可选属性 指定请求action时候调用的方法convertor 可选属性 指定类型转换器类<action name="userAction" class="com.action.UserAction"></action>3.result元素result元素用来设置返回给浏览器的视图属性如下:dispatcher 将请求转发到指定的jsp页面redirect 将页面重定向到指定的视图资源chain 处理action的链freemarker 指定使用freemarker模板作为视图httpheader 控制特殊的http行为redirect-action 跳转到其他的actionstream 给浏览器返回一个inputstream 一般用户下载文件velocity 指定使用velocity模板作为视图xslt 使用xml或者xslt整合paintText 显示某个页面的原始代码<result>/success.jsp</result>4.include元素include元素用来包含其他元素,使用include元素便于模块化管理<include file="a.xml"/>5.global-results当一个action处理请求后返回时,现在action本身的局部结果中进行搜索,搜索不到会查找全局结果<global-results> <action name="user" class="com.action.UserAction"> <result name="hello">/hello.jsp</result> </action></global-results>6.default-action-ref如果找不到对应的action,使用默认的action来处理用户请求<default-action> <action name="defaultaction" class="com.action.XXXAction"> <result></result> </action></default-action>
action的动态调用DMI
单一的业务逻辑,使用execute()方法来处理没有问题
复杂的业务逻辑,使用execute()方法来判断具体的业务逻辑,转发到具体的处理方法上去
DMI的具体实现方式如下:
如配置名为user的action,调用其change()方法,方式为/user!change.action
通配符
通过一定的命名来配置action对象,达到简化action定义的效果
* 匹配0个或者多个字符除了”/”
* * 匹配0个或者多个字符包含”/”
\character 转义字符 “\”匹配”\”;”*”匹配*
<package name="login" extends="struts-default"> <!--使用*通配符,第一个表示调用方法,第二个表示action,{n}表示前面第n个*所匹配的字符串,{0}整个--> <action name"*_*" class="com.coderdream.action.{2}Action" method="1" <result name="success">/{0}.Suc.jsp</result> </action></package><!--在上面的代码中,当请求是/update_Login.action时,<action>的name属性中第一*匹配update,第二个*匹配Login,所以会对应的调用LoginAction类中的update()方法.在记过映射中的几号是{0},则会该几号会被整个URL代替.所以返回的页面是update_LoginSuc.jsp-->
常量配置
struts.xml,struts.properties,web.xml都可以配置常量
struts2框架加载常量的顺序如下:
struts-default.xml 在struts-core.jar包中
struts-plugin.xml 在struts-Xxx 在struts插件的jar中
struts.xml
struts.properties
web.xml
4.action类文件
action是业务逻辑处理对象,框架自动调用action类 的方法来实现相应的业务处理
ActionSupport类实现了action接口,它是一个默认的action实现类,它提供
了很多默认方法,如数据校验,获取国际化信息.
因为action继承了ActionSupport类,而ActionSupport类实现了Serializable接口,实现该接口必须声明serialVersionUID
private static final long serialVersionUID=1L;
如何访问servletAPI,Struts2框架提供了以下的三种方式
1.通过ActionContext类访问
1.通过ActionContext类访问servletAPIvoid put(String key,Object value): 将key-value存入到actionContext中object get(Object key):通过参数key来查找当前actionContext中的值map getApplication():返回一个application的Map对象Static ActionContext getContext():获取当前线程的ActionContext对象Map getParameters():返回一个包含所有的HttpServletRequest参数信息的map对象Map getSession():返回一个Map类型的HttpSession对象void put(Object key,Object value):向当前对象ActionContext对象中存入键值对信息void setApplication(Map application):设置Application上下文void setSession(Map session):设置Map类型的session的值
2.通过特定接口访问
ActionContext类,可以访问servletAPI,但是无法访问其实例ServletRequestAware:实现该接口后,可以直接访问HttpServletRequest实例ServletResponseAware:实现该接口后,可以直接访问HttpServletResponse实例ServletContextAware:实现该接口后,可以直接访问ServletContext实例public class LoginAction implements Action,ServletContextAware{ private ServletContext context; public void setServletContext(ServletContext ctx){ context=ctx; } public Strng execute() throws Exception{ context.setAttribute("user","jim"); return SUCCESS; }}
3.通过ServletActionContext访问
org.apache.struts2.ServletActionContext1.ServletActionContext.getResponse() 获得HttpServletResponse对象2.ServletActionContext.getRequest()获得HttpServletRequest对象3.ServletAction.getServletContext()获得ServletContext对象
ModelDriven接口
大量数据提交时,一一获取很不方便
实现ModelDriven接口,将用户提交的信息赋值给model
public class XxxAction extends ActionSupport implements ModelDrivern<XXModel>{ private static final long serivalVersionUID=1L; private xxModel x=new XXModel();//创建要使用的对象实例 public XXModel getModel(){ return x; } public String execute() throws Exception{ return SUCCESS; }}//XxxAction类实现了ModelDriven接口,这样用户提交的关于XXModel类的信息,就会直接存入x对象中
异常处理机制
1.配置异常处理
2.检测是否符合要求
3.输出异常信息
配置异常处理,全局异常和局部异常<struts> <package name="default"> <!--全局结果--> <global-results> <result name="Exception">/Exception.jsp</result> <result name="SQLException">/SQLException.jsp</result> </global-results> <!--全局异常映射--> <global-results-mappings> <exception-mapping exception="java.sql.SQLException" result="SQLException"> <exception-mapping exception="java.lang.Exception" result="Exception"> </global-results-mapping> </package></struts>
//编写异常检测代码public String execute() throws Exception{ if(!getName().equals("tom")) { //自定义异常类 throw new SecurityException("wrong name!!!!!!"); } else if(!getAge().equals("20")) { throw new Exception("wrong age!!!!!"); } else if(!getTel().equals("15202208200")) { throw new java.sql.SQLException(); } else { return SUCCESS; } }
输出异常信息<s:property value="excpetion.message"/>:输出异常对象信息<s:property value="exceptionStack"/>:输出异常堆栈信息
第三部分 Struts2数据校验与国际化
1.类型转换
2.数据校验
3.系统化
1.类型转换
基本类型转换
一.list使用泛型
private List<Users> users;public String execute() throws Exception { for (User user : users) { System.out.println("Name:"+user.getName()+" Age:"+user.getAge()+" Tel:"+user.getTel()); } return SUCCESS;
2.list使用局部类型转换文件
private List users;//重载execute方法 public String execute() throws Exception { return SUCCESS; }//properties文件书写规则//Element_listName=ElementTypeElement_users=com.model.User
//输入用户输入的信息Name: <s:property value="users[0].name"/>Age:<s:property value="users[0].age"/>Tel:<s:property value="users[0].tel"/>
二.Map使用泛型
private Map<String, User> users;//重载execute方法 public String execute() throws Exception { return SUCCESS; }
2.Map使用局部类型转换文件
private Map users;public void setUsers(Map users) { this.users = users; }//properties文件书写规则//Element_MapName=ValueType//Key_MapName=KeyTypeElement_users=com.model.UserKey_users=java.lang.String
//输出用户输入的信息Name:<s:property value="users['first'].name"/>Age:<s:property value="users['first'].age"/>Tel:<s:property value="users['first'].tel"/>
自定义类型转换
先定义相应的类型转换器类,然后注册类型转换器
自定义转换器类的方式
方式1.继承DefaultTypeConvertor类来定义转换器类,
重写convertValue()方法
public class LineConvertor extends DefaultTypeConverter{ @Override public Object convertValue(Map<String, Object> context, Object value, Class toType) { //字符串转向Line类类型 if(toType==Line.class) { //请求参数为字符串数组 String[] params=(String[])value; String param=params[0]; //创建Line实例 Line line=new Line(); StringBuilder temp=new StringBuilder(); char ch; int j=0; //字符串正确形式为(x1,y1,x2,y2) for(int index=0;index<param.length();index++) { ch=param.charAt(index); if(ch!=','&&ch!='('&&ch!=')') { temp.append(ch); }else if(ch==','||ch==')') { switch (j) { case 0: { line.setX1(Integer.parseInt(temp.toString())); temp.delete(0,temp.length()); break; } case 1: { line.setY1(Integer.parseInt(temp.toString())); temp.delete(0,temp.length()); break; } case 2: { line.setX2(Integer.parseInt(temp.toString())); temp.delete(0,temp.length()); break; } case 3: { line.setY2(Integer.parseInt(temp.toString())); temp.delete(0,temp.length()); break; } default: break; } j++; } } //返回结果Line实例 return (Object)line; } //将对象转换为字符串 else if(toType==String.class) { //强制转换为Line类型 Line line=(Line)value; return (Object)("("+line.getX1()+","+line.getY1()+","+line.getX2()+","+line.getY2()+")"); } return null; }}
方式2.继承StrutsTypeConvertor类来定义转换器类
重写convertFormString()方法,convertToString()方法
public class LineConvertor extends StrutsTypeConverter{ //字符串转向指定类型 public Object convertFromString(Map contenxt, String[] values, Class totype) { //请求参数为字符串数组 String[] params=(String[])values; String param=params[0]; //创建Line实例 Line line=new Line(); StringBuilder temp=new StringBuilder(); char ch; int j=0; //字符串正确形式为(x1,y1,x2,y2) for(int index=0;index<param.length();index++) { ch=param.charAt(index); if(ch!=','&&ch!='('&&ch!=')') { temp.append(ch); }else if(ch==','||ch==')') { switch (j) { case 0: { line.setX1(Integer.parseInt(temp.toString())); temp.delete(0,temp.length()); break; } case 1: { line.setY1(Integer.parseInt(temp.toString())); temp.delete(0,temp.length()); break; } case 2: { line.setX2(Integer.parseInt(temp.toString())); temp.delete(0,temp.length()); break; } case 3: { line.setY2(Integer.parseInt(temp.toString())); temp.delete(0,temp.length()); break; } default: break; } j++; } } return (Object)line; } //将对象转换为字符串 public String convertToString(Map context, Object o) { //强制转换为Line类型 Line line=(Line)o; return "("+line.getX1()+","+line.getY1()+","+line.getX2()+","+line.getY2()+")"; }}
类型转换器注册
//line=com.convertor.LineConvertor
1.局部类型转换 针对某个action的属性起作用
#line是Action的属性,com.action.LineConvertor类型转换器的实现类line=com.convertor.LineConvertor
2.全局类型转换 对所有的action对应的类型的属性起作用
#com.model.Line是具体类 com.convertor.LineConvteror是类型转换器的实现类com.model.Line=com.convertor.LineConvertor
2.数据校验
数据校验分为2种方式
1.客户端校验:通过js代码来检验数据的正确性
2.服务端校验:检查http请求信息是否正确
服务端数据校验的方式如下:
1.通过action的validate()方法
2.使用XWork校验框架实现
方式一重写validate()方法:
ActinoSupport类实现了Validateable接口,但是validate()方法是空实现.
在请求action中重写validate()方法
validate()方法会现在execute()方法之前执行,进行数据数据校验.
当校验正确,才会执行execute()方法
当校验错误,将错误信息以jsp文件输出
实际当中一个action处理多个业务逻辑,validate()方法无法实施准确校验
Struts2框架使用了validateX()方法来进行校验
案例 如果age在10-30之间,校验正确,否则报错
//log方法,Action调用的method方法 public String log()throws Exception{ System.out.println("log"); return "hello"; }//校验方法 public void validate() { System.out.println("validate"); } //log method的校验方法 public void validateLog(){ System.out.println("validatelog"); //age值必须在10-30之间 if(age<10||age>30) { addFieldError("age", "age must be from 10 to 30!"); } }
方式二 使用XWork的validator框架校验
不需要写validate()方法和validateLogin()方法
<!--配置框架校验--><!DOCTYPE validators PUBLIC "-//OpenSymphony Group//XWork Validator 1.0.2//EN" "http://www.opensymphony.com/xwork/xwork-validator-1.0.2.dtd"><validators> <!-- age域 --> <field name="age"> <!--域类型为int--> <field-validator type="int"> <param name="min">10</param> <param name="max">40</param> <message>the age must be from 10 to 40!</message> </field-validator> </field> <!-- name域 --> <field name="name"> <!-- 域类型为requiredstring类型 --> <field-validator type="requiredstring"> <message>the age must be from 10 to 40!</message> </field-validator> </field></validators>
校验配置方式
1.字段校验方式:将filed元素作为基本的子元素,针对字段和属性
<!-- age域 --> <field name="age"> <!--域类型为int--> <field-validator type="int"> <param name="min">10</param> <param name="max">40</param> <message>the age must be from 10 to 40!</message> </field-validator> </field>
2.非字段校验方式:以validator为基本单位校验,一个validator元素指定一个校验规则.针对一类事务
<validators><!--校验整型int--> <validator type="int"> <!--校验的域名为age--> <param name="fieldName">age<param> <param name="min">10</param> <param name="max">40</param> <message>the age must be from 10 to 40!</message></validator></validators>
3.校验器
1.required校验器要求指定的字段值非空
字段校验方式
<field name="username"> <field-validator type="required"> <message>用户名不能为空</message> </field-validator> </field>
非字段校验方式
<validator type="required"> <param name="fieldName">username</param> <message>用户名不能为空</message> </validator>
2.requiredstring要求指定的字段值非空且长度大于0
字段校验方式
<field name="username"> <field-validator type="requiredstring"> <param name="trim">true</param> <message>用户名不能为空</message> </field-validator> </field>
非字段校验方式
<validator type="requiredstring"> <param name="fieldName">username</param> <param name="trim">true</param> <message>用户名不能为空</message> </validator>
3.int校验器 要求指定字段的整数值在指定范围内,同理long,short,double
字段校验方式
<field name="age"> <field-validator type="int"> <param name="min">10</param> <param name="max">100</param> <message>年龄必须在在${min}到${max}之间</message> </field-validator> </field>
非字段校验方式
<validator type="int"> <param name="fieldName">age</param> <param name="min">10</param> <param name="max">100</param> <message>年龄必须在在${min}到${max}之间</message> </validator>
4.date校验器 要求日期在指定范围内
字段校验方式
<field name="birthday"> <field-validator type="date"> <param name="min">1990-01-01</param> <param name="max">2010-07-28</param> <message key="error.birthday"></message> </field-validator> </field>
非字段校验方式
<validator type="date"> <param name="fieldName">birthday</param> <param name="min">1990-01-02</param> <param name="max">2010-07-28</param> <message>生日数据错误</message> </validator>
5.email校验器 校验邮件地址是否合法.同理URL
字段校验方式
<field name="MyEmail"> <field-validator type="email"> <message>非法的邮件地址</message> </field-validator> </field>
非字段校验方式
<validator type="email"> <param name="fieldName">MyEmail</param> <message>非法的邮件地址</message> </validator>
6.stringlength校验器 校验字段的长度必须在指定范围内
字段校验方式
<field name="username"> <field-validator type="stringlength"> <param name="minLength">4</param> <param name="maxLength">10</param> <param name="trim">true</param> <message key="error.length.username"></message> </field-validator> </field>
非字段校验方式
<validator type="stringlength"> <param name="fieldName">username</param> <param name="minLength">4</param> <param name="maxLength">10</param> <message>用户名长度在${minLength}到${maxLength}之间</message> </validator>
国际化
通过加载国际化资源文件的方式来实现国际化
国际化字段文件的分类
1.包范围资源文件
只允许src包下的action访问的资源文件
package_language_country.properties
2.类范围资源文件
只能被指定类所对应的action访问的字段文件
ActionName_language_country.properties
3.全局范围内的资源文件
可以被所有的action和jsp访问
BaseName_language_country.properties
全局范围内的字段文件不是自动加载 的,需要在struts.custom.il8n.resources中配置baseName
举例globalMessage_en_US.properties
可以在struts.xml中指定<constant name="struts.il8n.resources" value="globalMessage">也可以在struts.properties中指定struts.custom.il8n.resources=globalMessage
4.临时资源文件
临时资源文件对应一个jsp页面,通过标签来引用
mess_zh_CN.properties
访问国际化字段文件的方式
1.通过actionSupport类的getText()方法
通过name得到key,通过key得到value
2.jsp页面中使用
- struts框架知识点总结<一>
- Struts框架知识点总结<二>
- 集合框架知识点总结(一)
- Struts学习总结(一)---搭建Struts框架
- struts框架基础知识点
- Struts知识点总结
- struts 知识点总结
- Struts知识点总结
- struts一些知识点总结
- Struts 2知识点总结
- Struts知识点概况(一)
- 黑马程序员 知识点总结-Java集合框架(一)
- Spring框架知识点总结
- Hibernate框架知识点总结
- Struts框架(一)
- Struts框架学习一
- Struts框架<一>
- Struts 2框架总结
- subeclipse 与SVN的对应版本,及插件下载URL
- C++基础学习之12 - 测试驱动开发
- pip install lxml scrapy pywin32等报错问题解决
- 指数序列
- 编写一个程序,将a.txt文件中的单词与b.txt文件中的单词交替合并到c.txt文件中,a.txt文件中的单词用回车符分隔,b.txt文件中用回车或空格进行分隔
- struts框架知识点总结<一>
- 2016书单总结--重构改善既有代码的设计--重新组织函数
- 在开发板上使用tftp命令下载服务器上的文件
- The content of the adapter has changed but ListView did not receive a notification
- 第29课 Python中for循环体与文件(迭代器解析)
- ROS新功能包PlotJuggler绘图
- .h .lib .dll文件作用和区别
- git——介绍与安装
- 编写一个程序,将djava目录下的所有.java文件复制到djad目录下,并将原来文件的扩展名从.java改为.jad