Struts2框架配置和基本用法

struts2框架
1、配置web.xml
<filter>
<filter-name>Struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>Struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
============================================================================================================================================
2、配置struts.xml
<struts>
<package name="aa" namespace="/demo" extends="struts-default">
<action name="msgIn" class="org.great.servlet.RegisterMsg" method="msgInIt">
<result name="success">
/jsp/showMsg.jsp
</result>
</action>
</package>
</struts>
============================================================================================================================================
3、使用struts标签
导包:<%@ taglib uri="/struts-tags" prefix="s" %>
//通过ActionContext类的静态方法getContext().getSession();取得Session对象;
//<s:property value="#session.stu_msg"/> 即可拿到
Map<String, Object> session = ActionContext.getContext().getSession();
session.put("stu_msg", stu);
//普通存session的方法
HttpServletRequest request = ServletActionContext.getRequest();
request.getSession().setAttribute("stu_msg", stu);
============================================================================================================================================
4、前台取得session中值并遍历的方法
<p><%=request.getSession().getAttribute("stu_msg") %></p>//将值存在普通session中的取值方法
<p><s:property value="#session.stu_msg"/></p>//通过静态类ActionContext存session的取值方法
*********推荐方法:实现接口SessionAware ***************************
Map<String, Object> session;
@Override
public void setSession(Map<String, Object> arg0) {
this.session = arg0;
}//然后就可以直接用session.put(key, value)
<table>
<s:iterator value="#session.stu_msg" status="index">//迭代
//property标签用于输出指定的值,可以去得到session等中的值<s:property value="#session.stu_id " />
<s:property value="stu_id " />
<s:property value="stu_account " />
<s:property value="stu_pwd " />
<s:property value="stu_name " />
<s:property value="stu_card " />
<s:property value="stu_sex " />
<s:property value="stu_tel " />
<s:property value="stu_qq " />
<s:property value="createTime " />
<s:property value="stu_status " />
<s:property value="class_id " />
</s:iterator>
</table>
//property标签获得bean中的值
<s:property value="bean.stu_id " />
遍历Map:
<s:iterator value="#session.map" var="i">
<s:property value="#i.key " />
<s:property value="#i.value " />
</s:iterator><br>
*****<s:property value="#userName " />这样可以直接拿到action中userName属性的值(userName必须有set\get方法)
*****<s:if text=""></s:if>标签中text允许使用bean.属性,例如:text="#session.bean.stu_id"
============================================================================================================================================
5、使用result中的stream(用于向页面输出二进制数据):
语法:<result name=”success” type=”stream”>
<param name=”inputName”>codeStream</param>
</result>
codeStream指的是Action中某属性名,该属性需为InputStream类型
inputName是固定写法
============================================================================================================================================
6、使用struts加ajax实现错误信息提示:
导包:commons-lang3-3.1.jar struts2-json-plugin-2.3.8.jar(包版本要一致)
Struts.xml配置:
<package name="login" namespace="/stuLogin" extends="json-default">//extends必须继承json-default
<action name="login" class="org.great.servlet.StuLogin" method="stuLog">
<result name="success" type="json">//type类型为json
<param name="root">result</param>//root为固定属性;result是action种的某属性,即要返回的属性值;
</result>
</action>
</package>
============================================================================================================================================
7、重定向(应用场景:登录失败重定向到注册页面):
<result name="false" type="redirectAction">//type为redirectAction
<param name="actionName">msgIn</param>//要重定向到的actionName
<param name="namespace">/demo</param>//要重定向到的namespace
<param name="method">msgInIt</param>//要重定向到的method
</result>
============================================================================================================================================
8、OGNL标签:
1)<s:form action="counter" method="get" namespace="/demo">//action和namespace必须分开
<s:textfield label="数字" name="numTwo"></s:textfield>//label是在文本框旁要显示的信息
<s:submit value="加" name="method"></s:submit>//提交表单
</s:form>
--------------------------------------------------------------------------------------------------------------------------------------------
2)****访问ActionContext资源:
a.获取值栈中的对象:${user.name};
b.获取application中的对象:#application.name或#application.['name'] 相当于 application.getAttribute("name")方法;
c.获取request中的对象:#request.name或#request.['name'] 相当于 request.getAttribute("name")方法;
d.获取session中的对象:#session.name或#session.['name'] 相当于 session.getAttribute("name")方法;
e.获取parameters中的值:#parameters.name或#parameters.['name'] 相当于 request.getParameter("name")方法;
f.获取attr中的值:#attr.name或#attr.['name'] 会按照page、request、session、application的顺序进行搜索;
--------------------------------------------------------------------------------------------------------------------------------------------
3)****用#过滤筛选集合:
List<book> book = new ArrayList<book>();
<s:iterator value="book.{?#this.price>50}"></s:iterator>//筛选价格大于50的数据;
<s:property value="book.{?#this.title=='java'"/>//筛选标题是java的数据
***选择操作符:?获取满足指定条件的所有元素;^获取满足条件的第一个元素;$获取满足条件的最后一个元素;
--------------------------------------------------------------------------------------------------------------------------------------------
4)用#构造Map并配合set标签进行参数设定:
<s:set name="user" value="#{'stu_name':'peter','stu_sex':'man'}"/>
--------------------------------------------------------------------------------------------------------------------------------------------
5)获取源文件(xx.properties)中的数据,搭配<s:text>标签使用:
源文件中使用OGNL语言:value=${userName}
JSP中:<s:text name="value"></s:text>
--------------------------------------------------------------------------------------------------------------------------------------------
6)多集合连接:
<s:append id="all">
<s:param value="集合1"/>
<s:param value="集合2"/>
</s:append>
<s:iterator value="#all">
<s:property/>
</s:iterator>
筛选集合:<s:iterator value="#all" begin="" end=""></s:iterator>
<s:subset source="{'PHP','JAVA','C','C++'}" start="1" count="3"></s:subset>筛选第二到第四个元素
--------------------------------------------------------------------------------------------------------------------------------------------
7)字符串分割:
<s:generator val="1,2,3" separator=","></s:generator>根据逗号分割
--------------------------------------------------------------------------------------------------------------------------------------------
8)引入action页面:
<s:action></s:action>
属性:name:引用的action 名称;executeResult:设定是否包含action的结果页;namespace:action的命名空间
--------------------------------------------------------------------------------------------------------------------------------------------
9)页面日期的输出:
<s:date/>
属性:name:指定要格式化的日期;format:指定日期格式化的样式;nice:输出当前时间与给定时间的时间差,默认false
--------------------------------------------------------------------------------------------------------------------------------------------
10)本地文件浏览:
<s:file name="file" label="浏览"></s:file>
--------------------------------------------------------------------------------------------------------------------------------------------
11)单选按钮:
<s:radio name="sex" label="性别" list="#{0:'男',1:'女'}"/>
下拉列表:
<s:select name="city" list="#request.city" labe="选择"></s:select>
自动完成功能的下拉列表框:
<sx:autocompleter name="city" list="#request.city" labe="选择"></sx:autocompleter>
复选框:
<s:checkboxlist name="like" list="#session.like"></s:checkboxlist>
可填写的复合框:
<s:combobox name="" list="" label=""></s:combobox>
联动选择框:
<s:doubleselect name="" list"{'河南','福建'}" doubleName="city" doubleList="top=='河南'?{城市}:{城市}" label="选择省市"/>
--------------------------------------------------------------------------------------------------------------------------------------------
12)日期选择:
<sx:datetimepicker name="" displayFormat="yyy/MM/dd" label="选择日期"/>
--------------------------------------------------------------------------------------------------------------------------------------------
============================================================================================================================================
9、数据校验:(Action类需要继承ActionSupport validate()方法为所有的方法进行校验 校验特定方法validateXxx())
JSP页面增加信息显示标签:<s:fielderror key="error"></s:fielderror>//key是键
Action中主要方法:
public String getin(){//原本中action中的方法,不受影响!
return "success";
}

public void validateGetin(){//首先校验此方法,符合条件才会进入上面的方法,否则直接input
if(numOne.equals("1")){
this.addFieldError("error", "测试成功!");
}
struts.xml配置:
<result name="success">//成功进入相关页面
/result.jsp
</result>
<result name="input">//出错直接返回当前页面,并且错误信息会显示在当前页面标签下
/index.jsp
</result>
============================================================================================================================================
10、拦截器:
strut.xml配置:
<package name="loginPackage" extends="struts-default,pagePackage">//拦截器的包采用多继承,实现拦截的包pagePackage
<interceptors>
<interceptor name="loginInterceptor" class="org.great.servlet.LoginInterceptorAction"/>
<interceptor-stack name="baseStack">
<interceptor-ref name="loginInterceptor"/>//以上标签的name
<interceptor-ref name="defaultStack"/>//默认必须加,否则会失效
</interceptor-stack>
</interceptors>
<default-interceptor-ref name="baseStack"></default-interceptor-ref>
<global-results>//拦截后要执行的方法,跳转到登录界面等
<result name="login">/jsp/showMsg.jsp</result>
</global-results>
</package>
//以下是要实行拦截的包
<package name="up" namespace="/update" extends="loginPackage">//直接继承拦截器包名
</package>
Action类继承AbstractInterceptor:
@Override
public String intercept(ActionInvocation invocation) throws Exception {
ArrayList<StudentBean> user = (ArrayList<StudentBean>) invocation.getInvocationContext().getSession().get("stu_msg");
if(null == user){
return "login";
}else{
return invocation.invoke();
}
}
============================================================================================================================================
11、struts.xml通配符的使用:
//*为通配符,匹配所有也可以根据几个写*_*_* action中的name是路径上的单词
<form action="<%=basePath%>demo/msgIn_to_login" method="post">
//路径上的单词可能来自表单上的action
//{1}对应着就是*号的单词
<package name="aa" namespace="/demo" extends="struts-default">
<action name="*_*_*" class="org.great.servlet.{1}" method="{2}">
<result name="success">
/jsp/{3}.jsp
</result>
</action>
</package>
============================================================================================================================================
12、文件上传:(导包commons-io-1.3.2.jar)
JSP页面:
<form action="upLoad/up" enctype="multipart/form-data" method="post">
<input type="file" id="file" name="file"><!-- name的值必须对应着action中fileFileName和File file -->
<input type="submit" value="上传">
</form>
Action类:(多文件上传所有属性全部使用数组)
private File file;//并不是上传的文件本身,而是存放的临时文件,和表单中的input file中的name属性的值对应
private String fileFileName;//和表单中的input file中的name属性的值对应,name属性的值必须放在FileName前!!!
private String fileContentType;//提交过来的类型
.....此处省去set\get方法
public String Up(){
File file_to = new File(ServletActionContext.getServletContext().getRealPath("up"), fileFileName);
InputStream in = null;
OutputStream out = null;
file_to .getParentFile().mkdirs();//创建文件夹
try {
in = new FileInputStream(file);//获得输入流
out = new FileOutputStream(file_to );//输出流要写到的位置
byte [] byt = new byte[1024];
int end = 0;
while((end = in.read(byt)) != -1){
out.write(byt, 0, end);
}
out.close();
in.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "success";
}
============================================================================================================================================
13、文件下载:(无法使用A标签的情况下,可使用隐藏form表单的提交方式)
JSP页面:<a href="downLoad/load">文件下载</a>//具体项目中应该指定下载文件
Action类:
private InputStream inputStream;
private String fileName;
private String contentType;
.....此处省略set\get...
public String load(){
File file = new File("D:/Test/ExamPaper.xls");
fileName = file.getName();
try {
inputStream = new FileInputStream(file);//获得此文件的输入流

} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "success";
}
strts.xml配置:
<package name="down" namespace="/downLoad" extends="struts-default">
<action name="load" class="org.great.servlet.LoadAction" method="load">
<result name="success" type="stream">//type必须为stream
<param name="contentType">${contentType}</param>//必须制定下载文件类型
<param name="inputName">inputStream</param>//inputStream是action中的属性
<param name="contentDisposition">attachment;filename="${fileName}"</param>//文件名;attachment让浏览器保存
<param name="bufferSize">2048</param>//缓冲区大小
</result>
</action>
</package>
============================================================================================================================================
14、重复提交表单的处理办法:
JSP页面:在form标签中增加<s:token></s:token>标签
strts.xml配置:(以下以登录为例)
<!-- 登录 -->
<action name="login" class="org.great.action.LoginAction" method="login">
<interceptor-ref name="token"></interceptor-ref>
<interceptor-ref name="defaultStack"></interceptor-ref>//上面这两个拦截器一定要写才能起作用
<result name="success" type="redirectAction">index</result>
<result name="invalid.token">/web/textAgain.jsp</result>//若重复提交,会跳转到此页面,result的名字是invalid.token
<result name="error">/web/login.jsp</result>
</action>
============================================================================================================================================

posted on 2017-07-09 09:40  猴子敲代码  阅读(324)  评论(0编辑  收藏  举报