酒店道路通车公示:Apache Struts - Key Technologies Primer struts学习前得基础

来源:百度文库 编辑:九乡新闻网 时间:2024/07/14 02:16:27

Key Technologies Primer

"The time has come," the Walrus said, "To talk of many things:Of shoes -- and ships -- and sealing-wax -- Of cabbages -- and kings --And why the sea is boiling hot -- And whether pigs have wings."

The Usual Suspects

The framework documentation is written for active webdevelopers and assumes a workingknowledge about how Java web applications are built.Before getting started, you shouldunderstand the basics of several key technologies:

  • HTTP, HTML, and User Agents
  • The HTTP Request/Response Cycle
  • JavaScript, AJAX, and SOAP
  • The Java Language and Application Frameworks
  • JavaBeans
  • Properties Files and ResourceBundles
  • Servlets, Filters and Web Containers
  • JavaServer Pages and JSP Tag Libraries
  • Extensible Markup Language (XML)
  • JAAS
  • Model View Controller

This primer briefly defines each of these technologiesbut does not describe them in detail.For your convenience, links to further information areprovided if you would like to learn more about atechnology.

If you are familiar with Java,but not these technologies,the best overall starting point isThe J2EE Tutorial.The tutorial is also available for download inPDFformat.

If you've created web applications for other platforms, youmay be able to follow alongand visit the other references as needed. The coretechnologies used by the framework arealso used by most other Java web development products, sothe background information will beuseful in any Java project.

If you are not familiar with the Java languagegenerally,then the best starting point isThe Java Tutorial.This overlaps with The J2EE Tutorial in someplaces, but the two work well together.

For more about building Java application in general, seetheNew toJava Center.

HTTP, HTML and User Agents

The World Wide Web was built over the Hypertext TransferProtocol(HTTP)and the Hypertext Markup Language(HTML).A User Agent, like a web browser, uses HTTP to requesta HTML document. The browser then formats and displays thedocument to its user. HTTP is used totransport more than HTML, but HTML is the lingua franca ofthe Web and web applications.

While building web applications, some Java developerswrite their own HTML. Others leave that responsibility tothepage designers.

For more about HTTP, HTML, and User Agents, see:

  • Getting started with HTML by Dave Raggett
  • HTTP Overview in The J2EE Tutorial.
  • HTTP/1.1 Specification
  • HTTP Basic and Digest Authentication Specification
  • State Management Mechanism Specification (Cookies)

The HTTP Request/Response cycle

A very important part of HTTP for the web developer is therequest/response cycle. To use HTTPyou have to make a request. A HTTP server, like a webserver, is then obliged to respond. When youbuild your web application, you design it to react to aHTTP request by returning a HTTP response.Frameworks abstract much of these nuts and bolts, but itis important to understandwhat is happening behind the scenes.

If you are not familiar with the HTTP request/responsecycle, westronglyrecommend theHTTP Overviewin The J2EE Tutorial.

JavaScript, AJAX, and SOAP

A problem with the HTTP request/response cycle is thatit does not promote an interactive user interface.Web developers often resort to scripting language,like JavaScript, to make web applications moreinteresting.

An advanced usage of JavaScript, called AJAX, canhelp developers create web applications that are asinteractive and responsive as desktop applications.

For more about JavaScript and AJAX, see

  • Wikipedia - JavaScript
  • Ajax: A New Approach to Web Applications
  • Wikipedia - AJAX

Another technology that can enhance the HTTPrequest/response cycle is SOAP.Using SOAP, an application can access data and invokebusiness logic on another server using HTTP as transferlayer.Using AJAX and SOAP together is becoming a popular way forpage to submit finely-grained requests directly to aremote server,while still retaining a separation of concerns beween thethe business logic and the page markup,.

For more about SOAP, see

  • Wikipedia - SOAP

The Java Language and Application Frameworks

The framework is written in the popular and versatileJava programming language.Java is an object-orientated language, and the frameworkmakes good use of manyobject-orientated techniques. In addition, Java nativelysupports theconcept ofthreads,which allows more than one task to beperformed at the same time. A good understanding of Java,and especiallyobject-orientated programming (OOP) and threading, willhelpyou get the most out of the framework and this User Guide.

For more about Java and threads, see

  • Learning the Java Language in the Java Tutorial
  • Threads: Doing Two or More Tasks At Once in the Java Language Tutorial

Even if you have worked with Java and OOP before, it canalso help to be aware of theprogramming challenges specific to creating and usingapplication frameworks. For more about applicationframeworks, see the classic white papers

  • Designing Reusable Classes by Ralph E. Johnson & Brian Foote
  • Object-Oriented Application Frameworks by Mohamed Fayad and Douglas C. Schmidt

These papers can be especially helpful if you arefact-finding or reviewing server-sideframeworks.

JavaBeans

Like many Java applications, most of the framework objectsare designed asJavaBeans.Following the JavaBean design patterns makesthe framework's classes easier to use -- both by Javadevelopers and by Java development tools.

Although JavaBeans were first created for visual elements,these object design patterns have been found tobe useful as the basis for any reusable component, likethose used by the framework.

For more about JavaBeans, see:

  • The JavaBeans Component Architecture Documentation page at java.sun.com, including a link to download the JavaBeans 1.01 Specification
  • The JavaBeans Trail in the Java Tutorial
  • JavaBeans Components in JSP Pages in The J2EE Tutorial

Reflection and Introspection

Reflection is the process of determining which memberfields and methods are available on an object.Introspection is a specialized form of reflection used bythe JavaBean API.Using Introspection, we can determine which methods of aJavaBean are intended to be accessed by other objects.(The getters and the setters, for example.)

The framework uses Introspection to convert HTTPparameters into JavaBean properties and to populate HTMLfields from JavaBean properties.This technique makes it easy to "roundtrip" propertiesbetween HTML forms and JavaBeans.

For more about Reflection and Introspection, see

  • The Reflection Trail
  • Chapter 8 of the JavaBeans API Specification

Maps

JavaBeans store data as properties and may act on thatdata through other methods.JavaBeans are flexible and powerful objects but are notthe only object that programmers use to store data.Another popular object is the Map[java.util.Map].A Map is a simple collection of name and value pairs.Maps are often used "behind the scenes" as a flexible wayto store dynamic data.

Properties Files and ResourceBundles

Java applications, including web applications, are oftenconfigured usingPropertiesfiles. Properties files are the basis for theResourceBundlesthat the framework uses to provide message resourcesto an application.

For more about Properties files, see:

  • Using Properties to Manage Program Attributes in The Java Tutorial

Java ResourceBundles use one or more Properties files toprovide internationalized messagesto users based theirLocale.Support for localizing an application was built into theframework from the ground-up.

For more about localization and ResourceBundles, see

  • About the ResourceBundle Class in the Java Tutorial

Servlets, Filters, and Web Containers

Since Java is an object-orientated language, theJava Servletplatform strives to cast HTTP into an object-orientatedform.This strategy makes it easier for Java developers toconcentrate on what they need their application to do --rather than the mechanics of HTTP.

HTTP provides a standard mechanism for extending serverscalled the Common Gateway Interface, or CGI.The server can pass a request to a CGI-aware program, andthe program will pass back a response.Likewise, a Java-aware server can pass a request to aservlet container.The container can fulfill the request or it can pass therequest back to the HTTP server.The container decides whether it can handle the request bychecking its list of servlets.If there is a servlet registered for the request, thecontainer passes the request to the servlet.

When a request comes in, the container checks to see ifthere is a servlet registered for that request.If there is a match,the request is given to the servlet.If not, the request is returned to the HTTP server.

It's the container's job to manages the servlet lifecycle.The container creates the servlets, invokes the servlets,and ultimately disposes the servlets.

A servlet is generally a subclass ofjavax.servlet.http.HttpServlet.A servlet must implement four methods, which are invokedby the container as needed:

  • public void init(ServletConfig config) - Called by the servlet container when the servlet instance is first created, and before any request is processed.
  • public void doGet(HttpServletRequest request, HttpServletResponse response) - Called to process a specific request received using the HTTP GET protocol, which generates a corresponding dynamic response.
  • public void doPost(HttpServletRequest request, HttpServletResponse response) - Called to process a specific request received using the HTTP POST protocol, which generates a corresponding dynamic response.
  • public void destroy() - Called by the servlet container when it takes this servlet instance out of service, such as when a web application is being undeployed or when the entire container is being shut down.

The framework provides a ready-to-use servlet for yourapplication[org.apache.struts.action.ActionServlet].As a developer, you can then just write objectsthat the ActionServlet calls when needed.But it is still helpful to understand theservlet essentials,and the role they play in a Java web application.

For more about Java Servlets, see:

  • The Java Servlet Technology page at java.sun.com
  • The Servlet 2.3 and 2.4 Specifications download page at java.sun.com
  • Java Servlet Technology in The J2EE Tutorial.

Servlets and Threads

To boost performance, the container can multi-threadservlets.Only one instance of a particular servlet is created,and each request for that servlet passes through the sameobject.This strategy helps the container make the best use ofavailable resources.The tradeoff is that the servlet'sdoGet()anddoPost()methods must be programmed in athread-safemanner.

For more about servlets and thread-safety, see:

  • Controlling Concurrent Access to Shared Resources in The J2EE Tutorial.

Servlet Context

TheServletContextinterface[javax.servlet.ServletContext]defines a servlet's view ofthe web application within which the servlet is running.It isaccessible in a servlet via thegetServletConfig()method,and in a JSP page as theapplicationimplicit variable.Servlet contexts provide several APIs that are very usefulin building web applications:

  • Access To Web Application Resources - A servlet can access static resource files within the web application using the getResource() and getResourceAsStream() methods.
  • Servlet Context Attributes - The context makes available a storage place for Java objects, identified by string-valued keys. These attributes are global to the entire web application, and may be accessed by a servlet using the getAttribute(), getAttributeNames(), removeAttribute(), and setAttribute() methods. From a JSP page, servlet context attributes are also known as "application scope beans".

For more about the servlet context, see:

  • Accessing the Web Context in The J2EE Tutorial.

Servlet Request

Each request processed by a servlet is represented by aJavainterface, normally aHttpServletRequest[javax.servlet.http.HttpServletRequest].The request interface provides an object-orientedmechanism to accessall of the information that was included in the underlyingHTTP request,including:

  • Cookies - The set of cookies included with this request are available via the getCookies() method.
  • Headers - HTTP headers that were included with the request are accessible by name. You can enumerate the names of all included headers.
  • Parameters - Request parameters, including those from the query string portion of the URL and from the embedded content of the request (POST only) are available by name.
  • Request Characteristics - Many other characteristics of the incoming HTTP request, such as the method used (normally GET or POST) the protocol scheme used ("http" or "https"), and similar values.
  • Request URI Information - The original request URI being processed is available via getRequestURI() . In addition, the constituent parts into which the servlet container parses the request URI (contextPath, servletPath, and pathInfo) are available separately.
  • User Information - If you are using Container Managed Security , you can ask for the username of the authenticated user, retrieve a Principal object representing the current user, and whether the current user is authorized for a specified role.

In addition, servlet requests supportrequest attributes(from JSP, these are "request scope beans"), analogous tothe servletcontext attributes described above. Request attributes areoften usedto communicate state information from a business logicclass thatgenerates it to a view component (such as a JSP page) thatwill usethe information to produce the corresponding response.

The servlet container guarantees that a particular requestwillbe processed by a servlet on a single thread. Therefore,you do notgenerally have to worry about the thread safety of youraccess torequest properties and attributes.

For more about the servlet request, see:

  • Getting Information from Requests in The J2EE Tutorial.

Servlet Response

The primary purpose of a servlet is to process an incomingServlet Request[javax.servlet.http.HttpServletRequest]and convert it into acorresponding response. This is performed by callingappropriatemethods on the servlet response[javax.servlet.http.HttpServletResponse]interface. Available methods let you:

  • Set Headers - You can set HTTP headers that will be included in the response. The most important header is the Content-Type header, which tells your client what kind of information is included in the body of this response. This is typically set to text/html for an HTML page, or text/xml for an XML document.
  • Set Cookies - You can add cookies to the current response.
  • Send Error Responses - You can send an HTTP error status (instead of a usual page of content) using sendError() .
  • Redirect To Another Resource - You can use the sendRedirect() method to redirect the client to some other URL that you specify.

An important principle in using the servlet response APIsis thatany methods you call to manipulate headers or cookiesMUSTbe performed before the first buffer-full ofcontent has been flushed to the client. The reason forthis restrictionis that such information is transmitted at the beginningof the HTTPresponse, so trying things like adding a header after theheaders havealready been sent will not be effective.

When you are using presentation pages in a Model 2application,you will not generally use the servlet response APIsdirectly.In the case of JavaServerPages, the JSP page compilerin your servlet container will convert your page into aservlet.The JSP servlet renders the response, interspersingdynamicinformation where you have interposed JSP custom tags.

Other presentation systems, like Velocity Tools forStruts,may delegate rendering the response to a specializedservlet,but the same pattern holds true.You create a template,and the dynamic response is generated automatically fromthe template.

For more about the servlet response, see:

  • Constructing Responses in The J2EE Tutorial.

Filters

If you are using a servlet container based on version2.3or later of the Servlet Specification (such asTomcat 4.x), you can take advantage of the new Filter APIs[javax.servlet.Filter]thatlet you compose a set of components that will process arequest orresponse. Filters are aggregated into a chain in whicheach filterhas a chance to process the request and response beforeand afterit is processed by subsequent filters (and the servletthat is ultimatelycalled).

Struts 1.2 and earlier require your container to implementversion 2.2 or later of the Servlet Specification,so those versions of the Struts framework do not useFilters internaly. Beginning with Struts 1.3, a containerthat supports version 2.3 or later of the ServletSpecification is required.Struts 2 uses a filter as the base of the controller,instead of a servlet.

For more about filters, see:

  • Filtering Requests and Responses
  • The Essentials of Filters

Sessions

One of the key characteristics of HTTP is that it isstateless.In other words, there is nothing built in toHTTP that identifies a subsequent request from the sameuser as beingrelated to a previous request from that user. This makesbuilding anapplication that wants to engage in a conversation withthe user overseveral requests to be somewhat difficult.

To alleviate this difficulty, the servlet API provides aprogrammaticconcept called asession,represented as an object thatimplements thejavax.servlet.http.HttpSessioninterface.The servlet container will use one of two techniques(cookies orURL rewriting) to ensure that the next request from thesame user willinclude thesession idfor this session, so that stateinformation saved in the session can be associated withmultiplerequests. This state information is stored insessionattributes(in JSP, they are known as "session scope beans").

To avoid occupying resources indefinitely when a user fails tocompletean interaction, sessions have a configurabletimeout interval.If the time gap between two requests exceeds thisinterval, the sessionwill be timed out, and all session attributes removed. Youdefine adefault session timeout in your web application deploymentdescriptor,and you can dynamically change it for a particular sessionby callingthesetMaxInactiveInterval()method.

Unlike requests, you need to be concerned about threadsafety onyour session attributes (the methods these beans provide,not thegetAttribute()andsetAttribute()methodsof the session itself). It is surprisingly easy for thereto bemultiple simultaneous requests from the same user, whichwill thereforeaccess the same session.

Another important consideration is that session attributesoccupymemory in your serverin betweenrequests. This can havean impact on the number of simultaneous users that yourapplication cansupport. If your application requirements include verylarge numbers ofsimultaneous users, you will likely want to minimize youruse ofsession attributes, in an effort to control the overallamount of memoryrequired to support your application.

For more about sessions, see:

  • Maintaining Client State in The J2EE Tutorial
  • javax.servlet.http.HttpSession

Dispatching Requests

The Java Servlet specification extends the HTTPrequest/response cycle by allowing the request to bedispatched,or forwarded, between resources.The framework uses this feature to pass a request throughspecialized components,each handling one aspect of the response.In the normal course, a request may pass through acontroller object, a model object,and finally to a view object as part of a singlerequest/response cycle.

Web Applications

Just as a HTTP server can be used to host several distinctwebsites,a servlet container can be used to host more than one webapplication.The Java servlet platform provides a well-definedmechanism for organizing and deploying web applications.Each application runs in its own namespace so that theycan be developed and deployed separately.A web application can be assembled into a Web ApplicationArchive, or WAR file.The single WAR can be uploaded to the server andautomatically deployed.

Web application deployment descriptor (web.xml)

Most aspects of an application's lifecycle are configuredthrough an XML document called the Web applicationdeployment descriptor.The schema of the descriptor, or web.xml, is given by theJava servlet specification.

Security

One detail that can be configured in the Web applicationdeployment descriptor is container-managed security.Declarative security can be used to protect requests forURIs that match given patterns.Pragmatic security can be used to fine-tune security makeauthorization decisions based on the time of day,the parameters of a call, or the internal state of a Webcomponent.It can also be used to restrict authentication based oninformation in a database.

For more about security, see:

  • J2EE Blueprints: Security
  • SecurityFilter
  • Acegi Security
  • The Struts SSL Extension for HTTP/HTTPS switching

JavaServer Pages, JSP Tag Libraries, and JavaServer Faces

JavaServer Pages(JSPs) are"inside-out servlets" that make it easier to create andmaintain dynamic web pages. Insteadof putting what you want to write to the HTTP responseinside of a Javaprintstatement, everything in a JavaServer Page is written tothe response,exceptwhat isplaced within special Java statements.

WithJavaServer Pagesyou can start by writing the page in standard HTML andthen add thedynamic features using statements in the Java language orby usingJSP tags.The framework distribution includes several JSP tagsthat make it easy to access the framework'sfeatures from a JavaServer Page.

For more about JavaServer Pages and Custom JSP TagLibraries see

  • The JavaServer Pages Technology page at java.sun.com
  • The JSP 1.2 and 2.0 Specifications download page at java.sun.com
  • JavaServer Pages Technology in The J2EE Tutorial
  • Custom Tags in JSP Pages in The J2EE Tutorial

Many times, JSP tags work hand-in-hand with JavaBeans. Theapplication sends a JavaBean tothe JSP, and the JSP tag uses the bean to customize thepage for the instant user. For more, seeJavaBeans Components in JSP Pagesin The J2EE Tutorial.

The framework also works well with theJavaServer Pages Standard Tag Library(JSTL) and taglibs from other sources, likeJSP Tags,Jakarta Taglibs,StrutsLayout,andDisplay Tags.

One of the components available with the framework isStruts-EL.This taglib is specifically designed to work well withJSTL.In particular, it uses the same " language"engine for evaluating tag attribute values as JSTL.This is in contrast to the original Struts tag library,which can only use "rtexprvalue"s (runtime scriptlets) for dynamic attribute values.

There are also toolkits available that make the frameworkeasy to use withXSLTandVelocity Templates.

The newest star on the Java horizon isJavaServer Faces technology.JSF aims to simplify building user interfaces for JavaServerapplications, both for the web and for the desktop.

For an open source implementation of JSF, visit oursibling project, Apache MyFaces.

For more about JSTL and JavaServer Faces see

  • Practical JSTL, Part 1 by Sue Spielman
  • JSF Central - JavaServer Faces resources.
  • JavaServer Faces Resources - James Holmes dot Com.
  • Apache MyFaces - An open source implementation of the JSF specification.

Extensible Markup Language (XML)

The features provided by the framework rely on a number ofobjects that areusually deployed using a configuration file written inExtensible MarkupLanguage.XML is also used toconfigure Java web applications; so, this is yet anotherfamiliar approach.

For more about how XML is used with Java applicationsgenerally, see theJava API for XML Processing Tutorial.While the framework makes good use of this API internally,it is not something most developers would usewhen writing their own applications with the framework.

Descriptors

When Java applications use XML configuration files,the elements are most often used asdescriptors.The application does not use the XML elements directly.The elements are used to create and configure (or deploy)Java objects.

The Java Servlet platform uses an XML configuration fileto deploy servlets (among other things).Likewise, The framework uses an XML configuration file todeploy objects.

JAAS

While the framework can work with any approach to userauthentication and authorization, version 1.1 and lateroffersdirect support for the standard Java Authentication andAuthorization Service (JAAS).You can now specify security roles on an action-by-actionbasis.

For more about JAAS, see the Sun Developer Networkproductpage.

A popular extension for handling security in a Java webapplication, including a framework application,isSecurityFilter .

Model View Controller (MVC)

Web applications based on JavaServer Pages sometimescommingle database code, page design code, and control flowcode. In practice, we find that unless these concerns areseparated, larger applications become difficult to maintain.

One way to separate concerns in a software application isto use a Model-View-Controller (MVC) architecture. TheModel represents the business or database code, the Viewrepresents the page design code, and the Controllerrepresents the navigational code.

The term "MVC" originated with the SmallTalkModel-View-Controller framework.In Smalltalk MVC, the View updates itself from the Model, viathe "Observer" pattern. The original MVC pattern is like aclosed loop: The View talks to the Controller, which talks tothe Model, which talks to the View.

But, a direct link between the Model and the View is notpractical for web applications, and we modify the classic MVCarrangement so that it would look less like a loop and morelike a horseshoe with the controller in the middle.

In the MVC/Model 2 design pattern, application flow is mediatedby a central Controller. The Controller delegates requests -in our case, HTTP requests - to an appropriate handler. Thehandlers are tied to a Model, and each handler acts as anadapter between the request and the Model. The Modelrepresents, or encapsulates, an application's business logic orstate. Control is usually then forwarded back through theController to the appropriate View. The forwarding can bedetermined by consulting a set of mappings, usually loaded from adatabase or configuration file. This provides a loose couplingbetween the View and Model, which can make applicationssignificantly easier to create and maintain.

While MVC is a convenient paradigm, many workers find thatapplcations may utilize more than three layers.For example, within the Model, there is often distinct businesslogic and data access layers.

The framework provides the control layer for a Model 2 webapplications.Developers can use this layer with other standardtechnologies to build the business, data access, andpresentation layers.

For more about MVC, see

  • Web-Tier Application Framework Design (Sun J2EE Blueprints)
  • Smalltalk MVC framework.
  • Wikipedia - MVC

Business Logic Frameworks

Most teams still roll their own business logic layer usingplain old JavaBeans (POJOs).Though, business layer frameworks are beginning to emerge,and now include:

  • Commons Chain of Responsiblity
  • Spring
  • XWork

Data Access Frameworks

Most often, the business layer is seen to be distinct fromthe data access layer.Some teams roll their own data access objects (DAOs),but more and more teams are turning to one of the manydata access frameworks.Some popular data access frameworks include:

  • Cayenne
  • Enterprise Java Beans
  • Hibernate
  • iBATIS
  • JDBC
  • Object Relational Bridge

View Frameworks

Aside from Java Server Pages, there are several otherpresentation technologies available to Java web applications.

  • Freemarker
  • iText (PDF)
  • JasperReports
  • Velocity
  • XSLT