Test the interceptor and login in struts2

Source: Internet
Author: User
Tags i18n

 

Today, I spoke to several Java-loving students about struts2 and focused on its most valuable interceptor.

 

I don't know whether you can remember it. In struts2 server-side verification, I said, "The verification has been completed before arriving at the login action ". I hope someone can raise the question, so that I can say that this is the benefit of the interceptor, so we can study the interceptor.

In fact, interceptors are neither difficult nor difficult to understand. Here we will add some more.

 

Open the interceptor section of the help document (Struts-2.0.6 \ docs \ interceptors.html.

 

Being able to read the English technical documents is one of the essential qualities for programmers. Let's take a look at it. As long as you calm down and repeat it word by word, there is nothing you can't understand. If you cannot understand it, take a look at the figure [Action lifecyle. Action lifecycle, which is surrounded by some interceptors. That is to say, the interceptor will be executed before or after the action is executed.

 

This is the Interceptor. It regards the program as a stream of sequential execution. Before or after the code of the action is executed, the interceptor will interrupt the execution of the action and let the program execute the code of the interceptor first, this may be why we call it an interceptor. Sometimes, the interceptor also blocks action execution. For example, if the verification fails, the program should be returned to the input interface for the user to re-enter.

 

We can also see from the figure that there is not only one interceptor besides an action, so which interceptor should be executed first? Struts2 puts multiple interceptors in one stack. We call it an interceptor stack. On the one hand, the stack can solve the execution sequence problem of the interceptor, and on the other hand, it is convenient to manage the relevant interceptor in a stack.

 

One advantage of struts2 is its configurability. we can select the desired function based on the actual situation. Of course, it also brings us some trouble. Let's take the interceptor as an example. To make the interceptor take effect, we need to configure it first. To configure the interceptor, add the following configurations to struts. xml:

<Package name = "default" extends = "struts-Default">

    <Interceptors>

        <Interceptor name = "timer" class = "..."/>

        <Interceptor name = "logger" class = "..."/>

    </Interceptors>

    <Action name = "login"

       Class = "tutorial. login">

         <Interceptor-ref name = "timer"/>

         <Interceptor-ref name = "logger"/>

          <Result name = "input"> login. jsp </result>

          <Result name = "success"

             Type = "Redirect-action">/secure/home </result>

    </Action>

</Package>

========================================================== ==================================

<Interceptors> and </interceptors> indicate that some interceptors are to be configured, and each of them is an interceptor.

 

<Interceptor name = "timer" class = "..."/>

Interceptor indicates that this is an interceptor. The name attribute is a name for it, and the class attribute indicates its implementation class, which is also the actual position of the Code.

 

The interceptor intercepts an action. Of course, you must add a reference to the action configuration to indicate which interceptor the action will use.

 

<Interceptor-ref name = "timer"/> tells the Struts framework that the login action must use the previous timer interceptor.

 

Some people may say that we didn't configure an interceptor before, but it seems to have been said just now, didn't we also use the interceptor? Indeed, it may be that struts2 developers are afraid that configuration is too troublesome. No one can use it: P, so I have configured some default interceptor and interceptor stacks in advance.

 

A lot of interceptors are defined in the struts-default.xml (the struts-default.xml is in the struts2-core-2.0.6.jar package:

<Interceptor name = "alias" class = "com. opensymphony. xwork. Interceptor. aliasinterceptor"/>

......

Validation and i18n are the verification and internationalization functions we used earlier.

 

There are also many interceptor stacks:

<! -- Basic Stack -->

<Interceptor-stack name = "basicstack">

<Interceptor-ref name = "exception"/>

<Interceptor-ref name = "servlet-config"/>

<Interceptor-ref name = "prepare"/>

<Interceptor-ref name = "static-Params"/>

<Interceptor-ref name = "Params"/>

<Interceptor-ref name = "conversionerror"/>

</Interceptor-stack>

...

<Interceptor-stack name = "defaultstack">

     <Interceptor-ref name = "exception"/>

     <Interceptor-ref name = "alias"/>

     <Interceptor-ref name = "prepare"/>

     <Interceptor-ref name = "servlet-config"/>

     <Interceptor-ref name = "i18n"/>

     <Interceptor-ref name = "chain"/>

     <Interceptor-ref name = "model-driven"/>

     <Interceptor-ref name = "fileupload"/>

     <Interceptor-ref name = "static-Params"/>

     <Interceptor-ref name = "Params"/>

     <Interceptor-ref name = "conversionerror"/>

     <Interceptor-ref name = "validation"/>

     <Interceptor-ref name = "workflow"/>

</Interceptor-stack>

 

<Default-interceptor-ref name = "defaultstack"/>

The final comparison is mainly about the interceptor stack used by the framework by default. That is to say, the interceptor in the defaultstack will take effect by default.

 

This is why validation and i18n are not configured.

 

By the way, interceptor should be an implementation of the AOP (Aspect-Oriented Programming) idea, which indeed brings many advantages to development, on the one hand, a large problem can be divided into multiple small problems for separate processing, on the other hand, action can be used to focus on and handle their own affairs, and relevant functions can be distributed to each interceptor for processing.

 

In struts2 server-side verification, we have discussed in detail the login verification issue. Only users who have obtained the token can access our system. For this reason, we have created a login verification page and corresponding action class, login verification (login. JSP) is responsible for providing users with the opportunity to enter their accounts and passwords. login action is responsible for verifying whether the accounts and passwords entered by users are correct. When the verification is successful, the accounts and passwords are saved to the session, A user obtains a token, which is a valid user.

 

Our goal is to restrict illegal users, that is, users who do not receive the token, and cannot access our system. However, we only did login verification and Token saving, and did not restrict illegal users. Users who are not regular can enter http: // localhost: 8080/success. jsp in the address bar of the browser.

Access our success. jsp page, which of course cannot be tolerated.

 

Before learning the interceptor, we can certainly go to success. add the code to the JSP page to restrict the user name and password from the session. If the user name and password are obtained, the user has logged on to the system. Otherwise, the browser displays login. JSP allows users to log on to the system. There is no problem in this way, which is equivalent to arranging a token checking person at the door of every room. However, if the number of restricted resources in the system is large, such as success. there are a lot of JSP or actions, dozens, and hundreds of times, we have to write such code many times. This is of course a smart one that we cannot tolerate: P

 

Obviously, it is no longer appropriate to let the interceptor do this job. We can add an interceptor so that it can run before these restricted resources are executed. In the interceptor, we check whether the user has logged on to the system. If so, they can access it, otherwise, a login is sent to the user. JSP allows users to log on. In this way, we only need to write the check code once and for all.

 

After understanding the principles, you need to do the following:

1. Write an interceptor to check whether the user logs in.

2. Add the interceptor configuration to let our self-written interceptor take effect.

 

First, complete the first task. open:

Inside struts-2.0.6docsdocsguides.html

Struts-2.0.6docsdocswriting-interceptors.html help.

From this help, we can see that the interceptor must implement the com. opensymphony. xwork2.interceptor. interceptor interface. Based on experience, the init () method should be the method for initializing the Interceptor. You can put some initialization code in it. The destroy () method is opposite to the method. Before the interceptor is destroyed, this gives us the opportunity to do some aftercare.

 

Obviously, the intercept () method is used to add code that actually executes interception. If we do not need initialization or cleanup operations, we can directly inherit from Com. opensymphony. xwork2.interceptor. abstractinterceptor class that overwrites its intercept () method. This method has an actioninvocation parameter, which can be used to obtain session or forward requests.

 

Create a package under SRC: tutorial. interceptor

Create a class logoninterceptor under this package to inherit from abstractinterceptor and overwrite the intercept () method:

 

Package tutorial. interceptor;

Import java. util. Map;

Import org. Apache. struts2.servletactioncontext;

Import com. opensymphony. xwork2.actioncontext;

Import com. opensymphony. xwork2.actioninvocation;

Import com. opensymphony. xwork2.interceptor. abstractinterceptor;

 

Public class logoninterceptor extends actinterceptor {

     Public String intercept (actioninvocation Invocation) throws exception {

         // Get the requested action name

         String  Name = invocation. getinvocationcontext (). getname ();

 

         If (name. Equals ("login ")){

             // If you want to log on, use

             Return invocation. Invoke ();

         } Else {

             // Obtain the session.

             Actioncontext AC = invocation. getinvocationcontext ();

             Map session =  (MAP) AC. Get (servletactioncontext. session );

  

             If (session = NULL ){

                 // If the session is empty, log on to the user.

                 Return "login ";

             } Else {

                 String username = (string) Session. Get ("username ");

                 If (username = NULL ){

                     // The session is not empty, but there is no user information in the session,

                     // Log on to the console

                     Return "login ";

                 } Else {

                     // The user has logged on and is allowed ~

                     Return invocation. Invoke ();

                 }

             }

         }

     }

}

 

Today, there are a lot of content. Next we need to configure this Interceptor:

For how to configure an interceptor to make it work for all actions, see:

Struts-2.0.6docsdocshow-do-we-configure-an-interceptor-to-be-used-with-every-action.html

Modify struts. XML,

1. Custom interceptor

2. Redefine the default interceptor Stack

3. Add a global-results. The user will jump to the login verification page if verification fails.

Complete content of Struts. xml:

<! Doctype struts public

     "-// Apache Software Foundation // DTD struts configuration 2.0 // en"

     Http://struts.apache.org/dtds/struts-2.0.dtd>

<Struts> <! -- Configuration for the default package. -->

<Constant name = "struts. Custom. i18n. Resources" value = "globalmessages"/>

 

<Include file = "struts-validation.xml"/>

<Package name = "default" extends = "struts-Default">

 

   <! -- Custom interceptor -->

   <Interceptors>

    <Interceptor name = "Logon" class = "tutorial. Interceptor. logoninterceptor"/>

    <! -- Custom interceptor Stack -->

    <Interceptor-stack name = "mystack">

     <Interceptor-ref name = "Logon"/>

     <! -- Reference the default interceptor Stack -->

     <Interceptor-ref name = "defaultstack"/>

    </Interceptor-stack>

   </Interceptors>

 

   <! -- Redefinition of the default interceptor Stack -->

   <Default-interceptor-ref name = "mystack"/>

 

   <Global-Results>

    <Result name = "login" type = "Redirect-action"> login! Input. Action </result>

   </Global-Results>

 

       <Action name = "helloworld" class = "tutorial. helloworld">

             <Result>/helloworld. jsp </result>

          </Action>

        

          <Action name = "login" class = "tutorial. login">

             <Result>/success. jsp </result>

             <Result name = "input">/login. jsp </result>

          </Action>

</Package>

</Struts>

 

Save the changes and deploy the project to Tomcat to start Tomcat.

In the address bar of the browser, enter:

HTTP: /localhost: 8080/tutorial/helloworld. Action

The system will automatically go to the login page.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.