cool hit counter SSH framework tour - struts2 (4)_Intefrankly

SSH framework tour - struts2 (4)


1.Struts2 Interceptor

1.1 AOP Ideas

AOP stands for Aspect Objected Prograing. The interceptor in struts2 is an implementation of this programming strategy. The AOP idea is to extend the functionality and improve the reusability of the code without modifying the source code on the basic functionality.

1.2 Overview of interceptors

Many features of the struts2 framework are based on interceptors. struts2 has many interceptors, and the default interceptor is executed every time. Speaking of interceptors, there is another kind of important concept - the interceptor chain (known as an interceptor stack in struts2). An interceptor chain is a bunch of interceptors linked into a chain in a certain order, and when the intercepted method or field is accessed, the interceptors in the interceptor chain are called in the order in which they are defined.

1.3 struts2 interceptor principle

struts2 The interception is done through the xml The configuration of the file implements the, The default interceptor is in the struts2-core-*.jar package struts-default.xml documents, may View source code。 When a request is received,struts2 Will first look forxml configuration file, and instantiate the interceptor object according to the configuration, And then strung together in a chain, The request goes through each interceptor, Only then can it be implemented Action Methods in, To get the desired result in the end。 So many interceptors, Use a proxy object to make dynamic calls to them。 proper action When the request arrives, establish Action proxy object of the, This proxy object is in the Action Execute default interceptors and other interceptors before method execution( User-defined interceptors), And finally. Action Corresponding method calls, Here's the idea of the data structure stack。 It is the bottom of the proxy object call stack that is Action Calling of methods, Then after returning to the previous interceptor, cascading exit。

The design of the struts2 interceptor structure is a typical application of the chain of responsibility pattern, first dividing the entire execution into a number of elements of the same type, each with a different logical responsibility, and placing these elements into a stack-type data structure, each of which in turn has the responsibility for the next element of the execution call. Taking a complex system and dividing it up so that the logic of each part can be highly reusable and scalable, the interceptor design in struts2 is brilliant.

Principle of implementation

View source code

find web.xml Configure in the file interceptor class location , find this class in the execute.executeAction(request, response, mapping) method, go to this method to see thatdispatcher.serviceAction(request, response, mapping) , after entering this method to find ActionProxy proxy = getContainer().getInstance(ActionProxyFactory.class).createActionProxy(namespace, name, method, extraContext, true, false) This method creates a proxy object for the action, not a new one, so go on and find the proxy.execute() method, go to the method view and you'll see that it's an interface, so find the class that implements this method StrutsActionProxy , found in this class execute() method, the return value of which is invocation.invoke() to execute the method in the Action, go to the method view which is also an interface and find the implementation class of this method DefaultActionInvocation , in this class of invoke() method has an operation that traverses the interceptor if (interceptors.hasNext()) , the next interceptor is executed after one interceptor is executed, and finally returnsinvocation.invoke() The method in the Action is executed.

1.4 The difference between interceptors and filters

  • Filters can theoretically filter any content, such as jsp pages, html pages, servlets, image paths, etc.
  • Interceptors can only intercept Actions, and create an Action, multiple objects of the Action, on each visit.

1.4 Custom Interceptors

There are a number of default interceptors in struts2. Open the struts-default.xml file in the struts2-core-*.jar package, and in the <interceptor-stack name="paramsPrepareParamsStack"> The interceptor in the tag is the default interceptor for struts2. In the actual development, if you want to use the interceptor function that is not available in struts2, then you have to write your own custom interceptor.

View the source code to see the structure of the interceptor class

In the struts-default.xml file, there are a number of interceptors in the <interceptors> Package name with interceptor in tag, You can find one to enter to view, These default interceptor class Both inherit from the abstract interceptor class AbstractInterceptor, abstraction interceptor class there is in it init(),destroy(),intercept() Three methods。init() method performs the initialization of the interceptor,destroy() method performs the destruction of the interceptor,intercept() method performs interceptor-specific logical operations。 However, it is recommended in development to inherit MethodFilterInterceptor class to implement a custom interceptor so that certain methods in the Action can be left unintercepted.

Instead of calling the interceptor's methods directly in the Action, the interceptor and Action establish a relationship by way of a configuration file.

Steps for interceptor implementation.

    1. Create an interceptor class that inherits the MethodFilterInterceptor class
    1. Override the doIntercept() method in the MethodFilterInterceptor class and write the interceptor logic in this method

Steps for interceptor configuration.

    1. In the case of an intercept to be action The label is located in the package Declare interceptors in tags
    1. In the specific action Custom interceptors using declarations in tags
    1. Manually configuring struts2's default interceptor

The following is an example of a user login to illustrate the use of a custom interceptor.

In a web application, the user needs to be logged in before they can use the features of the main page. If the user is not logged in, they are made to log in before using the features of the main page, and the user name is saved in the session if the user is successfully logged in.

The sample code is as follows.

interceptor class

package cc.wenshixin.interceptor;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.MethodFilterInterceptor;

public class LoginInteceptor extends MethodFilterInterceptor{

     // write the interceptor logic in this method
    protected String doIntercept(ActionInvocation invocation) throws Exception {
         // Determine if there is a username in the session, i.e. if the user is logged in
        HttpServletRequest request = ServletActionContext.getRequest();
        Object obj = request.getSession().getAttribute("username");
        if(obj != null)
            // already log in, then implement Action  Methods in
            return invocation.invoke();
            // not log in, then the return value causes it to jump to login page
            return "login";

Action Class

package cc.wenshixin.action;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

public class ActionDemo extends ActionSupport{
    public String login()
         // Get form data
        HttpServletRequest request = ServletActionContext.getRequest();
        String username = request.getParameter("username");
        String password = request.getParameter("password");
         // here for simplicity just write dead judgment, the actual development to be in the database query
        if("admin".equals(username) && "123".equals(password))
             // Login successfully, set session value, and pick to go to main page
            request.getSession().setAttribute("username", username);
            return "success";
//Incorrect username and password will jump back to the login page
            return "login";
    public String add()
        // Jump to Add page
        return "add";
    public String delete()
        // Jump to Delete page
        return "delete";

struts2 configuration file

Note: If you configure a custom interceptor in the configuration file, the default struts2 interceptor will not be executed, so use the default interceptor manually for a bit.

<?xml version="1.0" encoding="UTF-8"?>
  "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
  <package name="demo" extends="struts-default" namespace="/">
    <!--  Statement Interceptor -->
      <interceptor name="loginInteceptor" class="cc.wenshixin.interceptor.LoginInteceptor"></interceptor>
    <action name="user-*" class="cc.wenshixin.action.ActionDemo" method="{1}">
      <!--  Using custom interceptors -->
      <interceptor-ref name="loginInteceptor">
        <!--  Ways to configure not to intercept, Multiple methods separated by commas -->
        <param name="excludeMethods">login</param>
      <!--  Manually use the default interceptor -->
      <interceptor-ref name="defaultStack"></interceptor-ref>
      <!--  Set page jump to redirect method -->
      <result name="success" type="redirect">/index.jsp</result>
      <result name="login" type="redirect">/login.jsp</result>
      <result name="add" type="redirect">/add.jsp</result>
      <result name="delete" type="redirect">/delete.jsp</result>

jsp page

    1. login page
<%@ page language="java" contentType="text/html; charset=UTF-8"
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
  <h1> login page</h1>
  <form action="{pageContext.request.contextPath}/user-login.action" method="post">
         user ID:<input type="text" name="username"><br>
         pin number:    <input type="password" name="password"><br>
      <input type="submit" value=" log in"> 
    1. home page
<%@ page language="java" contentType="text/html; charset=UTF-8"
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
  <h1> welcomes ${sessionScope.username}  main page</h1>
  <a href="{pageContext.request.contextPath}/user-add.action" target="_parent"> Jump to Add page</a>
  <a href="{pageContext.request.contextPath}/user-delete.action" target="_parent"> Jump to Delete page</a>
    1. Add page
<%@ page language="java" contentType="text/html; charset=UTF-8"
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
  <h1> this is Add page</h1>
    1. Delete page
<%@ page language="java" contentType="text/html; charset=UTF-8"
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
  <h1> This is the delete page</h1>

2.struts2 tag library

2.1 Plain label

  • <s:property>: harmony OGNL Expressions used together in jsp page Get the data in the value stack in
  • <s:iterator>: Get value stack list Data of the set, travel throughout list The values in the set
  • <s:debug>: View the value stack structure and data

2.2 Form labels

2.2.1 Review of HTML form-related tags


<form action="" method="" enctype="">

input item

Common input items. <input type="text"> pin number input item: <input type="password"> choose individually input item: <input type="radio"> multiple choice input item: <input type="checkbox"> File upload item. <input type="file"> private input item: <input type="hidden"> Normal buttons. <input type="button"> Submit button. <input type="submit"> Picture button. <input type="image"> Reset button. <input type="reset"> pull down input item: <select><option></select> Text field. <textarea rows="" cols=""></textarea>

2.2.2 The corresponding form tags in struts2 (just know them)

Note that the struts2 tag library should be introduced in the jsp.

    <!--  ordinary input item -->
    <s:textfield name="username" label=" user ID"></s:textfield>
    <!--  pin number input item -->
    <s:password name="password" label=" pin number"></s:password>
    <!--  choose individually input item -->
      <!-- value is written in the same way as the displayed value of -->
    <s:radio list="{' male',' women',' secrecy'}" name="sex" label=" sex"></s:radio>
      <!-- value write the value of the value and the displayed value are not the same -->
    <s:radio list="#{'nan':' male','nv':' women','secret':' secrecy'}" name="sex" label=" sex"></s:radio>
    <!--  checkbox input item -->
    <s:checkboxlist list="{' study',' write characters',' paint'}" name="love" label=" hobbies"></s:checkboxlist>
    <!--  pull down input item -->
    <s:select list="{' Beijing, capital of People's Republic of China',' Shanghai',' Guangzhou'}" name="address" label=" address"></s:select>
    <!--  documents input item -->
    <s:file name="file" label=" Uploading files"></s:file>
    <!--  private input item -->
    <s:hidden name="hidden" value="123"></s:hidden>
    <!--  text field -->
    <s:textarea rows="10" cols="10"></s:textarea>
    <!--  Submit button -->
    <s:submit value=" submit"></s:submit>
    <!--  Reset button -->
    <s:reset value=" reprovision"></s:reset>

The page effect is shown below

rendering (visual representation of how things will turn out)

The page source code is shown below

View the page source code, you can find that struts2 form tag inside is through the table to layout, which does not meet the current page layout (Div layout), but also not conducive to the beautification of the page, so struts2 form tag is basically not used.

page source code

2、Hadoop distributed computing model MapReduce IV programming advancement
3、Digital health has become a national strategy security remains a challenge
4、Big 5 Exchange BTC Large TopUp Withdrawal Data
5、Blockchain layout in healthcare technology application draws expectations

    已推荐到看一看 和朋友分享想法
    最多200字,当前共 发送