Detailed explanation of struts2 and how to use struts2?

Introduction to Struts2:
1. MVC
Model 1: Write all the program code to the JSP page.
Model 2: JSP (process control, data display) + JavaBean Improved
Model2: Servlet (process control) + Jsp (data display) + JavaBean (business logic, data processing)
MVC: Divide the entire application into 3 major Components (Model, View, Controller)
Note: MVC and three layers are not the same thing.
Second, Struts2 Introduction
Struts2 is a typical MVC framework.
struts2 = Struts1 + WebWork
The directory structure of the struts2 download package: apps (sample program), docs (help document), lib (jar package), src (source code)
3. Development process of Struts2 project
1. Create a web project
2. Import struts2 Related Jar packages
Tip : You can unzip struts-blank.war in the apps directory, copy the related jar packages from its lib directory,
and configure the core controller (filter) of struts2 in the web.xml file
  <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>
4. In src Add struts.xml file in 5.
Create Action class, and add
Action method Method 2: Inherit class ActionSupport  Method 3: POJO class 6. Configure action node in struts.xml file 7. Write JSP page 4. Detailed explanation of struts.xml configuration , can also be written separately to struts.properties. 2.













json: When an ajax request is made, it is generally returned in json format
. 3. Common configuration introduction
The name attribute of result can be omitted, the default value is success
The type attribute of result can be omitted, the default value is dispatcher The
url address accessed by the user is namespace+actionName
  <?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>
<!-- Set struts2 constants-->
<constant name="struts.enable.DynamicMethodInvocation" value="true"></constant>
<!- - There can be multiple package nodes-->
<!-- name: the name value of each package cannot be the same, required
namespace: namespace (part of the URL address)
extends: generally inherit the struts-default package-- >
<package name="default" namespace="/" extends="struts-default">
/default-interceptor-ref> <!-- Default action. When the user does not enter any action in the browser address bar, the action configured on this node will be accessed --> <!-- http://localhost:8080/projectname/ -->


















<default-action-ref name="login"></default-action-ref>
<!-- 默认的action类(当action节点省略时,将使用本节点配置的类) -->
<default-class-ref class=""></default-class-ref>
<!-- 全局的result -->
<global-results>
<result name="login" type="dispatcher">/login.jsp</result>
<result name="error" type="dispatcher">/error.jsp</result>
</global-results>
<!-- 全局的异常映射 -->
<global-exception-mappings>
<exception-mapping result="error" exception="java.lang.Exception"></exception-mapping>
<exception-mapping result="error" exception="java.sql.SQLException"></exception-mapping>
<exception-mapping result="error" exception="java.lang.NullPointerException"></exception-mapping>
</global-exception-mappings>

<!-- There can be multiple actions (name is required; class and method can be omitted; if the method is omitted, the default is execute) -->
<action name="login" class="" method ="">
<!-- name can be omitted, the default value is success; type can be omitted, the default value is dispatcher -->
<result name="" type=""></result>
</action>
</package >
<!-- Import other struts configuration files, no matter how many struts configuration files there are, for the struts2 framework, only struts.xml will be loaded, all other configuration files need to be imported into the struts.xml file-->
<include file=""></include>
</struts>
5. Interceptor
1. Define interceptor
Implement interface: Interceptor
Inheritance class: AbstractInterceptor
2. Configure the interceptor
First, add the Interceptor node under the Interceptors node;
secondly, either use the interceptor through the interceptor-ref in the action, or configure the default-interceptor-ref
3. Note
Once a custom interceptor is used, the default interceptor defaultStack provided by struts2 will no longer work.
How to break? Add a new interceptor stack, add references to custom interceptors and defaultStack, and then set this interceptor stack as the default interceptor.
4. The interceptor provided by struts2, the
params interceptor, the
validation interceptor, the
fileUpload interceptor, the
workflow interceptor
...
6. The form tag of the file upload
1.jsp page, the method attribute value must be
the form tag of the post 2.jsp page, and enctype must be added =multipart/form-data attribute
3. The file domain of type=file in the jsp page
4. Add the jar package for apache file upload: commons-fileupload, commons-io
5. Add three attributes to the Action class:
  private File xxx ;
  private String xxxFileName;
  private String xxxContentType;
6. Save the file in the action method to
avoid the file being overwritten when the file name has the same name: uuid as the file name
The file path stored in the database must be a relative path
How to get the specified directory in the project absolute path
String path = ServletActionContext.getServletContext().getRealPath("files");
7. Limit the file size and file type
by setting the parameters of the fileUpload interceptor.
maximumSize: limit the size of file upload
allowedTypes: limit the type of file upload
<constant name="struts.multipart.maxSize" value="1024000"></constant>
<interceptor-ref name="fileUpload">
<!--Configuration File types allowed to be uploaded-->
<param name="allowedTypes">image/bmp,image/png,image/gif,image/jpeg</param>
<!--Configure the allowed file size in bytes-- >
<param name="maximumSize">5242880</param>
</interceptor-ref>
8. Multi-file upload You
only need to set the three properties in the action to an array to
private File[] xxx;
private String[] xxxFileName;


1. There must be an attribute of type InputStream in the action, and this attribute has a get method
2. In the result node of the action of struts.xml, the value of the type attribute is stream
<result name=”xxx” type=”stream”>
  <param name=”contentType”></param>
<param name=”inputName”>the attribute name of type inputstream</param>
<param name=”contentDisposition”>
  attachment;filename=”${fileName}”
</ param>
</stream>
8. How to use servlet api in struts2
1. Mode 1 (coupling)
HttpServletRequest request = ServletActionContext.getRequest();
HttpSession session = ServletActionContext.getRequest.getSession();
HttpServletResponse response = ServletActionContext.getResponse();
ServletContext application = ServletActionContext.getServletContext();
2. Method 2 (non-coupling)
Map<String, Object> request = (Map<String, Object>) ActionContext.getContext().get("request");
Map<String, Object> session = ActionContext.getContext().getSession();
Map<String , Object> application = ActionContext.getContext().getApplication();
3. Method 3 (non-coupling)
let Action class implement interfaces: RequestAware, SessionAware, ApplicationAware
9, OGNL
1.ognl: Object Graph Navigation Language
2.ognl and el Similar, are used to simplify the java code in jsp
3.ongl can get data from 2 places
ValueStack: value stack. Generally, only objects of the current Action class are stored in the value stack.
ActionContext: application, session, request, pageContext, parameters, attr.
Note: The data in the value stack can be obtained directly by name; but the data in the ActionContext needs to be prefixed with #
#application
#session
#request
#pageContext
#paramteters
#attr
Among them, attr indicates that data is obtained from pageContext, request, session, and application in turn.
Ten, the tags of struts2
1.jstl- JSP standard tag library Core
tags
forEach, choose, when, otherWise, if Format
tags
formatDate, formatNumber
2. The tags provided by struts2
form, iterator, if, else, select, checkbox, checkboxlist, radio, fielderror
11, data verification
1. Client-side verification Verify whether user data is legal
through javascript script
<form>
  <input type=”submit” value=”save Data” onclick=”return checkFormData();” / >
</form>
<script type=”text/javascript”>
function checkFormData(){
  … …
  return true|false;
}
</script>
Note : Client-side validation is not secure. Users can disable js code by disabling js scripts; users can also use HttpRequest to simulate user requests to avoid js validation.
2. Server-side verification
Server -side verification cannot be omitted.
If it does not pass the data verification, it will return input by default.
If the data type conversion fails, data validation is still performed.
If the data verification fails, the target action method will no longer be executed.
Override the validate method of the parent class ActionSupport, and all the action methods
in the Action class will be validated.
Add the validation method validateXxx method in the Action class
This validation method only works on the xxx method.
Add xml validation file in the same package of Action class, it
only works for specific action method. The biggest advantage is that there is no need to write java verification code.
The format of the validation file: ActionClassName-actionAlias-validation.xml.
Struts2 built-in validators:
required: required validator
requiredstring: required string validator (trim)
int: integer validator
stringlength: string length validator (minLength, maxLength)
 regex: regular expression validator
date: date validator
double: double-precision validator
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE validators PUBLIC
        "-//Apache Struts//XWork Validator 1.0.2//EN"
        "http://struts.apache.org/dtds/xwork-validator-1.0.2.dtd">
<validators>
<field name="user.userName">
<field-validator type="requiredstring">
<param name="trim">true</param>
<message>用户名不能为空</message>
</field-validator>
<field-validator type="stringlength">
<param name="minLength">6</param>
<param name="maxLength">10</param>
<message>用户长度必须介于${minLength}-${maxLength}之间</message>
</field-validator>
</field>
<field name="user.password">
<field-validator type="requiredstring">
<param name="trim">true</param>






















<constant name="struts.custom.i18n.resources" value="message"></constant>
Second, add a resource file named message
message_zh_CN.properties
message_en.properties
message.properties
Finally, use s in the JSP page: text to display text, use <message key=”key”> in the data validation file
13. Definition of ajax
1.ajax
Asynchronous javascript and xml.
2. The role of ajax
Asynchronous request, partial refresh
3. Basic concept of
ajax Ajax is not a separate technology, it involves javascript, css, XMLHttpRequest and so on. Its core component is XMLHttpRequest, but different browsers have different support for XMLHttpRequest, so when creating its object, the browser must be judged separately. Therefore, in the actual development process, we rarely write native ajax code, but use the ajax functions provided by frameworks such as jquery to quickly achieve ajax effects.
4.XMLHttpRequest
open(method, url, async)
method: the type of get|post request sent
onreadystatechange
request state change event, need to mount function.
readyState==4 status==200 indicates success
send(data)
formally sends a request to the server
5. The ajax function provided by
jquery load(url)
loads the result of the specified url request
$.get(url, parameter, callback, type )
send the request
url to the server in the get method: the address of the
request parameter: the parameter of the request, usually an object in json format {id: 5, name: "zhangsan"}
callback: callback function function(data){}, where data represents The result
type returned by the server: text|json|html|xml
$.post(url, parameter, callback, type)
sends a request to the server in post mode. The parameters are the same as $.get.
$.getJSON(url, parameter, callback)
sends a request to the server in get mode. The returned result is in json format.
$.ajax({})
The bottommost ajax function. All the above functions can be implemented by this function.
$.ajax({
url: url address,
type: “get|post”,
data:{id:5, name:”zhangsan”},
dataType: “json”,
success:  function(data){},
error: function(xhr){}
});

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326406062&siteId=291194637