zoukankan      html  css  js  c++  java
  • [转]Eclipse中配置Struts2并实现HelloWorld

    Struts2.xml的配置说明(—)

    http://www.cnblogs.com/taxuewuhen/archive/2012/07/12/2588928.html

    按struts2小例子配置开发环境。配置好后目录如下:                                             

    Struts2.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.enable.DynamicMethodInvocation" value="true" /><!-- 动态方法调用应设为true -->
        <constant name="struts.devMode" value="true" />
        
        <!-- namespace相当于路径,访问方式如下:/teacher/a/b/c/d/hello.action,
            先找 /teacher/a/b/c/d这个namespace,若存在,则找hello.action,若action找到,则进行处理,若action找不到,会报错,
                若namespace不存在,则找下级namespace即/teacher/a/b/c再次执行上述查找。直到/这个根namespace,若还找不到action,
                则会报错。
        -->
        <package name="default" namespace="/" extends="struts-default">
            <!-- 这些配置要注意符合struts2配置的先后顺序 -->
            <default-action-ref name="hello"/>   <!-- 配置默认action,即在该包下若找不到要访问的action,则就交给默认action处理 -->
        
            <global-results>   <!--配置global-result 这些result该包下所有action都可以使用-->
                <result name="error">/index.jsp</result>
            </global-results> 
               
            <global-exception-mappings>  <!-- 配置Exception-mapping来处理异常 ,交给相应的页面处理-->
                <exception-mapping result="error" exception="java.lang.Exception"/>
            </global-exception-mappings>
            
            <action name="hello"><!-- 若action的class和method没有配,默认调用ActionSupport.execute(),返回"success"-->
                <result>/index.jsp</result>  <!-- 默认result的name="success",type="dispatcher" -->
                <result name="error">/index.jsp</result>
                
                <exception-mapping result="error" exception="java.lang.Exception"/>   <!-- 在action配置该action的异常处理 -->
            </action>
        </package>
        <package name="teacher" namespace="/teacher" extends="struts-default">
            <action name="teacherAdd" class="cn.com.soft.action.TeacherAction" method="add">
                <param name="name">zhangsan</param>   <!-- 向action中传递静态参数 -->
                <param name="age">23</param>
                <result name="add_success">/teacher_add_success.jsp</result>
            </action>
            <!-- 可以使用/teacher!add.action来动态方法调用 method也可以配置-->
            <action name="teacher" class="cn.com.soft.action.TeacherAction">  
                <result name="add_success">/teacher_add_success.jsp</result>
                <!-- result type 有好多种, 可以在struts-default.xml查看,
                    默认dispatcher服务器端跳转,redirect客户端跳转   这两个只能跳转到页面
                    chain服务器端跳转,redirectAction客户端跳转  这两个跳转到action
                -->
                <result name="delete_success">/teacher_delete_success.jsp</result>
                <result name="redirect" type="redirect">/teacher_delete_success.jsp</result>
                <result name="chain" type="chain">teacherAdd</result>
                <result name="redirectAction" type="redirectAction">
                    <param name="actionName">hello</param> <!-- 若action不在同一个package中,配这两个参数 -->
                    <param name="namespace">/</param>
                </result>
            </action>
        </package>
        <!-- 使用通配符来进行action方法调用 -->
        <package name="user" namespace="/user" extends="struts-default"> 
            <action name="*_*" class="cn.com.soft.action.{1}Action" method="{2}">
                <result name="{2}_success">/${path}.jsp?path=${path}</result>  <!-- ${path}是从valueStack中取数据,动态跳转 和传递参数-->
            </action>
        </package>
    </struts>
    复制代码

    Teacher.java如下:

    复制代码
    package cn.com.soft.model;
    
    public class Teacher {
    
        private String name ;
        
        private int age ;
    
        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;
        }
    }
    复制代码

    TeacherAction.java如下:

    复制代码
    package cn.com.soft.action;
    
    import java.util.Map;
    
    import javax.servlet.ServletContext;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpSession;
    
    import org.apache.struts2.ServletActionContext;
    import org.apache.struts2.interceptor.ApplicationAware;
    import org.apache.struts2.interceptor.RequestAware;
    import org.apache.struts2.interceptor.ServletRequestAware;
    import org.apache.struts2.interceptor.SessionAware;
    import org.apache.struts2.util.ServletContextAware;
    
    import cn.com.soft.model.Teacher;
    
    import com.opensymphony.xwork2.ActionContext;
    import com.opensymphony.xwork2.ActionSupport;
    
    public class TeacherAction extends ActionSupport 
                    implements RequestAware,SessionAware,ApplicationAware ,
                    ServletRequestAware ,ServletContextAware {
        /**
         * 使用属性和Model来接受参数
         */
        private String name ;
        private int age ;
        private Teacher teacher ;
        
        private int type ;
        
        /**
         * 实现接口来获取request、session、application
         */
        private Map<String, Object> request3 ;
        private Map<String, Object> session3 ;
        private Map<String, Object> application3 ;
        
        private HttpServletRequest request4 ;
        private HttpSession session4 ;
        private ServletContext application4 ;
    
        /**
         * @method:add()
         * @return : add_success
         */
        public String add(){
            System.out.println("name :" + name );
            System.out.println("age : " + age);
            
            //获取request、session、context的常用两种方式,我们也可以使用implements接口:
            @SuppressWarnings("unchecked")
            Map<String, Object> request = (Map<String, Object>) ActionContext.getContext().get("request") ;
            Map<String, Object> session = ActionContext.getContext().getSession() ;
            Map<String, Object> application = ActionContext.getContext().getApplication() ;
            request.put("request", "requestAttribute") ;
            session.put("session", "sessionAttribute") ;
            application.put("application", "applicationAttribute") ;
            
            HttpServletRequest request2 = ServletActionContext.getRequest() ;
            HttpSession session2 = request2.getSession() ;
            ServletContext application2 = ServletActionContext.getServletContext() ;
            request2.setAttribute("request2","requestAttribute2") ;
            session2.setAttribute("session2", "sessionAttribute2") ;
            application2.setAttribute("application2", "applicationAttribute2") ;
            return "add_success" ;
        }
        /**
         * @method:delete()
         * @return : delete_success
         */
        public String delete(){
            if(type == 1 ){      
                return "redirect" ;
            }else if (type == 2) {
                return "chain" ;
            }else if (type == 3) {
                return "redirectAction" ;
            }
            return "delete_success" ;
        }
    
        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 Teacher getTeacher() {
            return teacher;
        }
    
        public void setTeacher(Teacher teacher) {
            this.teacher = teacher;
        }
    
        //另一种实现接口来获得request、session、application
        public void setApplication(Map<String, Object> application) {
            application3 = application ;
        }
    
        public void setSession(Map<String, Object> session) {
            session3 = session ;
        }
    
        public void setRequest(Map<String, Object> request) {
            request3 = request ;
        }
    
        //第四种获得request、session、application
        public void setServletContext(ServletContext context) {
            application4 = context ;
        }
    
        public void setServletRequest(HttpServletRequest request) {
            request4 = request ;
            session4 = request.getSession() ;
        }
        public int getType() {
            return type;
        }
        public void setType(int type) {
            this.type = type;
        }
    }
    复制代码

    UserActioin.java如下:

    复制代码
    package cn.com.soft.action;
    
    import com.opensymphony.xwork2.ActionSupport;
    
    public class UserAction extends ActionSupport {
    
        private String path ;
        
        public String add(){
            
            path = "user_add_success" ;
            return "add_success" ;
        }
        
        public String delete(){
            
            path = "user_delete_success" ;
            return "delete_success" ;
        }
    
        public String getPath() {
            return path;
        }
    
        public void setPath(String path) {
            this.path = path;
        }
    }
    复制代码

    拦截器后面再写。

    在Eclipse中配置struts-core.jar和x-work.jar的源文件,方式如下:

    在引入的struts-core.jar和x-work.jar两个jar包上分别点击右键,打开properties对话框,在对话框中选中Java Source Attachment选项,在右边点击External Folder打开文件查找窗口。

    struts-core.jar找:E:/文档/struts-2.3.1.2-all/struts-2.3.1.2/src/core/src/main/java 这个文件夹   确定  OK

    x-work.jar找:E:/文档/struts-2.3.1.2-all/struts-2.3.1.2/src/xwork-core/src/main/java这个文件夹  确定  OK

    E:/文档/这个目录根据自己情况确定下载的struts-2.3.1.2-all的位置

    本文转自:http://913046394-qq-com.iteye.com/blog/1456584

    刚刚把玩了Struts2,是第一次接触Struts2,就不做过多的解释了。下面介绍在Eclipse中配置Struts2的过程:

    一、下载Struts2,因为Struts2是开源的,百度或者google一下就可以找到下载地址。我下载的是struts-2.3.1.2版本 的,解压之后入下图:



    apps目录:Struts2的范例

    docs目录:Struts2的文档

    lib目录:Struts2的类库

    src目录:关于Struts2的一些资源

    二、现在是利用apps中的范例实现一个helloworld的action,在apps目录下有几个war文件,如下图:



     

    这几个文件可以用WinRAR打开,我用好压打开struts2-blank.war之后,如下图



     

    在WEB-INF目录下打开classes目录,找到struts.xml文件,如下图



     

    将struts.xml文件复制到Eclipse新建工程的src目录下,在我的工程中如下图:



     

    三、如上面所示,在WEB-INF目录下打开lib目录,如下图:



     打开之后会有如上图的jar包,为保险起见,将所有的jar包复制到新建工程的lib目录下,在我的工程中如下图:



     

    四、返回到WEB-INF目录下,找到web.xml文件并打开,打开之后会看到有如下代码:

    <?xml version="1.0" encoding="UTF-8"?>
    <web-app id="WebApp_9" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

        <display-name>Struts Blank</display-name>

        <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>

        <welcome-file-list>
            <welcome-file>index.html</welcome-file>
        </welcome-file-list>

    </web-app>

     将其中<filter></filter>和<filter-mapping></filter-mapping>元素复制到Eclipse新建工程的web.xml文件中,我的web.xml文件如下所示:

    <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
      <display-name>Structs0317</display-name>
      <welcome-file-list>
        <welcome-file>index.html</welcome-file>
        <welcome-file>index.htm</welcome-file>
        <welcome-file>index.jsp</welcome-file>
        <welcome-file>default.html</welcome-file>
        <welcome-file>default.htm</welcome-file>
        <welcome-file>default.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>

    五、在Eclipse中打开复制来的struts.xml文件,将文件中<struts>和</struts>之间的内容注释掉,并添加如下所示的代码:

     
    <package name="default" namespace="/" extends="struts-default">
    
            <action name="hello">
                <result>
                    /Hello.jsp
                </result>
            </action>
        </package>

    六、在Ecplise中新建一个Hello.jsp文件,在<body>标签之间写如下代码:

         

    Hello Struts2<br>

    然后启动Tomcat服务器,在IE浏览器中输入http://localhost:8080/Structs0317会发现出现如下错误:

    There is no Action mapped for namespace [/] and action name [] associated with context path [/Structs0317]. - [unknown location]
    at com.opensymphony.xwork2.DefaultActionProxy.prepare(DefaultActionProxy.java:185)
    at org.apache.struts2.impl.StrutsActionProxy.prepare(StrutsActionProxy.java:63)
    at org.apache.struts2.impl.StrutsActionProxyFactory.createActionProxy(StrutsActionProxyFactory.java:39)
    at com.opensymphony.xwork2.DefaultActionProxyFactory.createActionProxy(DefaultActionProxyFactory.java:58)
    at org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:500)
    at org.apache.struts2.dispatcher.ng.ExecuteOperations.executeAction(ExecuteOperations.java:77)
    at org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:91)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:230)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:104)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:261)
    at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:844)
    at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:581)
    at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447)
    at java.lang.Thread.run(Unknown Source)

    其实正确的输入是http://localhost:8080/Structs0317/hello或者http://localhost:8080/Structs0317/hello.action  访问到的Hello.jsp如下图所示:



     

    OK,至此所有的配置都配置好了,接下来就可以好好的去玩Struts2了。在这里还想再谈一点感受就是,遇到新的东西首先是先拿去用,等会用了在好好研究它的原理和细枝末节,就像别人给你一把枪一样,你不会一拿到枪就把它拆开来研究它的内部构造,而是直接拿去用,会用了,觉得这东西有意思了,再好好去研究的内部结构甚至是仿制出一把出来。这也是我以前所没有意识到的,希望今后改进,好好学习,天天向上。

  • 相关阅读:
    23种设计模式(12):策略模式
    23种设计模式(11):责任链模式
    23种设计模式(10):命令模式
    23种设计模式(9):访问者模式
    23种设计模式(8):观察者模式
    23种设计模式(7):中介者模式
    23种设计模式(6):模版方法模式
    创建型模式总结
    23种设计模式(5):原型模式
    leetcode6
  • 原文地址:https://www.cnblogs.com/freeliver54/p/2550160.html
Copyright © 2011-2022 走看看