Struts 2 Learning (i) Struts 2 environment construction and sample programming

Source: Internet
Author: User

before you learn Struts2, let's look at what is Struts2: Struts2 is a Web application framework based on the MVC design pattern, which essentially corresponds to a servlet, in the MVC design pattern, Struts2 as a controller to establish the data interaction between the model and the view. Struts 2 is the next generation of struts and is the new Struts 2 framework that was combined with struts 1 and webwork technology. Its new Struts 2 architecture differs greatly from the architecture of struts 1. Struts 2 takes the webwork as the core and uses the interceptor mechanism to handle the user's request, which also allows the business logic controller to completely disengage from the ServletAPI, so struts 2 can be understood as the WebWork update product. ---------from Baidu Encyclopedia
the difference between Struts2 and Struts1:

Struts2 is a lot simpler and more powerful than struts1, and we can see it in several ways:

    • In terms of architecture :Struts2 uses interceptors to come out of the request, allowing separation from the business logic controller and SERVLET-API, avoiding intrusive , and struts1.x in action obviously invaded the SERVLET-API.
    • from thread safety analysis :struts2.x is thread-safe, each object produces an instance, avoids thread-safety issues, and struts1.x is single-threaded in action.
    • performance :The struts2.x test can be detached from the Web container, and struts1.x relies on SERVLET-API, and the test relies on the Web container.
    • Request Parameter Package comparison :struts2.x uses Modeldriven mode so that we directly encapsulate the model object without having to inherit any struts2 base class, avoiding intrusion.
    • Tag Advantages : the tag library can almost completely replace the JSTL tag library, and struts2.x supports powerful OGNL expressions.

Of course, compared to struts2 and Struts1, in the file upload, data verification and other aspects also convenient a lot. There's no talking about it here.
build STRUTS2 development environment
STRUTS2 Official website: HTTPS://STRUTS.APACHE.ORG/STRUTS2 related jar package: http://struts.apache.org/ download.cgi using Eclipse can choose to download all the jar package files and import them into the project so that the preparation is done. The next demonstration is to use idea to build the STRUTS2 development environment. First, you start by opening idea and choosing a new project to select the Struts2 in Java EE. Note that if there is no LIB package locally, it will be downloaded automatically from the Internet, or you can choose to set it later. Select Next
Click Finish to

Dependent files are automatically downloaded from the Web waiting for dependent files to be downloaded, the project is completed
Where: The contents of the auto-generated struts.xml file are:
<?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></struts>
Introduce the main tags: the content of the automatically generated Web. xml file is:
<?xml version= "1.0" encoding= "UTF-8"? ><web-app xmlns= "Http://xmlns.jcp.org/xml/ns/javaee"        xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"        xsi:schemalocation= "HTTP://XMLNS.JCP.ORG/XML/NS/JAVAEE/HTTP// Xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd "        version=" 3.1 ">    <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>

Struts2 Hello World Program Creation
Let's start with what a demo program does: We write the login interface in a form, but unlike the previous login interface, we use STRUTS2 to accomplish these functions. First write the corresponding JSP interface under the Web folder index.jsp
<%--  Created by IntelliJ idea.  User:icarus  DATE:2016/7/2 time:12:16 To change this  template use  File | Settings | File templates.--%><%@ page contenttype= "Text/html;charset=utf-8" language= "java"%><%    String Path = Request.getcontextpath ();    String basepath = request.getscheme () + "://" +request.getservername () + ":" +request.getserverport () +path+ "/";%> 

Login Success Interface success.jsp
<%--  Created by IntelliJ idea.  User:icarus  DATE:2016/7/2 time:12:14 To change this  template use  File | Settings | File templates.--%><%@ page contenttype= "Text/html;charset=utf-8" language= "java"%>
Login Failure Interface fail.jsp
<%--  Created by IntelliJ idea.  User:icarus  DATE:2016/7/2 time:12:14 To change this  template use  File | Settings | File templates.--%><%@ page contenttype= "Text/html;charset=utf-8" language= "java"%>
Next is the corresponding action function to write Loginaction.java
Package cn.lovepi.chapter01.action;/*** Created by Icarus on 2016/7/2.* creating form data validation Classes */public class Loginaction {//    form Properties    private String userName;    Private String PassWord;    /**    * Perform form validation operation    * @return Validation status */Public    String execute () {        if (username.equals ("Wangxin") & &password.equals ("123456")) {            return "success";        } else {            return "fail";        }    }    Public String GetUserName () {        return userName;    }    public void Setusername (String userName) {        this.username = userName;    }    Public String GetPassword () {        return passWord;    }    public void SetPassword (String passWord) {        This.password = PassWord;    }}

The next step is the core of Struts2, which is struts.xml configuration file writing
<?xml version= "1.0" encoding= "UTF-8"? ><! DOCTYPE struts Public "-//apache software foundation//dtd struts Configuration 2.3//en" "Http://struts.apach E.org/dtds/struts-2.3.dtd "><!--configuration file root element--><struts> <!--bean tag for creating a Java Bean instance--<!-- Constant label for Struts2 default behavior label-<!--package label, which is used to differentiate between different request file labels, such as requests from the front and back of the website, and <!--include tags, to introduce other XML configuration file-<!--Next details the main usage of constant-<!--Configure the Web default encoding set, which is equivalent to httpservletrequest.setcharacterencoding usage but This setting is equivalent to writing in the filter, and all subsequent accesses do not need to be manually specified in the encoding format--<constant name= "struts.i18n.encoding" value= "UTF-8"/> <!-- The default Struts2 request suffix is. Action if we do not configure this property, Struts2 then intercepts the request with the suffix action, and after configuring it intercepts the action/do suffix request--<constant name= " Struts.action.extension "value=" Action,do "/> <!--set whether the browser caches static content, which is true by default and is recommended to close during our development phase, preventing changes from being tested to no--and <con Stant name= "Struts.serve.static.browserCache" value= "false"/> <!--struts2 configuration file re-modified, the system will automatically reload the configuration file, the default is FAlse. The development phase is recommended to be configured as true for easy development.    --<constant name= "Struts.configuration.xml.reload" value= "true"/> <!--development mode, you can print out more detailed error messages-- <constant name= "Struts.devmode" value= "true"/> <!--default View theme--<constant name= "Struts.ui.theme" value= "        Simple "/> <!--the main usage of the package is described in detail--<!--name: The packet name, which is called or inherited by another package. Namespace: namespace, optional, URL connection must be added to/new/action.*** extends: Inherit, all packages in Struts2 inherit from Struts-default package by default, and <package name= "t        Est "namespace="/new "extends=" Struts-default "> <!--action is equivalent to the concept of a previous servlet, which corresponds to a request's name as the requested URL address. That is to say we want to approach the action we configured, the access path is: localhost:8080/Project name/package (namespace)/login.do (as configured above)--<action name = "Login" class= "cn.lovepi.chapter01.action.LoginAction" > <!--configuration returns the corresponding jump page for the result--<result NA Me= "Success" >/chapter01/success.jsp</result> <result name= "fail" >/chapter01/fail.jsp</result&        Gt </action> </pAckage></struts> 

Publish the program to Tomcat to see the results of the run
You can see that you only need to configure the Struts.xml file instead of writing the servlet as before to forward requests to the corresponding interface. Greatly reduces the coupling degree between programs and facilitates development. So we're going to analyze the flow of the program in this case.
First, we introduce the process of the HTTP request flow:
1. You can see that an HTTP request is first processed by Web. XML and is first intercepted by the filter in Web. 2. The request is forwarded to Struts.xml by the default filter set by the STRUTS2. We configured the relevant pre-interceptor in Struts.xml, then the pre-intercept Will process the requested request (for example, the. Do request and the default. Action request) 4. The request is then forwarded to the corresponding action class according to the URL of the set, which is logically processed in the action class and returns a string flag of 5. If the corresponding post-interceptor is configured, it will go to the rear stop The business processing logic of the cutter. 6. Next Struts.xml will jump to the corresponding result interface based on the returned string. 7. Then display the desired interface to the user.
And what about the data flow in the example above us, then we'll take a look at
In this way, we have completed a simple STRUTS2 demo program.

Struts 2 Learning (i) Struts 2 environment construction and sample programming

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.