Struts1 简单示例

  之前都是一直使用Struts2,刚刚入职公司,主要使用Struts1,在网上查阅了一些资料,完成了一个简单的示例

  首先使用Myeclipse在项目中导入Struts1的jar包,Myeclipse会自动创建Struts1所需的配置文件并对web.xml进行必要的配置

  创建的配置文件如下图

  

  文件配置好了,就可以写第一个Action了,代码如下:

 1 public class JsonDataAction extends DispatchAction {
 2 
 3     public ActionForward getTreeData(ActionMapping mapping, ActionForm form,
 4             HttpServletRequest request, HttpServletResponse response)
 5             throws Exception {
 6         TreeDao treeDao = new JdbcTreeImpl();
 7         TreeService treeService = new TreeService();
 8         String json = treeService.getData(treeDao.getTrees()) ;
 9         response.setContentType("text/html;charset=UTF-8");
10         response.getWriter().println(json);
11         return null;
12     }
13 }

  这是一个比较简单的请求Json数据的Action,比较简陋,各位看官见笑了,这里并没有覆盖execute()方法,而是创建了一个getTreeData()方法,

这与之后的struts-config.xml中的配置有关.

  Action写好之后我们就需要配置struts-config.xml,代码如下:

 

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.2//EN" "http://struts.apache.org/dtds/struts-config_1_2.dtd">
 3 
 4 <struts-config>
 5 <action-mappings>
 6     <action
 7       path="/getdata"
 8       scope="request"
 9       parameter="method"
10       type="com.action.JsonDataAction" />
11 </action-mappings>
12 </struts-config>

  在action-mappings中配置action,path为请求路径,scope为请求方式,paramenter为请求路径后跟随的参数,用于直接访问方法,type为该Action的路径

这样配置好之后就可以部署Tomcat,通过访问 http://localhost:8080/struts1/getdata.do?method=getTreeData 来执行这个Action了

  总之呢,Struts1的Action编写有点类似于Servlet,不过Struts也有其他的方法,在以后的工作中慢慢摸索吧

posted @ 2013-03-17 17:26  辣松  阅读(222)  评论(0)    收藏  举报