STRUTS2 Basic Knowledge Learning

Source: Internet
Author: User

JAVA Web Development History

In earlier Java Web applications, JSP files were responsible for producing web pages, controlling the flow to the next page, and responsible for business logic,
This poses a number of problems for Web development:
HTML and Java are coupled together, the JSP file must be written by the Web designer and Java developer.
Disadvantages:
Poor readability
Difficult to debug
Not conducive to maintenance, changing business logic or data may design multiple related pages

It is now usually divided into four layers:
Presentation Layer (Jsp,html page)
Business Logic Layer (JavaBean)
Persistence layer (Spring for persistence)
Database tier

Benefits of Layering:
Scalability
Maintainability
Scalability
Re-usability
Manageability

Stratification also embodies the idea of divide and conquer.

Web. XML welcome tag specifies access to home page
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>


The difference between the Pageencoding and contenttype two properties of a JSP page:

Pageencoding is the encoding of the JSP file itself

ContentType CharSet refers to the content encoding when the server is sent to the client


STRUTS2 Core Pack

Common-logging-1.0.4.jar STRUTS2 Framework's Log package
Freemarker-2.3.8.jar UI label templates for Struts2
Ognl-2.6.11.jar Object Map Navigation language pack
Core class Library of the Strut2-core-2.0.11.jar struts framework
Xwork-2.0.4.jar Xwork class Library, STRUTS2 based on this build

The ultimate goal of Struts 2 is to decouple page jumps and module processing, which can be configured.

Frequently asked questions about STRUTS2:

1. Tomcat Settings
Window->references->tomcat

2. Default JDK settings, the selected JRE will be added to the newly created Java Project build path

Window->references->java->installed JREs

3. Project name is too long

Right-click the project, copy qulified name

Common configuration steps for 4.Struts

1.web.xml Configuring the filter class for struts
The 2.struts.xml is copied to the SRC directory. To configure the page jump for action
3.lib package copied to Web-inf\lib


5. Configuration in Struts.xml, after modifying the Struts.xml file, do not restart Tomcat to take effect immediately
<constant name= "Struts.devmode" value= "true"/>

6. How to quickly view the source of Lib package in eclipse?

In referenced libraries, right-click the Lib package, select Java Source attachement,

C:/users/anker/desktop/java Learning/struts2/struts-2.1.6-all/struts-2.1.6/src/core/src/main/java

7. Set up the Lib package documentation

In referenced libraries, right-click the Lib package and select Java location
File:/c:/users/anker/desktop/java Learning/struts2/struts-2.1.6-all/struts-2.1.6/docs/struts2-core/apidocs/

8. Question:
After the Copy project, when the Tomcat deployment was made, an error occurred that the item already existed.

Answer:
You need to modify the context root, right-click the project, select Properties->myeclipse->web, modify Web context-root

Introduction to 9.STRUTS2 Configuration


<package name= "Default" namespace= "/path" extends= "Struts-default" >
<action name= "path" class= "Com.bjsxt.struts2.front.action.StudentAction" >
<result name= "SUCCESS" >
/indexaction.jsp
</result>
</action>
</package>

Package is mainly used to solve the problem of duplicate action
Namespace: The page access path, equivalent to Namespace= "" or namespace= "/", means that the action tag matches the access path on the failed match in all other Namespace.
Extends: Secondary Contracting
Action: Access to the module processing, can be followed later. Action
Class: The actual class that the module handles, if omitted, accesses the Actionsupport class in struts, there is an Execute method, which returns the success string.
Result: Accept the return processing of the module processing
Name: The JSP page is accessed based on the returned string, and the default is the "success" string if not filled in.


Global result configuration: Sets the result set that is common to all action under the current namespace
<global-results>
<result name= "MainPage" >login.jsp</result>
<global-results>

The default action, when a matching action is not found in the currently contained namespace, the action accessed
<default-action-ref name= "index" > </default-action-ref>
<action name= "Index" >
<result>/default.jsp</result>
</action>

Module contains <include file= "login.xml"/>,login.xml file content consistent with Struts.xml structure

Three ways to implement the 10.Action class

1. General class, implement a method that returns a string.
2. Implementing the Action Interface
3. Integration from Actionsupport, the advantage is that you can directly use the Struts2 package good method. Recommended

When the action class is accessed, the object is automatically created by the STRUT2 framework. Each time a user accesses, a different action object is generated.
At Struts1, this object has only one. There are security implications for multiple thread access.

Method invocation of the 11.Action class

1. Without specifying a method, the Execute method of the action class is accessed by default.
2. Call through Xx!method.action, XX is the action module, method is the way in the action class
3. In the Action tab, add the Method= "Add" string, which is the Add method that is accessed when accessing this action module.

How does the 12.Action class accept parameters?


1. Pass through the URL. The parameters passed in the action class need to define the corresponding member variables.
For example

Http://localhost:8080/Struts2_0700_ActionAttrParamInput/path/path!GetMessage.action?name=Anker&age=18


This accesses the GetMessage method under the action class of path and passes the anker,18 to the member variable name of the action class and the age

2. Accept parameters by Domain model (recommended)

The corresponding entity class is created, and the entity class contains the corresponding member variables. and implement the Get,set method of this object in the action class.

Invocation mode
Http://localhost:8080/Struts2_0700_ActionAttrParamInput/path/path!GetMessage.action?user.name=Anker&user.age=18

Note: If you do not assign a property to an entity class during the call to action, the entity object is not created.

3.ModelDriven Model Driven

Implement the Modeldriven interface to assign values to object member variables by Getmodel the object that returns the entity class.

13. How to use wildcard characters in Struts.xml

The use of wildcards can greatly simplify our configuration. However, it is important to follow the "contract better than the configuration" principle


Use the * number in the ActionName, followed by the class,method or the result tag, you can use {1} to configure the first * number corresponding to the string,
{2} configures a string corresponding to the second * number, and so on
<package name= "Actions" extends= "Struts-default" namespace= "/actions" >
<action name= "student*" class= "com.bjsxt.struts2.action.StudentAction" method= "{1}" >
<result>/Student{1}_succes.jsp</result>
</action>

<action name= "*_*" class= "com.bjsxt.struts2.action. {1} Action ">
<result>/{1}_{2}_success.jsp</result>
</action>
</package>

14. Question: How to resolve the default encoding for a page

Answer:
Windows->preferences-> JSP
Encoding transposition Chinese, national standard, so that the default encoding format is GB18030. The page can be written in Chinese.

Absolute path problem for 15.JSP pages

The path problem in Struts2 is determined by the path of the action rather than the JSP path, so try not to use a relative path

A JSP page generated by MyEclipse that typically includes the following sections:
<%
String path = Request.getcontextpath ();
String basepath = request.getscheme () + "://" +request.getservername () + ":" +request.getserverport () +path+ "/";
%>
Path is the context root that gets the current project
BasePath = http://localhost: Port number/Item up/down root/


In the head tag, add <base href= "<%=basePath%>", meaning that the link to the page takes absolute path
<base href= "<%=basePath%>" >


16. In version 1.6, the string @override is automatically generated when the interface is implemented. And this string is not supported in 1.5
JDK 1.6 Settings:
Installed JRE set to 1.6
The Java Compiler level of the project should also be set to 1.6
The JDK under Tomcat 6.x is also set to 1.6

Concept of 17.MVC

In MVC.
M:model entity
C:action
V:view View

Control access by C, separating model from view.

18. How do I view Tomcat's port number?

/conf/server.xml files under%tomcat%:

<connector port= "9090" protocol= "http/1.1"
connectiontimeout= "20000"
Redirectport= "8443" uriencoding= "UTF-8"/>

19.struts2 ways to access web elements
(request,session,application)

Request < Session < application

Request: Only on one request (forwarding does not count the request, because forwarding is the behavior of the server) takes effect.
Session: When a user accesses a site, the server generates a SessionID for the customer and returns it to the client as a cookie. One
The user is like a session object until the browser is closed.
Application: A server is a Application object, and application is destroyed when the server is stopped.


The corresponding interface
Request:javax.servlet.http.HttpServletRequest
Session:javax.servlet.http.HttpSession
Application:javax.servlet.ServletContext

A common approach
SetAttribute (string name, Object o), GetAttribute (string name)

In the STRUTS2 framework, how to get the Request,session,application object

1. Using the Actioncontext container to get, get the type of the map type
2. Implement Interface requestaware,sessionaware,applicationaware,struts the framework automatically injects objects through the set method. Object type is map<string,object> (recommended)
3. Use the Servletactioncontext container to get the object type Httpservletrequest,httpsession,servletcontext.
4. Implement Interface Servletrequestaware interface, the struts framework automatically injects objects through the set method. The object type is Httpservletrequest,httpsession,servletcontext.

IOC and DI Concepts

Shorthand for ioc:inverse of control. Control inversion, created by the framework configuration for controlling objects
Di:dependency injection, relying on the framework to inject objects, rather than automatically go to new or get

20. Use JavaScript to implement multiple button submissions on a page

<input type= "button" value= "Submit1" onclick= "javascript:document.f.action= ' login/login1.action '; Document.f.submit (); " >
<input type= "button" value= "Submit2" onclick= "javascript:document.f.action= ' login/login2.action '; Document.f.submit (); " >
<input type= "button" value= "Submit3" onclick= "javascript:document.f.action= ' login/login3.action '; Document.f.submit (); " >
<input type= "button" value= "SUBMIT4" onclick= "javascript:document.f.action= ' login/login4.action '; Document.f.submit (); " >

21. Use the Addfielderror method and the S:fielderror label to easily handle data validation


Add error after data check
This.addfielderror ("name", "Name is Error");

Add Struts Tab
<% @taglib uri= "/struts-tags" prefix= "s"%>


Remove the fielderror that you added in the action to display
<s:fielderror fieldname= "name" theme= "Simple"/>


<s:debug> </s:debug>
Value Stack
Value stack: The property name and property value are stored in the middle
Stack is a container, LIFO, advanced after the principle.
The value Stacke is evaluated by <s:property value= "errors.name[0]"/>.
The errors here is the property name,
Name is the key,[0 of the collection of map types] is the first value that takes the array value of a collection.

22. How do I quickly open the edit JSP page?

Right-click on the JSP page, select Open With, select MyEclipse JSP Editor

23.ACTION when Chinese parameters are accepted, how to deal with Chinese characters?

<constant name= "struts.i18n.encoding" value= "GBK"/>

Struts 2.16 has a bug, and after setting this statement in Struts.xml, Chinese is still garbled. This issue was resolved after the 2.17 release.

24. Result type

<result type= "Dispatcher" name= "SUCCESS" >/indexAction.jsp</result>

Dispatcher (default, Server jump.) Forward equivalent to JSP, can only jump to JSP page)
Redirect (the client jumps to the JSP and cannot share the contents of the value stack.) Need to take value from action Context)
Chain (Jump to action, type of jump is server jump)
Redirectaction (client jumps to action)


25. The difference between a server jump and a client-side jump

1. From the Address bar display
Forward is the server requests the resource, the server directly accesses the URL of the destination address, reads the response content of that URL, and then sends the content to the browser. The browser doesn't know where the server sent the content from,
So its address bar is still the original address.
Redirect is the server based on logic, sending a status code that tells the browser to re-request that address. So the address bar shows a new URL.

2. From data sharing
Forward: The forwarded page and the forwarded page can share the data within the request.
Redirect: Data cannot be shared.

3. From the place of use
Forward: Generally used for user login, according to the role of forwarding to the corresponding module.
Redirect: Generally used for users to log off when landing to return to the main page and jump to other sites and so on.

4. From an efficiency standpoint
Forward: High.
Redirect: Low.


26.OGNL-expression

The action common property in the value stack of the access stacks: <s:property value= "username"/>
accessing objects in the value stack normal properties (Get,set method): <s:property value= "User.age"/>

The contents of the value stack can be viewed through <s:debug></s:debug>

When an object's properties are assigned to an action, struts is automatically constructed by the object. Otherwise, it will not be created.

STRUTS2 Basic Knowledge Learning

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.