In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-01 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/03 Report--
Title: in-depth understanding of the operating mechanism of struts
Date: 2016-10-26 20:02
Tags: java
Categories: programming
Permalink: zxh
Personal analysis, do not spray if you like it.
Scan the code to follow the official account and update the work irregularly.
Write the picture description here.
I would like to declare that this blog post is not original, the original article: http://blog.csdn.net/lenotang/article/details/3336623, this article is optimized on the basis of this article. It's not optimization, it's just a little bit of my own idea.
Jar package preparation
Write the picture description here.
Why do I use these two jar packages, because I need this jar to parse the xml configuration file.
New project
Write the picture description here.
Process carding
Struts profile
/ index.jsp
/ WEB-INF/login.jsp
Friends who are familiar with struts are aware of the importance of the struts.xml configuration file. The name of this configuration file can be changed. Here we briefly explain the function of this configuration file. First of all, we find that the name of the action node, this action, is login. That is to say, after the foreground requests the login to parse the configuration file, it will give the request to the class attribute in the action, that is, the above.
Org.zxh.action.LoginAction
Specifically, it is passed to the login (method) method of this class. This method methods a string of type string, and redirects the page to index.jsp if success is returned. If it is login, redirect to login.jsp. That's what this configuration file does. Because I wrote it myself, I don't encapsulate a lot of things like the struts framework, but just to give readers a deeper understanding of how struts works.
How to start the struts.xml file we wrote in the program?
Beginner comrades may wonder, write a configuration file can deal with the front and background interaction? The answer is, of course, no. Here to popularize the web basic contact with filter, each interaction requires filter (jsp is a special servlet), so if we want to achieve interaction, we have to create a new servlet, in which we read the struts.xml file we wrote, and determine the next step through the information we read. So how do you start a filter? Needless to say, configuring the interceptor directly in the web.xml in the web project will execute filter.
Create a new filter (FilterDispatcher)
This servlet is the core filter of struts, which needs to be inherited first.
`
Public class FilterDispatcher implements Filter {
@ Override
Public void destroy () {
/ / TODO Auto-generated method stub
}
@ Override
Public void doFilter (ServletRequest arg0, ServletResponse arg1
FilterChain arg2) throws IOException, ServletException {
/ / TODO Auto-generated method stub
}
@ Override
Public void init (FilterConfig arg0) throws ServletException {
/ / TODO Auto-generated method stub
}
}
`
In Filter, we need to initialize some parameters in the initialization function (init). Initialize those data. Yes! Take the configuration file information, of course. The configuration file is .xml. Here I use dom4j to read the .xml configuration file. Put the struts.xml configuration file under src (you can put it somewhere else, just fill in the corresponding address here)
/ / obtain the xml configuration file
String webRootPath = getClass () .getClassLoader ()
.getResource ("struts.xml") .getPath ()
After getting the configuration file path, we start to read. Here, the data I read is encapsulated in a map. Let's take a closer look at the configuration file after encapsulating it in Map
Write the picture description here.
In fact, we put the values of these four attributes in Map, with these four values, we can complete a mapping of the front and background interaction. So in order to facilitate the packaging here into javabean.
Package org.zxh.util
Import java.util.HashMap
Import java.util.Map
/ * *
* encapsulate the action attribute into a class
* @ author 87077
*
, /
Public class ActionConfig {
/ / the name that action calls to others
Private String name
/ / action class in action corresponding program
Private String clazzName
/ / methods in action
Private String method
/ / the returned result is unknown, so use Map
Private Map resultMap = new HashMap ()
Public ActionConfig () {
}
Public ActionConfig (String name, String clazzName, String method, Map resultMap) {
This.name=name
This.clazzName=clazzName
This.method=method
This.resultMap=resultMap
}
Public String getName () {
Return name
}
Public String getClazzName () {
Return clazzName
}
Public String getMethod () {
Return method
}
Public Map getResultMap () {
Return resultMap
}
Public void setName (String name) {
This.name = name
}
Public void setClazzName (String clazzName) {
This.clazzName = clazzName
}
Public void setMethod (String method) {
This.method = method
}
Public void setResultMap (Map resultMap) {
This.resultMap = resultMap
}
}
With javabean, we start parsing the xml file.
Package org.zxh.util
Import java.io.File
Import java.util.List
Import java.util.Map
Import org.dom4j.Document
Import org.dom4j.DocumentException
Import org.dom4j.Element
Import org.dom4j.io.SAXReader
/ * *
* parsing xml configuration files using dom4j
*
* @ author 87077
*
, /
Public class ConfigUtil {
/ * *
* @ param fileName
* Files to be parsed
* @ param map
* storing parsed data
, /
Public static void parseConfigFile (String fileName
Map map) {
SAXReader reader = new SAXReader ()
Try {
Document doc = reader.read (new File ("D:\\ zxh\\ soft\\ apache-tomcat-7.0.70\\ apache-tomcat-7.0.70\\ webapps\\ MyStruts\\ WEB-INF\\ classes\\ struts.xml"))
Element root = doc.getRootElement ()
List list = root.selectNodes ("package/action")
For (Element element: list) {
/ / encapsulated into an ActionConfig object and saved in map
ActionConfig config = new ActionConfig ()
/ / get the value in action
String name = element.attributeValue ("name")
String clazzName = element.attributeValue ("class")
String method = element.attributeValue ("method")
/ / pass the value into javabean
Config.setName (name)
Config.setClazzName (clazzName)
/ / if the execution method is not set to execute the default
If (method = = null | | ".equals (method)) {
Method = "execute"
}
Config.setMethod (method)
/ / continue to get the return method in action.
List resultList = element.selectNodes ("result")
For (Element resultElement: resultList) {
String resultName = resultElement.attributeValue ("name")
String urlPath = resultElement.getTextTrim ()
If (resultName = = null | | ".equals (resultName)) {
ResultName = "success"
}
Config.getResultMap () .put (resultName urlPath)
}
Map.put (name, config)
}
} catch (DocumentException e) {
/ / TODO Auto-generated catch block
E.printStackTrace ()
}
}
}
Now let's go back to the filter, and the above two classes are used to parse xml. So in the init method in Filter, we can put the parsed data into our global Map.
@ Override
Public void init (FilterConfig arg0) throws ServletException {
/ / initialization process of TODO Auto-generated method stub filter
/ / obtain the xml configuration file
String webRootPath = getClass () .getClassLoader ()
.getResource ("struts.xml") .getPath ()
/ / parsing the xml configuration file into map
ConfigUtil.parseConfigFile (webRootPath, map)
}
Implementation of filter
The filter is actually executed at the beginning of the doFilter method.
Public void doFilter (ServletRequest arg0, ServletResponse arg1
FilterChain arg2)
The doFilter () method is similar to the service () method of the Servlet interface. When the client requests the target resource, the container invokes the doFilter () method of the filter associated with the target resource. Parameters request and response are the requests and corresponding objects passed by the last Filter of the web container or Filter chain The parameter chain represents the object of the current Filter chain. After a specific operation is completed, you can call the chain.doFilter (request,response) method of the FilterChain object to deliver the request to the next Filter or target Servlet program in the Filter chain for processing, or you can return the response information directly to the client, or use the forward () and include () methods of RequestDispatcher, and the sendRedirect () method of HttpServletResponse to direct the request to other resources. The request and response parameters of this method are of the types ServletRequest and ServletResponse, that is, the use of the filter does not depend on the specific protocol.
Get the request domain and response domain as well as the Filter chain, and set the code to prevent garbled
/ / for http requests, restore the request and response types to HTTP types
HttpServletRequest request = (HttpServletRequest) arg0
HttpServletResponse response = (HttpServletResponse) arg1
/ / set the coding problem of request and response
Request.setCharacterEncoding ("UTF-8")
Response.setCharacterEncoding ("UTF-8")
Get the request address
/ / get the request path
String url = request.getServletPath ()
By request to determine whether to intercept and filter requests for this address, this article filters all requests ending in .action by default.
/ / request address filtering, if it does not end in .action
If (! url.endsWith (".action")) {
/ / not the release of .action
Arg2.doFilter (request, response)
Return
}
Looking at the format in which I put the data in the xml file into Map, you can see that I am talking about putting the whole javabean into the name named action in Map. So next I'm going to that name (that is, the login in the request)
/ / resolve the request path
Int start = url.indexOf ("/")
Int end = url.lastIndexOf (. ")
String path=url.substring (start+1,end)
/ / match to the corresponding ActionConfig class through path. All the action information has been parsed here.
ActionConfig config = map.get (path)
/ / if the match is not successful, the error message of the page cannot be found
If (config==null) {
Response.setStatus (response.SC_NOT_FOUND)
Return
}
Now that you have the ActionConfig class, and all the information about action is stored in this javabean class, the following things are easy to do. The following is just the knowledge that will be used in reflection. After we get the name of the real action class, we need to get the entity class of the action by name.
/ / obtain the completed class name through ActionConfig
String clazzName=config.getClazzName ()
/ / instantiate the Action object and prompt an error message if it does not exist
Object action = getAction (clazzName)
If (action==null) {
/ / indicates that the action is incorrect and does not occupy the corresponding action class in the configuration file.
Response.setStatus (response.SC_NOT_FOUND)
Return
}
The request parameter is obtained and assigned to action
Before executing the method of action, it is necessary to get the parameters in request and assign them. This is the real interaction.
Public static void requestToAction (HttpServletRequest request, Object action)
Class the incoming action object and get the attributes under the action entity
Class
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.