今天没啥事,像弄一下ajax请求struts2的小demo,结果遇到一些麻烦,最后发现是一个小问题,先看看我的代码吧(很简单,有什么错误欢迎指出,大家一起学习)
struts2包自己在网上能下载到的,
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>/*</url-pattern>
</filter-mapping>
</web-app>
index.jsp的代码:
<%@ page language=”java” contentType=”text/html; charset=UTF-8″
pageEncoding=”UTF-8″%>
<%
String path = request.getContextPath();
// 获得本项目的地址(例如: http://localhost:8080/MyApp/)赋值给basePath变量
String basePath = request.getScheme()+”://”+request.getServerName()+”:”+request.getServerPort()+path+”/”;
// 将 “项目路径basePath” 放入pageContext中,待以后用EL表达式读出。
pageContext.setAttribute(“basePath”,basePath);
%>
<script type=”text/javascript” src=”jquery-1.5.1.min.js”></script>
<!DOCTYPE html PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN” “http://www.w3.org/TR/html4/loose.dtd”>
<html>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=UTF-8″>
<title>Insert title here</title>
</head>
<script type=”text/javascript”>
function submit() {
$.ajax({
async:true,
type:’POST’,
url:”<%=basePath%>user/test”,
success: function(result){
alert(“qqqq”);
}
});
alert(“a”);
}
</script>
<body>
<input type=”button” value=”提交” onclick=”submit()”/>
<form action=”user/test”>
<input type=”submit” value=”test”/>
</form>
</body>
</html>
这里有两个按钮,value=提交的是ajax请求的按钮,value=test的是通过表单提交的按钮
success.jsp页面非常简单,几乎什么也没有
<%@ page language=”java” contentType=”text/html; charset=ISO-8859-1″
pageEncoding=”ISO-8859-1″%>
<!DOCTYPE html PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN” “http://www.w3.org/TR/html4/loose.dtd”>
<html>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=ISO-8859-1″>
<title>Insert title here</title>
</head>
<body>
success
</body>
</html>
struts.xml配置也简单:
<?xml version=”1.0″ encoding=”UTF-8″ ?>
<!DOCTYPE struts PUBLIC
“-//Apache Software Foundation//DTD Struts Configuration 2.0//EN”
“http://struts.apache.org/dtds/struts-2.0.dtd”>
<struts>
<constant name=”struts.devMode” value=”true” />
<package name=”user” extends=”struts-default” namespace=”/user”>
<action name=”test” class=”ActionTest.Test” method=”ajaxTest” >
<result>/success.jsp</result>
</action>
</package>
</struts>
Test 类的代码:
package ActionTest;
import com.opensymphony.xwork2.ActionSupport;
public class Test extends ActionSupport {
public String ajaxTest() {
System.out.println(“———-20——————————–“);
return SUCCESS;
}
}
好了,所有的东西都有了,可以运行了,但是不要忘记要使用$.ajax({})的时候一定要引入jquery-1.5.1.min.js,要不然就会不发请求、、、、、
最新评论