struts2 +jquery+ajax简单小例子



struts2 +jquery+ajax简单小例子

首先写页面,主要代码为:
[plain] view plaincopy
<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;

[plain] view plaincopy
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,代码为:

[plain] view plaincopy
<?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,代码为:
[plain] view plaincopy
<?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结合的一个小例子,只是一个最简单的流程,但却是最基本,最关键的一步。

http://blog.csdn.net/lqx1988221/article/details/8308100