[Struts2] Introduction and Getting Started

I. Overview

  1. Question: What is the framework, the framework of what is the use?
    • Framework is the code (semi-finished) to achieve some of the features, use the framework to simplify enterprise-class software development and improve development efficiency.
    • Learning framework, the framework should clearly know what to do, what work needs its own Coding
  2. Question: What is the Struts2 framework, what use is it?
    • Struts Struts2 is the next generation of products, is a merger of the new framework Struts2 technology based on Struts1 and WebWork. Struts2 its new architecture and architecture Struts1 huge difference. In Struts2 WebWork core, Struts2 = Struts1 + Webwork
    • Struts2 framework is Apache products.
    • Struts2 is a standard MVC framework.
    • JavaWeb in Model2 mode is a mode mvc
    • Model2=Servlet+Jsp+JavaBean
    • Struts2 framework is used in Javaweb development.
    • Use Struts2 framework, we can simplify the development of the web, and reduce the coupling procedure.
  3. Struts2 framework similar products:
    • Struts1 Webwork Jsf Springmvc
    • SSH --- Struts2 + Spring + Hibernate
    • SSM --- SpringMVC + Spring + Mbatis
  4. XWork --- it is the core of WebWork
    • Xwork offers many core features: front-end interceptor (interceptor), run-time form attribute validation, type conversion, a powerful expression language (OGNL - the Object Graph Navigation Language), IoC (Inversion of Control reverse control) containers

Two, Struts2 Quick Start program

2.1 Comparison of the development process

  • Web development process: index.jsp ------> HelloServlet --------> hello.jsp
  • Struts2流程:index.jsp------>HelloAction--------->hello.jsp

2.2 introduced dependence

<!-- https://mvnrepository.com/artifact/org.apache.struts/struts2-core -->
<dependency>
    <groupId>org.apache.struts</groupId>
    <artifactId>struts2-core</artifactId>
    <version>2.3.16.3</version>
</dependency>

2.2 Creating jsp page

  • Creating index.jsp page (later modified)
  • Creating hello.jsp page (as follows)
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head> 
    <title>My JSP 'index.jsp' starting page</title>
  </head>
  
  <body>
    <h1>hello Struts2</h1>
  </body>
</html>

2.3 front controller disposed in web.xml

  • Configuration front-end controller (core controller) in web.xml ----- is a Filter
<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>

2.4 struts.xml create profile

  • Struts.xml create a configuration file in the src (lower classes), this is the framework struts2 configuration file.

2.4 Create a class HelloAction

  • Request to create a return value of type String method, note that no parameters HelloAction class.
public class HelloAction {
    
    public String say() {
        return "good";
    }
}

2.5 configuration file HelloAction in struts.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
    "http://struts.apache.org/dtds/struts-2.3.dtd">

<struts>

    <package name="default" namespace="/" extends="struts-default">
        <action name="hello" class="com.hao.action.HelloAction"
            method="say">
            <result name="good">/hello.jsp</result>
        </action>
    </package>
    
</struts>

2.6 Add Connection test in index.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>  
    <title>My JSP 'index.jsp' starting page</title>
  </head>
  <body>
    <a href="${pageContext.request.contextPath}/hello">第一次使用struts2</a>
  </body>
</html>

2.7 Test

  • In the address bar: http://localhost:8080/Struts2-001-EntryP/index.jspaccess, you can see the method say HelloAction class execution, and also jump to the hello.jsp.

Third, entry procedures for process analysis

  • Imitate struts2 process is complete entry procedures:

3.1 Creating a project, dependent on the introduction of Maven

<dependency>
    <groupId>org.apache.struts</groupId>
    <artifactId>struts2-core</artifactId>
    <version>2.3.16.3</version>
</dependency>

<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>servlet-api</artifactId>
    <version>3.0-alpha-1</version>
    <scope>provided</scope>
</dependency>

<!-- https://mvnrepository.com/artifact/dom4j/dom4j -->
<dependency>
    <groupId>dom4j</groupId>
    <artifactId>dom4j</artifactId>
    <version>1.6.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-beanutils/commons-beanutils -->
<dependency>
    <groupId>commons-beanutils</groupId>
    <artifactId>commons-beanutils</artifactId>
    <version>1.9.3</version>
</dependency>

Custom filters StrusFilter 3.2

  • 1. Create a Filter ---- StrutsFilter
  • 2. Configure StrutsFilter in web.xml
<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>Archetype Created Web Application</display-name>
  <filter>
    <filter-name>StrutsFilter</filter-name>
    <display-name>StrutsFilter</display-name>
    <description></description>
    <filter-class>com.hao.filter.StrutsFilter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>StrutsFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
</web-app>
  • 3. Complete the StrutsFilter the interception, and the access method Action, Jump to page hello.jsp operation.
public class StrutsFilter implements Filter {

    public void init(FilterConfig filterConfig) throws ServletException {

    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
            throws IOException, ServletException {

        // 1.强转
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;

        // 2.操作

        // 2.1 得到请求资源路径
        String uri = request.getRequestURI();
        String contextPath = request.getContextPath();
        String path = uri.substring(contextPath.length() + 1);

        // System.out.println(path); // hello

        // 2.2 使用path去struts.xml文件中查找某一个<action name=path>这个标签
        SAXReader reader = new SAXReader();

        try {
            // 得到struts.xml文件的document对象。
            Document document = reader.read(new File(this.getClass().getResource("/struts.xml").getPath()));

            Element actionElement = (Element) document.selectSingleNode("//action[@name='" + path + "']"); // 查找<action
                                                                                                            // name='hello'>这样的标签

            if (actionElement != null) {
                // 得到<action>标签上的class属性以及method属性
                String className = actionElement.attributeValue("class"); // 得到了action类的名称
                String methodName = actionElement.attributeValue("method");// 得到action类中的方法名称。

                // 2.3通过反射,得到Class字节码对象,得到Method对象
                Class<?> actionClass = Class.forName(className);
                Method method = actionClass.getDeclaredMethod(methodName);

                // 处理请求参数封装:

                Object actionObj = actionClass.newInstance();

                // 2.模型驱动
                if (actionObj instanceof MyModelDriven) {
                    MyModelDriven mmd = (MyModelDriven) actionObj;

                    BeanUtils.populate(mmd.getModel(), request.getParameterMap());
                } else {
                    // 1.属性驱动
                    BeanUtils.populate(actionObj, request.getParameterMap());//
                }

                // 2.4 让method执行.
                String returnValue = (String) method.invoke(actionObj); // 是让action类中的方法执行,并获取方法的返回值。

                // 2.5
                // 使用returnValue去action下查找其子元素result的name属性值,与returnValue做对比。
                Element resultElement = actionElement.element("result");
                String nameValue = resultElement.attributeValue("name");

                if (returnValue.equals(nameValue)) {
                    // 2.6得到了要跳转的路径。
                    String skipPath = resultElement.getText();

                    // System.out.println(skipPath);

                    request.getRequestDispatcher(skipPath).forward(request, response);
                    return;
                }
            }

        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        }

        // 3.放行
        chain.doFilter(request, response);

    }

    public void destroy() {
    }

}

3.3 Process Analysis

  • Request ---- StrutsPrepareAndExecuteFilter core controller ----- Interceptors Interceptors (code that implements functions) ----- Action's execute --- results page Result

Four, Struts2 configuration

4.1 Struts2 configuration file load order

  • Struts2 framework to be able to execute, you must be loaded StrutsPrepareAndExecuteFilter.
  • In the init method StrutsPrepareAndExecuteFilter in for Dispatcher initialized.
  • Init method defined in the class Dispatcher to the order described in the loading profile struts2
// [1]   org/apache/struts2/default.properties 
init_DefaultProperties();
// [2]  struts-default.xml,struts-plugin.xml,struts.xml 
init_TraditionalXmlConfigurations(); 
// [3] --- 自定义struts.properties  (源码中的注释没有[4])
init_LegacyStrutsProperties(); 
// [5]  ----- 自定义配置提供
init_CustomConfigurationProviders(); 
// [6] ----- web.xml 
init_FilterInitParameters() ; 
// [7] ---- Bean加载 
init_AliasStandardObjects() ; 
1.default.properties文件
    作用:定义了struts2框架中所有常量
    位置: org/apache/struts2/default.properties ,struts2-core.jar包下
    
2.struts-default.xml
    作用:配置了bean,interceptor,result等。
    位置:在struts的core核心jar包.
    
  struts-plugin.xml
    它是struts2框架中所使用的插件的配置文件。
  struts.xml              
    我们使struts2所使用的配置文件。
        
3.自定义的struts.properties
    我们可以自定义常量。
    
4.web.xml
    
在开发中,后加载文件中的配置会将先加载文件中的配置覆盖。我们一般要记住如下顺序即可:
default.properties
struts-default.xml
struts.xml

About 4.2 Configuring the Action

  1. <package>Role: is used to declare a package. For management action. It is common properties as follows
    • name: it is used to declare a package name, package name can not be repeated, that is, it is unique.
    • namespace: It identifies a unique path to access the combined action of the name attribute of the action tag.
    • extends: it represents the inheritance of the package name.
    • abstrace: It can be a value of true / false, if true, this represents the package is intended to be inherited.
  2. <action> A declaration for action, it is common properties as follows:
    • name: is the action of a name, it is the only (in the same package) which defines the path to access the action with the package in the namespace.
    • class: full name of the Action class
    • method: Action class name of the method to be accessed, a method without parameters, return value String.
  3. <result> Return means for determining the type of result, it is common properties as follows:
    • It returns the name of the action to make the value comparison method, to determine the branch path.

4.3 Other details about the action configuration:

  1. About default value problem
    • <package namespace="默认值"> - the default namespace is ""
    • <action class="默认值" method="默认值">- the default class is the "com.opensymphony.xwork2.ActionSupport"default value method is to execute
    • <result name="默认值"> The default value is the name of "success"
  2. Action regarding access path problems, action configuration now is:

    <package name="default" namespace="/" extends="struts-default">
    <action name="hello" class="com.hao.action.DefaultAction">
    <result>/hello.jsp</result>
    </action>
    </package>
    • When we enter: http://localhost/Struts2-003-ExerConfig/a/b/c/helloYou can also access to the action.
    • Reason: struts2 in action is accessed, it first looks
    • txt 1.namespace="/a/b/c" action的name=hello 没有.
      2.namespace="/a/b action的name=hello 没有
      3.namespace="/a" action的name=hello 没有
      4.namespace="/" action的name=hello 查找到了.

    • If you can not find eventually, it will be reported 404 errors.
  3. The default action.

    • Action: action can not handle other processing path.
    • <default-action-ref name="action的名称" /> , This configuration, when the access path, the other could not handle the action, will perform the action name specified name.
  4. The default action handler class

    • When action configuration, if the class does not write. The default iscom.opensymphony.xwork2.ActionSupport
    • <default-class-ref class="com.hao.action.DefaultAction"/>If this is set, then in the current package, the default handler class that handles the action requested is specified for the class to class.

About 4.4 Constants Configuration

  • default.properties it declares constants in the struts.
  • Question: artificial setting constants, which can be set at the position?

    • 1.struts.xml (most applications),<constant name="常量名称" value="常量值"></constant>
    • 2.struts.properties (basically do not use)
    • 3.web.xml (understand), the configuration constants is to use initialization parameters to configure the StrutsPrepareAndExecuteFilter.
    <init-param>
        <param-name>struts.action.extension</param-name>
    <param-value>do,,</param-value>
    </init-param>
  • Common Constants

    • struts.action.extension=action,, - This constant is used to specify the default frame strus2 intercept extension.
    • <constant name="struts.i18n.encoding" value="UTF-8"/>- equivalent to request.setCharacterEncoding("UTF-8");solve garbled post requests
    • <constant name="struts.serve.static.browserCache" value="false"/> - false does not cache, true browser will cache static content, the production environment is set true, the development environment set up false
    • <constant name="struts.devMode" value="true" /> Do not need to restart the server, providing a detailed error page, modify struts.xml

3.5 struts.xml separate files:

  • Purpose: To read is convenient. A module allows a profile in the file struts.xml by <include file="test.xml"/>introducing another profile.

Five, Action

Way to create 5.1 Action class

  • Three ways to create ways

  1. Create a POJO class.
    • Simple Java objects (Plain Old Java Objects)
    • Refers not implement any interfaces, not inherited any parent class (except Object)
    • Advantages: no coupling.
    • Cons: All work should themselves realize.
    • In struts2 underlying framework is operated by reflection:
      • struts2 framework struts.xml read a complete Action class name
      • obj = Class.forName ( "full class name") .newInstance ();
      • Method m = Class.forName ( "full class name") .getMethod ( "execute"); m.invoke (obj); execute method performed by reflection
  2. Create a class that implements the Action interface. ( com.opensymphony.xwork2.Action)

    • Advantages: low coupling. Provides five results view, we define a behavior method.
    • Cons: All work should themselves realize.
    public static final String SUCCESS = "success";  // 数据处理成功 (成功页面)
    public static final String NONE = "none";  // 页面不跳转  return null; 效果一样
    public static final String ERROR = "error"; // 数据处理发送错误 (错误页面)
    public static final String INPUT = "input"; // 用户输入数据有误,通常用于表单数据校验 (输入页面)
    public static final String LOGIN = "login"; // 主要权限认证 (登陆页面)
  3. Create a class that inherits from ActionSupport class. ( com.opensymphony.xwork2.ActionSupport)

    • ActionSupport class implements the Action interface.
    • Advantages: form validation, error message settings, read the international information three functions are supported.
    • Disadvantages: high coupling.
    • In the development, the third will be used more.

5.2 access on the action

  • By setting the value of 1. The method to determine the access action in which a class method.
    • <action name="book_add" class="com.hao.action.BookAction" method="add"></action>
    • When the visit was book_add, then we will call the add method BookAction class.
    • <action name="book_update" class="com.hao.action.BookAction" method="update"></action>
    • When the visit was book_update, then we will call the update method BookAction class.
  • 2. The use wildcards to simplify the configuration

    • In the configuration file struts.xml
    • <action name="*_*" class="com.hao.action.{1}Action" method="{2}"></action>
    • jsp page
    • book.jsp
    <a href="${pageContext.request.contextPath}/Book_add">book add</a><br>
    <a href="${pageContext.request.contextPath}/Book_update">book update</a><br>
    <a href="${pageContext.request.contextPath}/Book_delete">book delete</a><br>
    <a href="${pageContext.request.contextPath}/Book_search">book search</a><br>
    • product.jsp
    <a href="${pageContext.request.contextPath}/Product_add">product add</a><br>
    <a href="${pageContext.request.contextPath}/Product_update">product update</a><br>
    <a href="${pageContext.request.contextPath}/Product_delete">product delete</a><br>
    <a href="${pageContext.request.contextPath}/Product_search">product search</a><br>
    • When accessing the book add, then the path is Book_add, then for struts.xml file.
    • The first *is the Book
    • The second *is to add
    • For {1} Action ----> BookAction
    • For method = {2} ---> method = add
    • Use wildcards to configure Notes:
    • 1. You must define a uniform naming convention.
    • 2. do not recommend using too many wildcards, read inconvenient.
  • 3. Dynamic method invocation (understand)

    • In struts.xml file
    • <action name="book" class="com.hao.action.BookAction"></action>When access paths: http://localhost/Struts2-003-ExerConfig/book!add
      to add a method to access BookAction class.
    • For book!addthis is the dynamic method invocation.
    • Note: struts2 framework supports dynamic method calls, because the set in the configuration file default.properties dynamic method invocation is true. struts.enable.DynamicMethodInvocation = true

5.3 servlet api acquired in the framework struts2

  • For struts2 framework does not recommend direct use servlet api;
  • Struts2 get in the servlet api There are three ways:

  • 1. be obtained by ActionContext

    • Gets a ActionContext object. ActionContext context=ActionContext.getContext()
    • Get servlet api
    • Note: By ActionContext acquired is not a true Servlet api, but a Map collection.
    1.context.getApplication()
    2.context.getSession()
    3.context.getParameter();---得到的就相当于request.getParameterMap()
    4.context.put(String,Object) 相当于request.setAttribute(String,String);
  • 2. Fill the way to get (this is the real way to get the servlet api)

    • Mention must implement the required action given interface.
    • ServletContextAware: injection ServletContext object
    • ServletRequestAware: injecting request object
    • ServletResponseAware: inject the response object

    • The method of rewriting the interface.

    • Declare a web object, use the interface of the web object parameter assignment statement.

    //获取servlet api  通过注入方式
    public class ServletDemo2Action extends ActionSupport implements
    ServletRequestAware {
    private HttpServletRequest request;
    @Override
    public String execute() throws Exception {
    System.out.println(request.getParameter("username"));
    return null;
    }
    public void setServletRequest(HttpServletRequest request) {
    this.request = request;
    }
    }
    • Expansion: Analysis of its implementation, the use of an interceptor struts2 is completed (the interceptor in struts-default.xml).
    <interceptor name="servletConfig" class="org.apache.struts2.interceptor.ServletConfigInterceptor"/>
    
         if (action instanceof ServletRequestAware) { //判断action是否实现了ServletRequestAware接口
            HttpServletRequest request = (HttpServletRequest) context.get(HTTP_REQUEST); //得到request对象.
    ((ServletRequestAware) action).setServletRequest(request);//将request对象通过action中重写的方法注入。
    }
  • 3. Obtain by ServletActionContext. ServletActionContext the method are static.

//获取servlet api  通过ServletActionContext获取
public class ServletDemo3Action extends ActionSupport {

    @Override
    public String execute() throws Exception {
        HttpServletRequest request = ServletActionContext.getRequest();

        System.out.println(request.getParameter("username"));
        return SUCCESS;
    }

}

5.4 Result Result Type

  • label
  • 1.name the action of the return value of the matching method, jump.
  • 2.type role: is used to define the jump method
  • For its type attribute has the following value: the value of the type defined can take in the file struts-default.xml
<result-type name="chain" class="com.opensymphony.xwork2.ActionChainResult"/>
<result-type name="dispatcher" class="org.apache.struts2.dispatcher.ServletDispatcherResult" default="true"/>
<result-type name="freemarker" class="org.apache.struts2.views.freemarker.FreemarkerResult"/>
<result-type name="httpheader" class="org.apache.struts2.dispatcher.HttpHeaderResult"/>
<result-type name="redirect" class="org.apache.struts2.dispatcher.ServletRedirectResult"/>
<result-type name="redirectAction" class="org.apache.struts2.dispatcher.ServletActionRedirectResult"/>
<result-type name="stream" class="org.apache.struts2.dispatcher.StreamResult"/>
<result-type name="velocity" class="org.apache.struts2.dispatcher.VelocityResult"/>
<result-type name="xslt" class="org.apache.struts2.views.xslt.XSLTResult"/>
<result-type name="plainText" class="org.apache.struts2.dispatcher.PlainTextResult" />
  • 必会: chain dispatcher redirect redirectAction stream
  • dispatcher: it represents a request to forward, is the default. It is generally used to jump from page to action.
  • chain: it is equivalent to forward the request. It is generally used to jump from one action to another action.
  • redirect: redirect it represents it is generally used to jump from page to action
  • redirectAction: it represents it is generally redirected to another action from the jump action.
  • stream: represents the server returns a stream, typically for downloading.

  • Local and global results page results page

<package name="default" namespace="/" extends="struts-default">
    <!-- 全局结果页面 -->
    <global-results>
        <result>/demo1_success.jsp</result>
    </global-results>

    <action name="demo1" class="com.hao.action.ServletDemo1Action">
        <!-- 局部结果页面 -->
    </action>

    <action name="demo2" class="com.hao.action.ServletDemo2Action">
        <!-- <result>/demo1_success.jsp</result> -->
    </action>

    <action name="demo3" class="com.hao.action.ServletDemo3Action">
        <!-- <result type="redirect">/demo1_success.jsp</result> -->
    </action>

</package>

Guess you like

Origin www.cnblogs.com/haoworld/p/struts2-jian-jie-ji-ru-men.html