Java-Zhang Kan-Struts2 -- HelloWorld

Source: Internet
Author: User

Struts 2 is an elegant, extensible framework for creating enterprise-ready Java web applications. the framework is designed to streamline the full development cycle, from building, to deploying, to maintaining applications over time. apache Struts 2 was originally known as WebWork 2. after working independently for several years, the WebWork and Struts communit Ies joined forces to create Struts2. This new version of Struts is simpler to use and closer to how Struts was always meant to be. apache Struts2 is an excellent and scalable WEB framework for enterprise-level applications. It aims to fully streamline the development cycle of applications, this reduces the time it takes to create, publish, and wait for the application. Apache Struts2 was originally the world-famous Webwork2. After years of development, the Struts and WebWork communities decided to merge into one, that is, today's Struts2. Struts is a Model 2-based MVC framework that provides a well-structured and rigorous implementation for the WEB layer of the application. Struts developed earlier, and the early version of Struts1.X has become familiar to many J2EE programmers. After years of development, this team has become larger and larger, and many enterprise-level applications are developed based on Struts. Struts2 and Struts1.X cannot be put together for comparison. Although they all implement the MVC Architecture Pattern, they are completely different in nature. The predecessor of Struts2 is WebWork. Its implementation methods and functions are superior to those of Struts1.X. However, Struts is the most advanced, and many applications are based on Struts. Its vitality and popularity make WebWork fall under the storm. With the influx of new ideas and new architectures, especially web, Struts1.x is obviously unable to keep up with the ever-changing changes. In many applications, struts2.0. It can be said that Struts2.0 is changing. To a large extent, Struts2.0 cannot avoid speculation. However, leveraging Struts's reputation and WebWork to build a good framework, the two complement each other. It is indeed a golden combination and an excellent propaganda method. When I write this article, I can download the latest version 2.1.0. However, his charm has already become a tip, and it should have a bright future. New Features of Struts2 if readers are familiar with Struts1.X, they will find that Struts2 has changed significantly compared with Struts1.X: Action class: • Struts1 requires the Action class to inherit an abstract base class. A common problem with Struts1 is the use of abstract class programming rather than interfaces. • The Struts 2 Action class can implement an Action interface or other interfaces to make optional and customized services possible. Struts2 provides an ActionSupport base class to implement common interfaces. The Action interface is not required. Any POJO object with the execute identifier can be used as the Action object of Struts2. Thread mode: • Struts1 Action is a singleton mode and must be thread-safe, because only one instance of Action can process all requests. The Singleton policy limits what Struts1 actions can do and requires caution during development. Action resources must be thread-safe or synchronized. • The Struts2 Action object generates an instance for each request, so there is no thread security problem. (In fact, the servlet container generates many discarded objects for each request without causing performance and garbage collection issues.) Servlet dependency: • Struts1 Action depends on the Servlet API, when an Action is called, HttpServletRequest and HttpServletResponse are passed to the execute method. • Struts 2 Action does not depend on the container, allowing the Action to be tested independently from the container. If necessary, Struts2 Action can still access the initial request and response. However, other elements reduce or eliminate the need to directly access HttpServetRequest and HttpServletResponse. Testability: • A major problem in testing Struts1 Action is that the execute method exposes the servlet API (which makes the test dependent on the container ). A third-party extension, Struts TestCase, provides a set of Struts1 simulated objects for testing ). • Struts 2 Action can be tested through initialization, setting attributes, and calling methods. "dependency injection" also makes testing easier. Capture input: • Struts1 uses the ActionForm object to capture input. All actionforms must inherit a base class. Because other JavaBean cannot be used as an ActionForm, developers often create redundant class capture inputs. Dynamic beans (DynaBeans) can be used as an option to create a traditional ActionForm. However, developers may re-describe (create) the existing JavaBean (which will still lead to redundant javabean ). • Struts 2 directly uses the Action attribute as the INPUT attribute, eliminating the need for the second input object. The INPUT attribute may be a rich object type with its own (sub) attribute. The Action attribute can be accessed through taglibs on the web page. Struts2 also supports the ActionForm mode. Rich object type, including business objects, which can be used as input/output objects. This ModelDriven feature simplifies taglib's reference to POJO input objects. Expression Language: • Struts1 integrates JSTL, so jstl el is used. This kind of EL has basic object graph traversal, but the support for set and index attributes is weak. • Struts2 can use JSTL, but also supports a stronger and more flexible Expression Language-"Object Graph Notation Language" (OGNL ). binding value to the page (view): • Struts 1 binds the object to the page using the standard JSP mechanism to access. • Struts 2 uses the "ValueStack" technology to enable taglib to access values without binding your page (view) and objects. The ValueStack policy allows you to reuse a page (view) through a series of attributes with the same name but different types ). Type conversion: • The Struts 1 ActionForm attribute is usually of the String type. Struts1 uses Commons-Beanutils for type conversion. One converter for each class is not configurable for each instance. • Struts2 uses OGNL for type conversion. Provides Converters for basic and common objects. Validation: • Struts 1 supports manual verification in the validate method of ActionForm, or verification through Commons Validator extension. The same class may have different verification content, but it cannot verify the child object. • Struts2 supports verification through the validate method and XWork verification framework. The XWork verification framework uses the checksum content validation defined for the attribute class type to support control the execution of the chain checksum subattribute Action: • Struts1 supports a separate Request Processors (lifecycle) for each module ), however, all actions in the module must share the same lifecycle. • Struts2 supports creating different lifecycles for each Action through Interceptor Stacks. The stack can be used with different actions as needed. Note: The above information is collected from the Internet. Source: Struts development team. Translation: tianxinet (fat monkey ). [Html] view plaincopy <filter> <filter-name> struts2 </filter-name> <filter-class> org. apache. struts2.dispatcher. filterDispatcher </filter-class> </filter> <filter-mapping> <filter-name> struts2 </filter-name> <url-pattern>/* </url-pattern> </filter-mapping> note: in Sturts1.X, this line is completed by the Servlet. 8. Create the com. lizanhong. action package and create the HelloWorldAction class in the package. This class inherits from com. opensymphony. xwork2.ActionSupport. Theoretically, Action can not inherit any class or implement any interface to enhance the testability of the program, which is also different from Struts1.X. However, inheriting from ActionSupport can reduce the coding workload. In ActionSupport, the method execute () is defined. When a user sends a request to this Action, it is called automatically. The program code is as follows: Code List 2: HelloWorldAction. java [java] view plaincopypackage com. lizanhong. action; import com. opensymphony. xwork2.ActionSupport; publicclass HelloWorldAction extends ActionSupport {@ Override public String execute () throws Exception {System. out. println ("Action is executed. "); ReturnSUCCESS;} Note: ActionSupport is a class provided by Struts2. Its functions are similar to the Action class in Struts1.x. This class encapsulates several useful functions, such as getText (): obtain international messages from resource files. AddFieldError (): adds error messages when verification input is not passed. It supports internationalization. Execute (): This method is generally overwritten. This method is called when the client sends a request to the Action. To sum up, this type mainly provides support for error messages and international support. Create the struts. xml file in the engineering path, which is the configuration file of Struts2, similar to the struts-config.xml in Struts1.x, you can configure components such as Action, Bean, Interceptor in the struts. xml file. Code List 3: struts. xml [html] view plaincopy <! DOCTYPE struts PUBLIC "-// Apache Software Foundation // DTD Struts Configuration 2.0 // EN" ""> <struts> <include file = "struts-default.xml"> </include> <package name = "a" extends = "struts-default"> <action name = "helloworld" class = "com. lizanhong. action. helloWorldAction "> <result>/result. jsp </result> </action> </package> </struts> note: the WEB application class path is the WEB-INF/classes directory, In Eclipse, files created under the src directory are automatically copied to the WEB-INF/classes directory after they are finally published. Many labels are involved in code listing 3. The following is a simple explanation: the label Name Description include contains other xml files. In the example, this means struts. xml can access components that are defined in struts-default.xml files. This element allows Struts2 to define multiple configuration files and "divide and conquer ". Note that any struts2 configuration file should have the same format as struts. xml, including doctype, and can be placed anywhere in the class path. The package is an Action group or an intercept group. Name: name. It is required and the name is customized. It is not required. Facilitate other package references. Extends: the package can inherit from other packages, that is, the value of this attribute is the name of another package. In the example, extends = "struts-default" is inherited from the struts-default.xml. Action defines Action. The name attribute is the name used for access, and the class attribute is the class name of Action. Result defines the page navigation based on the return value of Action. The predefined return values of Action are: String SUCCESS = "success"; String NONE = "none"; String ERROR = "error"; String INPUT = "input "; string LOGIN = "login"; for example, you want to go to OK when the Action returns SUCCESS. the jsp page can be written as follows: <result name = "success"> OK. jsp </result> where the default name is success. 9. result. jsp is a very simple jsp page that outputs "world, hello ". Code list 4: result. jsp [html] view plaincopy <% @ page language = "java" import = "java. util. * "pageEncoding =" UTF-8 "%> <% String path = request. getContextPath (); String basePath = request. getScheme () + ": //" + request. getServerName () + ":" + request. getServerPort () + path + "/"; %> <! Doctype html public "-// W3C // dtd html 4.01 Transitional // EN">

Related Article

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