struts1和spring 1.2 的简单配置(我是初学者)
以前用过struts2,但没用过struts1,最近项目上需要用到1,所以这两天在看1的配置,自己动手配了一个测试项目,
首先把包导近来,包括commons、struts1、spring、log4j的包,
其次,配置web.xml
如下:
注意点:我刚开始在<set-property property="contextConfigLocation" value="/WEB-INF/classes/conf/spring/spring.xml" />走了弯路,写成 value="conf/spring/spring.xml"。以为这样可以了,并且刚开始没配log4j,看不出来什么错误,浪费了很多时间,后来裴了log4j才知道是路径搞错了.
在然后,在/WEB-INF/classes/conf/spring里配一个spring.xml,
如下;
再然后,添加action类,添加jsp,添加html文件。
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;public class TestAction extends DispatchAction {protected ActionForward unspecified(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { System.out.println("-----------UserAction.unspecified()-----------"); // 调用业务逻辑操作 request.setAttribute("welcome", "from unspecified"); TestForm testForm = (TestForm)form; System.out.println(testForm.getName()); return mapping.findForward("success"); } public ActionForward go(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {if(form!=null){ TestForm testForm = (TestForm)form; if(testForm.getName()!=null){ System.out.println(testForm.getName());}}request.setAttribute("welcome", "from go method");return (mapping.findForward("success"));}public ActionForward come(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { request.setAttribute("welcome", "from come method");return (mapping.findForward("success"));}}
jsp和html文件我就不列出来了,太长了。
然后一切就可以了,这个mini练手项目就搭起来了,大家可以根据自己需求往里面添砖加瓦,让它不断壮大。
注意点:为了可以使用action中的其它方法,需要继承DispatchAction,这样可以通过url来指定你使用的方法,别忘了重写unspecified方法,写清楚没有指定方法时应该怎么办。
简单说明一下,DispatchAction本身时继承了Action,并重写了它的execute方法(可以看一下它的源码,应该接受parameter,并做相应处理),所以我们这里就不要重写execute了,否则很可能报错。