首先是创建web项目T,然后修改web.xml,加入下面这一段:
org.apache.struts.action.ActionServlet
/WEB-INF/struts.xml
这是为了引入struts(这里使用的struts1),然后下面这段是struts.xml:
"http://jakarta.apache.org/struts/dtds/struts-config_1_1.dtd">
type="form.CommonForm">
然后便是action代码:
package action;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;
import org.json.JSONWriter;
import form.CommonForm;
public ActionForward execute(ActionMapping mapping,
ActionForm form,
HttpServletRequest request, HttpServletResponse
response)
throws Exception {
String param = mapping.getParameter();
String cmd = request.getParameter(param);
CommonForm cform = (CommonForm) form;
if(cmd!=null){
return dispatchMethod(mapping, cform, request,
response, cmd);
}
return mapping.findForward("welcome");
}
words.append("hello "+cform.getName());
request.setAttribute("words", words.toString());
return mapping.findForward("welcome");
}
public ActionForward doAjax(ActionMapping mapping,
ActionForm form,
HttpServletRequest request, HttpServletResponse
response)
throws Exception {
CommonForm cform = (CommonForm) form;
String msg = "";
boolean success = true;
response.setContentType("text/plain");
response.setCharacterEncoding("UTF-8");
JSONWriter jsw = new
JSONWriter(response.getWriter()).object().key(
"success").value(Boolean.valueOf(success));
if (msg != null) {
jsw.key("msg").value(msg != null ? msg : "");
}
if(cform.getName().equalsIgnoreCase("rains")){
jsw.key("address").value("地址");
}
jsw.endObject();
return null;
}
}
以及form:
package form;
import org.apache.struts.action.ActionForm;
public class CommonForm extends ActionForm{
private static final long serialVersiOnUID= 6080705692924414987L;
private String name;
private int age;
private int phone;
private String address;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int getPhone() {
return phone;
}
public void setPhone(int phone) {
this.phOne= phone;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
然后万事具备,除了前台jsp,呼呼~~~
<%@ page language="java" import="java.util.*"
pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath =
request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
你的名字:
你的年龄:
你的电话:
你的地址:
部署好项目(此处测试时使用了tomcat,呵呵~)
页面效果如下:
我们输入名字rains,如下:
点击按钮,就可以看到成果了:
注意anction里面这一个逻辑:
if(cform.getName().equalsIgnoreCase("rains")){
jsw.key("address").value("地址");
}
我们只有在这里加上自己想要的复杂逻辑(而不是测试这样简单的随意设置一个),然后在页面上var address = json.address;拿到你想要的值并且显示出来。如此则大功告成。
最后附加的福利~~吼吼~~
ps:欢迎留言