struts2
Definition:
struts2 Is based on mvC Design mode web Application framework, its essence is equivalent to a servlet,stay MVC In design mode, Struts2 As controller( controller)To establish data interaction between model and view Struts2 That's right web Controller to jump to between different pages in the project. However, the controller is mounted on MVC IQ, ratio MVC The framework has more inherent technical advantages and model implementation advantages. It's a web Developed components, usually spring,hibernate,mybatis And other frameworks. Throughout web Play the role of the page Jump controller in the project.
servlet disadvantages?
1,If there are many functions, you need to write many servlet,Of course, it can be simplified by reflection, but it is still troublesome 2,servlet You need to get the data transferred from the page, request.getParamter("")Method. If you get a lot of values, you need to write a lot request.getParamter("")
Set up struts2 environment
1. Guide 13 core jar packages:
2. Web Configuring filters in XML
The core controller of Struts2 intercepts the following requests by default
- Request with action suffix
- Request without any suffix
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <display-name>struts2Day1_01</display-name> <!-- Configure filters --> <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> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>
Under the filter node, we set the corresponding class of filter, which is fixed here. In the filter mapping node, set the value of URL pattern to / *, which represents global validation. All requests take effect, that is, each http request will be processed by struts2.
3. Define a java class action, which is used to process requests. The method return value type is String
action creation method:
1. To implement the Action interface, you can directly use the constants provided by the Action. You must override the default processing method execute().
2. Inherit ActionSupport class, recommended.
3. Directly define a common class [you can see from the last position of the struts-default.xml file]
<default-class-ref class="com. opensymphony.xwork2.ActionSupport" />
You have inherited ActionSupport class by default.
When we use a servlet, the server will execute the servlet method every time we access the servlet. In struts2, we call every request action. When the user accesses the action, the default method is execute. Therefore, we create a new class, as follows:
package action; import com.opensymphony.xwork2.Action; public class LoginAction implements Action{ private String userName; private String passWord; 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; } @Override public String execute() throws Exception { System.out.println("User name:"+this.getUserName()); System.out.println("Password:"+this.getPassWord()); return "success"; } }
4. Configure struts XML
<?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> <!-- Must inherit struts-default.xml --> <package name="default" namespace="/" extends="struts-default" method="execute"> <action name="login" class="action.LoginAction"> <result name="success">/loginSuccess.jsp</result> <!-- <result name="success">/fail.jap</result> --> </action> </package> </struts>
1.package node: represents a package. A package can contain multiple action s, and a program can also have many packages. We let it inherit struts default XML.
- Name: the name of the package. Must be configured
- Namespace: indicates the namespace. The value of namespace is "/", which means that when we access an action, we directly access it through the IP/action name. For example: http://localhost:8081/struts2Day1_01/login.action , if we define the value of namespace as the user needs to: http://localhost:8081/struts2Day1_01/user/login.action Access in this way.
2.action node: the name attribute identifies the name of the form you submit, corresponding to a class class.
3.result node: represents the processing result. The name attribute represents the character result returned by the method in the action class after processing. The corresponding processing is made according to the returned character result. The success string (default forwarding) returned above is forwarded to loginsuccess JSP.
Jump to the Type attribute of result
<action name="login" class="action.LoginAction"> <result name="success">/loginSuccess.jsp</result> <result name="fail" type="redirect">/fail.jsp</result> </action>
1. dispatcher: default value, forwarding
2. Redirect: redirect
3. chain: forward to action, generally not used, cache problem
4. redirectAction: redirect to Action
Global results global variable:
If multiple action s return the same results and go to the same page, you can actually configure global variables.
<package name="user" namespace="/user" extends="struts-default" > <action name="login" class="action.LoginAction" method="login"> <result name="success">/login.jsp</result> </action> <action name="register" class="action.LoginAction" method="register"> <result name="success">/register.jsp</result> </action> <!-- Configure global variables --> <global-results> <result name="error">/hello.jsp</result> </global-results> </package>
Sub module development:
In project development, it is generally developed by multiple people to prevent everyone from configuring the same struts XML files are generally developed in modules, so that they will not be confused. Write the module functions that everyone needs to do into an independent configuration file.
Struts XML file:
<struts> <!-- If no path is specified, the default path is src Lower use --> <include file="struts-shop.xml"></include> <!-- stay src lower action package --> <include file="action/struts-shop.xml"></include> </struts>
Action access method:
1. Traditional access
Use the method attribute in the action tag, and configure the action method to be executed in this attribute. If it is not written, the execute() method will be executed by default
<!-- struts.xml --> <package name="user" namespace="/user" extends="struts-default"> <action name="login" class="action.LoginAction" method="login"> <result name="success">/login.jsp</result> <result name="fail" type="redirect">/fail.jsp</result> </action> <action name="register" class="action.LoginAction" method="register"> <result name="success">/register.jsp</result> <result name="fail" type="redirect">/fail.jsp</result> </action> </package>
<!-- index.jsp --> <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@taglib prefix="s" uri="/struts-tags" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <s:form action="/user/login" method="post"> <input type="submit" value="Go to login" /> </s:form> <s:form action="/user/register" method="post"> <input type="submit" value="To register" /> </s:form> </body> </html>
2. Dynamic call access
<!-- struts.xml --> <!-- Set constants to allow dynamic method calls --> <constant name="struts.enable.DynamicMethodInvocation" value="true" /> <package name="user" namespace="/user" extends="struts-default"> <!-- /user/userFacillity!register.action call action.LoginAction Lower register method--> <action name="userFacillity" class="action.LoginAction" > <result name="dologin">/login.jsp</result> <result name="doregister">/register.jsp</result> </action> </package>
<!-- index.jsp --> <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@taglib prefix="s" uri="/struts-tags" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <!--package Nodal namespace + action Nodal name + !Method name( )--> <s:form action="/user/userFacillity!login" method="post"> <input type="submit" value="Go to login" /> </s:form> <s:form action="/user/userFacillity!register" method="post"> <input type="submit" value="To register" /> </s:form> </body> </html>
3. Wildcard call access
<!-- struts.xml --> <package name="user" namespace="/user" extends="struts-default"> <!-- addUser.action deleteUser.action Metropolis requests*User.action {1}For the first*No --> <action name="*User" class="action.LoginAction" method="{1}" > <result name="doadd">/{1}_User.jsp</result> <result name="dodelete">/{1}_User.jsp</result> </action> </package>
<!-- index.jsp --> <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@taglib prefix="s" uri="/struts-tags" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <s:form action="/user/addUser" method="post"> <input type="submit" value="To increase"> </s:form> <s:form action="/user/deleteUser" method="post"> <input type="submit" value="To delete"> </s:form> </body> </body> </html>
OGNL:
In the web phase, EL expressions are used in jsp pages to obtain the values of domain objects. struts2 provides OGNL tags, which are more powerful than EL expressions
OGNL(object Graph Navigation Language),Object graph navigation language, which is a powerful expression language,It is very convenient to manipulate object attributes. Open source projects, not strus2 It comes with it, but it is usually the same as struts2 Used in conjunction with frames to replace the java Scripts to simplify data access and EL Expressions belong to expression languages.
OGNL does two things in struts2:
1. Expression language:
Bind forms or struts2 tags to specific java data to move data into and out of the framework.
2. Automatic type conversion
The data entry and exit framework enables automatic conversion between the string data entered on the page and java data and java data types.
Get form data:
1. Property acquisition
LoginAction.java
package action; import com.opensymphony.xwork2.Action; import entity.User; public class LoginAction implements Action{ private String username; private String password; private String address; private String message; 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; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } @Override public String execute() throws Exception { System.out.println("username: "+username); System.out.println("password: "+password); System.out.println("address: "+address); System.out.println("message: "+message); return "success"; } }
index.jsp
<form action="login.action"> User name:<input type="text" name="username"><br/> Password:<input type="text" name="password"><br/> Address:<input type="text" name="address"><br/> General message:<input type="text" name="message"><br/> <input type="submit" value="Submit"> </form>
success.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@taglib prefix="s" uri="/struts-tags" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <s:property value="username"/><br/> <s:property value="password"/><br/> <s:property value="address"/><br/> </body> </html>
2. Object acquisition
LoginAction.java
package action; import com.opensymphony.xwork2.Action; import entity.User; public class LoginAction implements Action{ //Encapsulate objects private User user; //Encapsulation properties private String message; public User getUser() { return user; } public void setUser(User user) { this.user = user; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } @Override public String execute() throws Exception { System.out.println("username: "+user.getUsername()); System.out.println("password: "+user.getPassword()); System.out.println("address: "+user.getAddress()); System.out.println("message: "+message); return "success"; } }
index.jsp
<form action="login.action"> User name:<input type="text" name="user.username"><br/> Password:<input type="text" name="user.password"><br/> Address:<input type="text" name="user.address"><br/> General message:<input type="text" name="message"><br/> <input type="submit" value="Submit"> </form>
success.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@taglib prefix="s" uri="/struts-tags" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <s:property value="user.username"/><br/> <s:property value="user.password"/><br/> <s:property value="user.address"/><br/> <s:property value="message"/> </body> </html>
3. Model driven acquisition
LoginAction.java
package action; import com.opensymphony.xwork2.Action; import com.opensymphony.xwork2.ModelDriven; import entity.User; public class LoginAction implements Action,ModelDriven<User>{ //Encapsulate objects private User user =new User(); @Override public User getModel() { return user; } @Override public String execute() throws Exception { System.out.println("username: "+user.getUsername()); System.out.println("password: "+user.getPassword()); System.out.println("address: "+user.getAddress()); return "success"; } }
index.jsp
<form action="login.action"> User name:<input type="text" name="username"><br/> Password:<input type="text" name="password"><br/> Address:<input type="text" name="address"><br/> General message:<input type="text" name="message"><br/> <input type="submit" value="Submit"> </form>
success.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@taglib prefix="s" uri="/struts-tags" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <s:property value="username"/><br/> <s:property value="password"/><br/> <s:property value="address"/><br/> </body> </html>
4. Get array
ArrayDataAction.java
package action; import com.opensymphony.xwork2.Action; import com.opensymphony.xwork2.ModelDriven; import entity.User; public class ArrayDataAction implements Action{ private String[] hobbies; //Automatic type conversion //The double type is defined, but the data submitted by the page is of text type //The type conversion of Struts2 is based on the automatic type conversion of OGNL expression, //No more double Parsedouble ("123") transform private Double[] numbers = new Double[3]; public String[] getHobbies() { return hobbies; } public void setHobbies(String[] hobbies) { this.hobbies = hobbies; } public Double[] getNumbers() { return numbers; } public void setNumbers(Double[] numbers) { this.numbers = numbers; } @Override public String execute() throws Exception { for (int i = 0; i < hobbies.length; i++) { System.out.println(hobbies[i]); } System.out.println("------------------------"); for (int i = 0; i < numbers.length; i++) { System.out.println(numbers[i]); } return "success"; } }
index.jsp
<form action="ArrayData.action"> Hobby 1:<input type="text" name="hobbies" /> <br/> Hobby 2:<input type="text" name="hobbies" /> <br/> Hobby 3:<input type="text" name="hobbies" /> <br/> Number1:<input type="text" name="numbers" /> <br/> Number2:<input type="text" name="numbers" /> <br/> Number 3:<input type="text" name="numbers" /> <br/> <input type="submit" value="Submit"> </form>
success.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!-- lead into jstl Standard label Library --> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %> <!-- Set the root path of the project --> <c:set var="ctx" value="${pageContext.request.contextPath}"></c:set> <%@taglib prefix="s" uri="/struts-tags" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <--Traverse to get array data--> <c:forEach items="${hobbies}" var="hobbie"> <span>${hobbie}</span> </c:forEach> <c:forEach items="${numbers}" var="number"> <span>${number}</span> </c:forEach> </body> </html>
5. Get list collection
ListDataAction.java
package action; import java.util.List; import com.opensymphony.xwork2.Action; public class ListDataAction implements Action{ private List<String> hobbies; private List<String> numbers; public List<String> getHobbies() { return hobbies; } public void setHobbies(List<String> hobbies) { this.hobbies = hobbies; } public List<String> getNumbers() { return numbers; } public void setNumbers(List<String> numbers) { this.numbers = numbers; } @Override public String execute() throws Exception { for (int i = 0; i < hobbies.size(); i++) { System.out.println(hobbies.get(i)); } System.out.println("------------------------"); for (int i = 0; i < numbers.size(); i++) { System.out.println(numbers.get(i)); } return "success"; } }
index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib prefix="s" uri="/struts-tags" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <form action="ListData.action"> Username 1:<input type="text" name="list[0].username" /> <br/> Password 1:<input type="text" name="list[0].password" /> <br/> Address 1:<input type="text" name="list[0].address" /> <br/> Username 2:<input type="text" name="list[1].username" /> <br/> Password 2:<input type="text" name="list[1].password" /> <br/> Address 2:<input type="text" name="list[1].address" /> <br/> Username 3:<input type="text" name="list[2].username" /> <br/> Password 3:<input type="text" name="list[2].password" /> <br/> Address 3:<input type="text" name="list[2].address" /> <br/> <input type="submit" value="Submit"> </form> </body> </html>
success.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!-- lead into jstl Standard label Library --> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %> <!-- Set the root path of the project --> <c:set var="ctx" value="${pageContext.request.contextPath}"></c:set> <%@taglib prefix="s" uri="/struts-tags" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <!-- Get the value method of the collection 1 --> <s:property value="list[0].username"/><br/> <s:property value="list[0].password"/><br/> <s:property value="list[0].address"/><br/> <s:property value="list[1].username"/><br/> <s:property value="list[1].password"/><br/> <s:property value="list[1].address"/><br/> <s:property value="list[2].username"/><br/> <s:property value="list[2].password"/><br/> <s:property value="list[2].address"/><br/> <hr/> <!-- Get the value of the collection method 2 struts2 Label iteration --> <s:iterator value="list"> <s:property value="username"/> <br/> <s:property value="password"/> <br/> <s:property value="address"/> <br/> </s:iterator> <hr/> <!-- Get the value of the collection method 3 el expression --> <c:forEach items="${list}" var="user"> <span>${user.username}</span> <span>${user.password}</span> <span>${user.address}</span> </c:forEach> </body> </html>
6. Get map collection
MapDataAction.java
package action; import java.util.Map; import com.opensymphony.xwork2.Action; import entity.User; public class MapDataAction implements Action{ private Map<String,User> map; public Map<String, User> getMap() { return map; } public void setMap(Map<String, User> map) { this.map = map; } @Override public String execute() throws Exception { User user1 = map.get("one"); User user2 = map.get("two"); System.out.println("map1:"+user1.toString()); System.out.println("map2:"+user2.toString()); return "success"; } }
index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib prefix="s" uri="/struts-tags" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <form action="MapDataAction.action"> Username 1:<input type="text" name="map['one'].username" /> <br/> Password 1:<input type="text" name="map['one'].password" /> <br/> Address 1:<input type="text" name="map['one'].address" /> <br/> Username 2:<input type="text" name="map['two'].username" /> <br/> Password 2:<input type="text" name="map['two'].password" /> <br/> Address 2:<input type="text" name="map['two'].address" /> <br/> <input type="submit" value="Submit"> </form> </body> </html>
success.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!-- lead into jstl Standard label Library --> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %> <!-- Set the root path of the project --> <c:set var="ctx" value="${pageContext.request.contextPath}"></c:set> <%@taglib prefix="s" uri="/struts-tags" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <--Key value pair traversal--> <c:forEach var="item" items="${map}"> ${item.key} > ${item.value} <br> </c:forEach> <--Key traversal--> <c:forEach var="item" items="${map}"> ${item.key}<br> </c:forEach> <--Value traversal--> <c:forEach var="item" items="${map}"> ${item.value}<br> </c:forEach> </body> </html>
struts2 automatic type conversion
We used to get the page data at the servlet time, because the data submitted from the page data are all text data. If we need to convert it to other types, such as int, we need integer Parselnt (request.getparame ("") to convert to int type, or we add
When.
Value stack:
1.Previously in web Phase, in servlet Inside, you can put the data into the domain object and use it in the page EL The expression gets that the domain object is in a-Storage and value taking within a certain range 2,stay struts2 The framework provides its own storage mechanism, similar to domain objects, which is the value stack. You can save and take values through action Put the data into the value stack, and get the data of the value stack in the page. The value stack has the characteristics of stack. 3,servlet and action Differences between (1)servlet: By default, it is created at the first access. The singleton mode is created once. (2)Action: Created during access, each time action Will be created when action Object, create multiple times, multi instance object. 4,Value stack storage location (1)Every visit action Every time action object (2)In each action There will be a value stack object (only one) in the object
Get value stack object
//Get ActionContext object ActionContext context = ActionContext.getContext(); //Get the value stack object. Each action object has only one value stack object ValueStack stack1 = context.getValueStack(); ValueStack stack2 = context.getValueStack(); System.out.println(stack1==stack2);
Value stack value
//Value stack storage method 1: //stack1.set("username", "Zhang San"); //Value stack storage mode 2: //stack1.push("abcd"); //Value stack storage method 3: the most common method is to define variables in action and generate variable get/set methods (the advantage is to reduce space allocation) name="myname";
Get non value stack object
Non value stack objects: application, session, request, parameters, attr
//application Map<String, Object> application = ActionContext.getContext().getApplication(); //session Map<String, Object> session = ActionContext.getContext().getSession(); //request HttpServletRequest request = ServletActionContext.getRequest();
Non value stack value
//application session.put(key, value); //session application.put(key, value) //request request.setAttribute("name", value);
Get non value stack object
<!-- Non value stack object acquisition method#--> <s:iterator> <s:property value="#user.username"/> <s:property value="#user.password"/> </s:iterator>
Interceptor
Definition:
Interceptors in java are objects that dynamically intercept action calls. It provides a mechanism for developers to define the code to be executed before and after the execution of an action, or to prevent the execution of an action before it is executed. It also provides a way to extract the reusable part of an action. In AOP (aspect oriented programming), interceptors are used to intercept a method or field before it is accessed, and then add some operations before or after it.
Principle:
What is the difference between filters and interceptors?
(1) Filter: created when the server is started. Theoretically, the filter can contain any content, such as html, jsp, servlet, and image path
(2) Interceptor: the interceptor can only intercept the difference between action 2 Servlet and action.
What is the difference between Servlet and action?
(1) By default, the servlet is created at the first access. It is created once. It is a single instance object
(2) action is created at each access, multiple times, and multiple instance objects
Customizing an interceptor requires two steps:
There are many interceptors in struts2. These interceptors are the functions encapsulated by struts2. However, in actual development, the interceptors in struts2 may not have the functions to be used. At this time, you need to write your own interceptors to realize the functions.
1 Customize a class that implements the Interceptor interface (or inherits from AbstractInterceptor).
package interceptor; import com.opensymphony.xwork2.ActionInvocation; import com.opensymphony.xwork2.interceptor.AbstractInterceptor; public class MyTimeInterceptor extends AbstractInterceptor{ @Override public String intercept(ActionInvocation invocation) throws Exception { //start time long startTime = System.currentTimeMillis(); System.out.println("Action start time"+startTime); //Responsible for calling action. Before that, all configured interceptors will be called in turn to return action results String result = invocation.invoke(); long endTime = System.currentTimeMillis(); long execTime = endTime-startTime; System.out.println("Action End time:"+endTime); System.out.println("implement Action Total time"+execTime); System.out.println("implement Action Returned result Results:"+result); return result; } }
2 In struts The interceptor defined above the action in XML refers to the interceptor defined above in the action to be used.
<?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> <package name="default" namespace="/" extends="struts-default"> <!-- Configuring Interceptors --> <interceptors> <interceptor name="myTime" class="interceptor.MyTimeInterceptor"/> </interceptors> <action name="login" class="action.MyTimeAction" method="execute"> <result name="success">/success.jsp</result> <result name="fail" type="redirect">/fail.jsp</result> <!-- stay action It refers to a custom interceptor --> <interceptor-ref name="myTime"> <!-- Can be set by parameters action Some methods of do not intercept --> <!-- <param name="excludeMethods">add,delete</param> --> </interceptor-ref> <interceptor-ref name="defaultStack"/> </action> </package> </struts>
Case:
Single file upload:
UploadFileAction.java
package action; import java.io.File; import org.apache.commons.io.FileUtils; import org.apache.struts2.ServletActionContext; public class UploadFileAction{ private String savePath; private File upload; private String uploadContentType; private String uploadFileName; public String getSavePath() { return savePath; } public void setSavePath(String savePath) { this.savePath = savePath; } public File getUpload() { return upload; } public void setUpload(File upload) { this.upload = upload; } public String getUploadContentType() { return uploadContentType; } public void setUploadContentType(String uploadContentType) { this.uploadContentType = uploadContentType; } public String getUploadFileName() { return uploadFileName; } public void setUploadFileName(String uploadFileName) { this.uploadFileName = uploadFileName; } public String uploadFile() throws Exception { // File destFile = new File(ServletActionContext.getRequest().getRealPath(save)); String file = ServletActionContext.getRequest().getRealPath(savePath)+"\\"+this.getUploadFileName(); File destFile = new File(file); FileUtils.copyFile(upload, destFile); return "success"; } }
struts.xml
<?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> <!-- <include file="action/struts-time.xml"></include> --> <package name="default" namespace="/" extends="struts-default"> <action name="upload" class="action.UploadFileAction" method="uploadFile"> <param name="savePath">/upload</param> <result name="input">/uploadError.jsp</result> <result name="success">/uploadFile.jsp</result> <!-- apply struts2 FileUploadInterceptor Uploaded interceptor --> <interceptor-ref name="fileUpload"> <!-- Size of uploaded file in bytes, 10 M --> <param name="maximumSize">10240000</param> <!-- Type of uploaded file --> <param name="allowedTypes">png,gif,jpg,jpej</param> </interceptor-ref> <interceptor-ref name="defaultStack"></interceptor-ref> </action> </package> </struts>
uploadFile.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib prefix="s" uri="/struts-tags" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <s:form action="upload.action" enctype="multipart/form-data" method="post"> <s:file name="upload" /> <s:submit value="upload" /> </s:form> <img width="600px" height="200px" src="upload/<s:property value='uploadFileName'/>"> </body> </html>
Multi file upload:
UploadFileAction.java
package action; import java.io.File; import org.apache.commons.io.FileUtils; import org.apache.struts2.ServletActionContext; public class UploadFileAction{ private String savePath; private File[] upload; private String[] uploadContentType; private String[] uploadFileName; public String getSavePath() { return savePath; } public void setSavePath(String savePath) { this.savePath = savePath; } public File[] getUpload() { return upload; } public void setUpload(File[] upload) { this.upload = upload; } public String[] getUploadContentType() { return uploadContentType; } public void setUploadContentType(String[] uploadContentType) { this.uploadContentType = uploadContentType; } public String[] getUploadFileName() { return uploadFileName; } public void setUploadFileName(String[] uploadFileName) { this.uploadFileName = uploadFileName; } public String uploadFile() throws Exception { for (int i = 0; i < upload.length; i++) { String file = ServletActionContext.getRequest().getRealPath(savePath)+"\\"+this.getUploadFileName()[i]; File destFile = new File(file); //upload[i] traverse the upload object (upload file) FileUtils.copyFile(upload[i], destFile); } return "success"; } }
struts.xml
<?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> <!-- <include file="action/struts-time.xml"></include> --> <package name="default" namespace="/" extends="struts-default"> <action name="upload" class="action.UploadFileAction" method="uploadFile"> <param name="savePath">/upload</param> <result name="input">/uploadError.jsp</result> <result name="success">/uploadFile.jsp</result> <!-- apply struts2 FileUploadInterceptor Uploaded interceptor --> <interceptor-ref name="fileUpload"> <!-- Size of uploaded file in bytes, 10 M --> <param name="maximumSize">10240000</param> <!-- Type of uploaded file --> <param name="allowedTypes">png,gif,jpg,jpej</param> </interceptor-ref> <interceptor-ref name="defaultStack"></interceptor-ref> </action> </package> </struts>
uploadFile.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib prefix="s" uri="/struts-tags" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <s:form action="upload.action" enctype="multipart/form-data" method="post"> <s:file name="upload" /> <s:file name="upload" /> <s:file name="upload" /> <s:submit value="upload" /> </s:form> <s:iterator value="uploadFileName"> <img width="600px" height="200px" src="upload/<s:property />"> </s:iterator> </body> </html>
File download:
DownloadAction.java
package action; import java.io.BufferedInputStream; import java.io.FileInputStream; import java.io.InputStream; import org.apache.struts2.ServletActionContext; import com.opensymphony.xwork2.ActionSupport; public class DownloadAction extends ActionSupport{ private String fileName; private String inputPath; private InputStream inputStream; public String getFileName() { return fileName; } public void setFileName(String fileName) { this.fileName = fileName; } public String getInputPath() { return inputPath; } public void setInputPath(String inputPath) { this.inputPath = inputPath; } public InputStream getInputStream() throws Exception { //Get the file path to download from the server String path = ServletActionContext.getRequest().getRealPath(inputPath+"\\"+fileName); //Return stream object return new BufferedInputStream(new FileInputStream(path)); } public void setInputStream(InputStream inputStream) { this.inputStream = inputStream; } public String login(){ return "success"; } }
struts.xml
<?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 constant total size of three files 5 M Exceedance report exception--> <constant name="struts.multipart.maxsize" value="50971520"></constant> <package name="default" namespace="/" extends="struts-default"> <action name="download" class="action.DownloadAction" method="login"> <!-- wrong Action in inputPath Assignment, from server/upload File download --> <param name="inputPath">/upload</param> <result type="stream"> <!-- Download download in binary mode --> <param name="contentType">application/octet-stream</param> <!-- Default call getinputStream()Method to download --> <param name="inputName">inputStream</param> <!-- Download popup information --> <param name="contentDisposition"> attachment;filename="${fileName}" </param> <!-- Set cache size in bytes --> <param name="bufferSize">4096</param> </result> </action> </package> </struts>
uploadFile.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib prefix="s" uri="/struts-tags" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <a href="download.action?fileName=1.png">download</a> </body> </html>
} public String login(){ return "success"; }
}
struts.xml ```xml <?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 constant total size of three files 5 M Exceedance report exception--> <constant name="struts.multipart.maxsize" value="50971520"></constant> <package name="default" namespace="/" extends="struts-default"> <action name="download" class="action.DownloadAction" method="login"> <!-- wrong Action in inputPath Assignment, from server/upload File download --> <param name="inputPath">/upload</param> <result type="stream"> <!-- Download download in binary mode --> <param name="contentType">application/octet-stream</param> <!-- Default call getinputStream()Method to download --> <param name="inputName">inputStream</param> <!-- Download popup information --> <param name="contentDisposition"> attachment;filename="${fileName}" </param> <!-- Set cache size in bytes --> <param name="bufferSize">4096</param> </result> </action> </package> </struts>
uploadFile.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib prefix="s" uri="/struts-tags" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <a href="download.action?fileName=1.png">download</a> </body> </html>