Struts2 和 Ajax 交互
struts2 的项目的建立我就不多说了,网上很多。这里就说下 struts.xml 里面关于 result 的配置含义,因为 struts2 会通过这个配置来判断你想要做什么样的操作,是重定向、返回数据还是其他什么的,默认配置的结果类型是dispatcher。具体的 result-type 可以 在struts2-core-2.0.11.1.jar 包或 struts2 源代码中的 struts-default.xml 文件中找到,在这个文件中找到标签,所有的result-type都在里面定义了。
?
result-type
class
说明
dispatcher
org.apache.struts2.dispatcher.
ServletDispatcherResult
默认结果类型,用来转向页面,通常处理JSP
chain
com.opensymphony.xwork2.
ActionChainResult
将action和另外一个action链接起来
freemarker
org.apache.struts2.views.freemarker.
FreemarkerResult
处理FreeMarker模板
httpheader
org.apache.struts2.dispatcher.
HttpHeaderResult
用来控制特殊的Http行为
redirect
org.apache.struts2.dispatcher.
ServletRedirectResult
重定向到一个URL
redirectAction
org.apache.struts2.dispatcher.
ServletActionRedirectResult
重定向到一个Action
stream
org.apache.struts2.dispatcher.
StreamResult
向浏览器发送InputSream对象,通常用来处理文件下载或者返回数据给 Ajax 调用
velocity
org.apache.struts2.dispatcher.
VelocityResult
处理Velocity模板
xslt
org.apache.struts2.views.xslt.
XSLTResult
处理XML/XLST模板,
该XML可以通过XSL模板进行转换
plaintext
org.apache.struts2.dispatcher.
PlainTextResult
显示原始文件内容,例如文件源代码?
?
ajax 调用 action 没什么说的,跟以前 struts1 差不多,直接调用 .action ,直接将参数 post 传递过去,在 action execute 方法或者动态方法中获取参数就可以了;
action 回传数据给 ajax 的时候用到了上面 result-type 里面的 stream 参数配置,将 InputStream 对象返回给浏览器,在ajax 中通过?responseText 来获取返回的值。
有个问题需要说明一下,尽管工程和 jsp 编码都设置成 utf-8,在使用 stream 进行传递的时候仍然会出现乱码问题,这个时候过滤器也是帮不上忙的,需要在生成 InputStream 对象之前的字符串重新编码,否则中文传递到前台就会出乱码。
下面来看看代码:
ajax.jsp
?
?
?
ajax.js
?
??
AjaxAction.java
?
??
struts.xml
?web.xml
?上面配了一个自定义的过滤器,主要处理页面提交的中文编码问题的,本例中可以不用,struts2 当中也是有自带的中文过滤器的,这个自定义的过滤器也顺便贴出来了
SetCharacterEncodingFilter.java