struts2 +jquery+ajax简单小例子

 

首先写页面,主要代码为:

<script type="text/javascript" src="js/jquery-1.6.1.js"></script>
 <script type="text/javascript">
 $(document).ready(function(){
  $("input").click(function(){
 
 $.ajax({
 url:'<%=basePath%>strutsJ.do',
 error:function(){
 alert("this has errors!!");
 },
 success:function(data){
 alert(data);
 }
 });
 });
 });
 </script>
  </head>
  
  <body>
   <input type="submit" value="submit"/>
  </body>


 
然后是action,代码为import java.io.IOException;

import org.apache.struts2.ServletActionContext;

public class TestAction {

    private String result;


    // ajax返回结果
    public String getResult() {
        return result;
    }

    public String execute() {
        this.result = "Hello! ";
        System.out.println("this is action here!!");
        try {
   ServletActionContext.getResponse().getWriter().print(result);
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } 

        return null;
    }

}


其次是struts.xml,代码为:

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE struts PUBLIC
        "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN"
        "http://struts.apache.org/dtds/struts-2.1.dtd">

<struts>
 <!--指定web应用的默认编码集,相当于调用HttpServletRequest.setCharacterEncoding方法 -->
 <constant name="struts.i18n.encoding" value="UTF-8" />
 <!-- 指定需要struts2处理的请求后缀,默认值为action. 如果用户需要指定多个请求后缀,则多个后缀之间以英语逗号(,)隔开 -->
 <constant name="struts.action.extension" value="do" />

 

 <package name="struts-platform" extends="struts-default" namespace="/">
  <!--自定议返回类型 -->
  <action name="strutsJ" class="lqx.TestAction">
  
  </action>
  
 </package>
</struts>  


最后是web.xml,代码为:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
 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_2_5.xsd">
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  
  <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>*.do</url-pattern>
 </filter-mapping>
</web-app>


结束语:这是一个关于jquery ajax和struts2结合的一个小例子,只是一个最简单的流程,但却是最基本,最关键的一步。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值