Struts2示例
来源:互联网 发布:阿里云 教程 编辑:程序博客网 时间:2024/06/08 16:35
struts2配合jquery 的ajax实现数据交互及异步加载
1.action中需要返回一个二进制的inputstream流
//判断用户名、密码,生成对应的响应 inputStream = user.equals("crazyit.org") && pass.equals("leegang") ? new ByteArrayInputStream("恭喜你,登录成功!" .getBytes("UTF-8")) : new ByteArrayInputStream("对不起,用户名、密码不匹配!" .getBytes("UTF-8"));
2.struts.xml中指定返回文件的参数
<result name="success" type="stream"> <!-- 指定下载文件的文件类型 --> <param name="contentType">text/html</param> <!-- 指定由getResult()方法返回输出结果的InputStream --> <param name="inputName">result</param> </result>
3.jsp中配合jquery的ajax实现数据交互,主要使用$.get()获取数据
//为id为loginBn的按钮绑定事件处理函数 $("#loginBn").click(function() { //指定向loginPro发送请求,以id为loginForm表单里各表单控件作为请求参数 $.get("loginPro" , $("#loginForm").serializeArray() , //指定回调函数 function(data , statusText) { $("#show").height(80) .width(300) .css("border" , "1px solid black") .css("background-color" , "#efef99") .css("color" , "#ff0000") .css("padding" , "20px") .empty(); $("#show").append("登录结果:" + data + "<br />"); $("#show").show(2000); }, //指定服务器响应为html "html"); });
struts2实现下载中文及用struts.xml控制授权下载
1.直接下载出现中文乱码,使用DownloadAction中的getTargetFile()从struts.xml中获取inputPath初始值,并返回一个InputStream,交由struts.xml控制下载
<action name="download" class="org.crazyit.app.action.FileDownloadAction"> <!-- 指定被下载资源的位置 --> <param name="inputPath">\images\疯狂联盟.jpg</param> <!-- 配置结果类型为stream的结果 --> <result name="success" type="stream"> <!-- 指定下载文件的文件类型 --> <param name="contentType">image/jpg</param> <!-- 指定由getTargetFile()方法返回被下载文件的InputStream --> <param name="inputName">targetFile</param> <param name="contentDisposition">filename="wjc_logo.jpg"</param> <!-- 指定下载文件的缓冲大小 --> <param name="bufferSize">4096</param> </result> </action>
2.授权下载在AuthorityDownloadAction中判断sessoin的用户名是否正确,正确返回success,然后交由struts.xml控制下载。
<action name="download2" class="org.crazyit.app.action.AuthorityDownAction"> <!-- 定义被下载文件的物理资源 --> <param name="inputPath">\images\wjc_logo.zip</param> <result name="success" type="stream"> <!-- 指定下载文件的文件类型 --> <param name="contentType">application/zip</param> <!-- 指定由getTargetFile()方法返回被下载文件的InputStream --> <param name="inputName">targetFile</param> <param name="contentDisposition">filename="wjc_logo.zip"</param> <!-- 指定下载文件的缓冲大小 --> <param name="bufferSize">4096</param> </result> <!-- 定义一个名为login的结果 --> <result name="login">/WEB-INF/content/login.jsp</result> </action>
struts 的异常处理无需使用try catch块。直接抛出异常给struts框架,交给struts.xml来处理
<!-- 定义全局异常映射 --> <global-exception-mappings> <!-- 当Action中遇到SQLException异常时, 系统将转入name为sql的结果中--> <exception-mapping exception="java.sql.SQLException" result="sql"/> <!-- 当Action中遇到Exception异常时, 系统将转入name为root的结果中--> <exception-mapping exception="java.lang.Exception" result="root"/> </global-exception-mappings> <action name="login" class="org.crazyit.app.action.LoginAction"> <!-- 定义局部异常映射, 当Action中遇到MyException异常时, 系统将转入name为my的结果中--> <exception-mapping exception="org.crazyit.app.exception.MyException" result="my"/> <!-- 定义三个结果映射 --> <result name="my">/exception.jsp</result> <result name="error">/error.jsp</result> <result name="success">/welcome.jsp</result> </action> //jsp中则通过<s:property value="exceptionStack"/>来获取异常值
struts2拦截器在action类的excute方法执行前调用。当返回invocatioin.incoke()时进入下一个拦截器,下面没有拦截器时直接执行excute方法。
1.struts.xml的包中定义拦截器
<package name="lee" extends="struts-default"> <!-- 用户拦截器定义在该元素下 --> <interceptors> <!-- 定义了一个名为authority的拦截器 --> <interceptor name="authority" class="org.crazyit.app.interceptor.AuthorityInterceptor"/> </interceptors>
2.在struts.xml的action中使用该拦截器
<action name="viewBook"> <!-- 返回success视图名时, 转入/WEB-INF/content/viewBook.jsp页面 --> <result>/WEB-INF/content/viewBook.jsp</result> <interceptor-ref name="defaultStack"/> <!-- 应用自定义拦截器 --> <interceptor-ref name="authority"/> </action>
struts2通过ajax异步传递json数据
1.action中封装请求参数的属性,并set和get来序列化每个参数。
private Map<String , String> map = new HashMap<String , String>(); private String customName = "顾客"; //封装请求参数的三个属性 private String field1; //'transient'修饰的属性不会被序列化 private transient String field2; //没有setter和getter方法的字段不会被序列化 private String field3;
2.struts.xml中指定返回类型
<action name="JSONExample" class="org.crazyit.app.action.JSONExample"> <!-- 配置类型的json的Result --> <result type="json"> <!-- 为该Result指定参数 --> <param name="noCache">true</param> <param name="contentType">text/html</param> <!-- 设置只序列Action的map属性 --> <!-- param name="root">map</param --> </result> </action>
3.jsp中使用jquery的ajax来获取返回参数,并解析json数组
function gotClick() { //请求的地址 var url = 'JSONExample.action'; //将favorite表单域的值转换为请求参数 var params = Form.serialize('form1'); //创建Ajax.Request对象,对应于发送请求 var myAjax = new Ajax.Request( url, { //请求方式:POST method:'post', //请求参数 parameters:params, //指定回调函数 onComplete: processResponse, //是否异步发送请求 asynchronous:true }); } function processResponse(request) { //使用JSON对象将服务器响应解析成JSON对象 var res = request.responseText.evalJSON(); alert(res); //遍历JSON对象的每个属性 for(var propName in res) { $("show").innerHTML += propName + " --> " + res[propName] + "<br/>"; } }
1.定义action的不同方法
//为每个action写一个method <action name="regist" class="org.crazyit.app.action.LoginRegistAction" method="regist"> <!-- 定义逻辑视图和物理视图之间的映射关系 --> <result name="input">/login.jsp</result> <result name="error">/error.jsp</result> <result name="success">/welcome.jsp</result> </action> //或使用通配符匹配,避免同一个类,相同的返回类型写多个方法(但此时form表单的action名称需要一致) <action name="*Action" class="org.crazyit.app.action.LoginRegistAction" method="{1}"> <!-- 定义逻辑视图和物理视图之间的映射关系 --> <result name="input">/login.jsp</result> <result name="error">/error.jsp</result> <result name="success">/welcome.jsp</result> </action>
2.在Action转入实际的物理视图前通过ActionInvocation的addResultListener方法完成回调。
//在action的excute方法中添加监听addPreResultListener ActionInvocation invocation = ActionContext .getContext().getActionInvocation(); invocation.addPreResultListener(new PreResultListener() { public void beforeResult(ActionInvocation invocation, String resultCode) { System.out.println("返回的逻辑视图名字为:" + resultCode); //在返回Result之前加入一个额外的数据。 invocation.getInvocationContext().put("extra" , new java.util.Date() + "由" + resultCode + "逻辑视图名转入"); //也可加入日志等 } }); //物理视图的jsp中使用struts的方法获取回调的属性标签 <s:property value="extra"/>
Struts2上传文件及用filter实现文件过滤
1.上传的jsp中需指定form格式为enctype=”multipart/form-data
2.UploadAction中封装多个上传的文件属性并重写excute方法
@Override public String execute() throws Exception { //以服务器的文件保存地址和原文件名建立上传文件输出流 FileOutputStream fos = new FileOutputStream(getSavePath() + "\\" + getUploadFileName()); FileInputStream fis = new FileInputStream(getUpload()); byte[] buffer = new byte[1024]; int len = 0; while ((len = fis.read(buffer)) > 0) { fos.write(buffer , 0 , len); } fos.close(); return SUCCESS; }
3.struts中对文件过滤
<interceptor-ref name="fileUpload"> <!-- 配置允许上传的文件类型 --> <param name="allowedTypes">image/png ,image/gif,image/jpeg</param> <!-- 配置允许上传的文件大小 --> <param name="maximumSize">2000000</param> </interceptor-ref>
struts2输入校验
*Action同目录下 *Action-validata.xml
<validators> <!-- 校验Action的name属性 --> <field name="name"> <!-- 指定name属性必须满足必填规则 --> <field-validator type="requiredstring"> <param name="trim">true</param> <message>必须输入名字</message> </field-validator> <!-- 指定name属性必须匹配正则表达式 --> <field-validator type="regex"> <param name="expression"><![CDATA[(\w{4,25})]]></param> <message>您输入的用户名只能是字母和数字 ,且长度必须在4到25之间</message> </field-validator> </field> <!-- 校验Action的pass属性 --> <field name="pass"> <!-- 指定pass属性必须满足必填规则 --> <field-validator type="requiredstring"> <param name="trim">true</param> <message>必须输入密码</message> </field-validator> <!-- 指定pass属性必须满足匹配指定的正则表达式 --> <field-validator type="regex"> <param name="expression"><![CDATA[(\w{4,25})]]></param> <message>您输入的密码只能是字母和数字 ,且长度必须在4到25之间</message> </field-validator> </field> <!-- 指定age属性必须在指定范围内--> <field name="age"> <field-validator type="int"> <param name="min">1</param> <param name="max">150</param> <message>年纪必须在1到150之间</message> </field-validator> </field> <!-- 指定birth属性必须在指定范围内--> <field name="birth"> <field-validator type="date"> <!-- 下面指定日期字符串时,必须使用本Locale的日期格式 --> <param name="min">1900-01-01</param> <param name="max">2050-02-21</param> <message>生日必须在${min}到${max}之间</message> </field-validator> </field></validators>
阅读全文
0 0
- Struts2示例
- Struts2示例
- Struts2+JS,Struts2+jQuery示例
- Struts2上传文件示例
- Struts2.0配置示例
- struts2 UI标签示例
- struts2 doubleselect高级示例
- struts2 doubleselect示例
- 第一个struts2示例
- struts2 UI标签示例
- struts2上传文件示例
- struts2下载文件示例
- struts2 第一个示例
- struts2 doubleselect示例
- struts2配置文件示例
- Struts2上传文件示例
- Struts2 登录示例
- Struts2的简单示例
- scala学习笔记-继承
- Struts2学习(十二)【标签】
- lua笔记:初试更换图片
- React Native 封装自定义的Button
- 初识Hive,Zookeeper
- Struts2示例
- spring cloud FeignClient fallback 断路器
- GSM模块_GPRS数据传输机制和原理
- cocos2d相关网站mark
- 利用Tensorflow的Slim API实现卷积神经网络
- BZOJ2789 逆序对
- 洛谷P2312 解方程(NOIp2014)
- 指针和引用的区别
- 微信扫码登录java代码