标签:ref 编写 javaee write rri 方式 pre and dtd
第一步:导入相关jar包,本样例需导入struts相关jar包,json-lib.jar,gson-2.1.jar可以任意选择,但是这里需要都导入,因为为了做测试,两种jar包的转换方式都用到了。
第二步:配置web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" 
 xmlns="http://java.sun.com/xml/ns/javaee" 
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
 http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
 <display-name></display-name> 
 <!-- 声明Struts2的前端控制器 -->
 <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>
 
 <!-- 声明Spring的ContextListener,负责上下文一加载立即创建BeanFactory -->
 <context-param> <!-- 若applicationContext.xml没有放在WEB-INF下或者不叫这个名字,必需声明此参数 -->
 <param-name>contextConfigLocation</param-name>
 <param-value>classpath:applicationContext.xml</param-value> 
 </context-param>
</web-app>
第三步:新建struts.xml,默认admin/下跳转到/WEB-INF/index.jsp
<?xml version="1.0" encoding="UTF-8" ?>
<!-- <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> -->
<!DOCTYPE struts PUBLIC
 "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
 "http://www.yxccc.com/news/">
<struts>
 <package name="bg" namespace="/" extends="struts-default">
 <default-action-ref name="index"/>
 <!-- =================基础跳转====================== -->
 <action name="index">
 <result>/WEB-INF/index.jsp</result>
 </action>
 </package>
</struts>
第四步:编写AjaxRequestAction.java文件,这里做了两种请求,一种是直接请求到字符串,另一种是请求到一组数组格式的数据,但该数据必须要转换成JSON支持的数组,具体如下
package com.fengqi.action;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONArray;
import org.apache.struts2.ServletActionContext;
import com.google.gson.Gson;
import com.opensymphony.xwork2.ActionSupport;
/**
 * 创建时间:2014-10-24,ajax请求的action样例
 */
public class AjaxRequestAction extends ActionSupport{
 private String sex;
 @Override
 public String execute() throws Exception {
 return super.execute();
 }
 
 /**
 * ajax请求,以json格式的字符串响应请求
 */
 public void ajaxString(){
 System.out.println(sex);
 //获取相应Response
 HttpServletResponse response = ServletActionContext.getResponse(); 
 //设置编码方式
 response.setCharacterEncoding("UTF-8"); 
 try {
 if(sex.equals("nan")){
 response.getWriter().write("我是男的");
 }else if(sex.equals("nv")){
 response.getWriter().write("我是女的");
 }else{
 response.getWriter().write("男女都不是");
 }
 //将数据写到页面中
 } catch (IOException e) {
 e.printStackTrace();
 }
 }
jQuery ajax请求struts action实现异步刷新
标签:ref 编写 javaee write rri 方式 pre and dtd
原文地址:http://www.cnblogs.com/2881064178dinfeng/p/6979514.html