当前位置:网站首页>Hands on Teaching: XML modeling
Hands on Teaching: XML modeling
2022-07-07 14:04:00 【Xiao afai_】
Previous review :XML File parsing operation _ Little Alfie _ The blog of -CSDN Blog
XML Is a commonly used configuration file , But in the last article XML The code of the file cannot be rewritten every time it is needed , Modeling in this issue (OOP thought ) Is a good solution ( Will parse XML The code of the file becomes object-oriented data )
This issue is wonderful ( From the first step to the last step, teach hand in hand )
Catalog
1、 Construction of environment
2、 The import related jar package
3、 Build related packages and MVC Configuration file for
4、 adopt config.xml Format establishment related model classes
5、 Observe MVC Configuration file for config.xml To write code
7、 Factory ConfigModelFactory To write
XML Modeling steps
1、 Construction of environment
(1) Select a workspace and click Launch
(2.1) Click preferences
(2.2) Enter the workspace and set the encoding format to UTF-8
(2.3) take JSP The encoding format of is also set to UTF-8
(3.1) New dynamic project ( The project name can be all lowercase )
(3.2) To configure tomcat Environmental Science
Choose your computer tomcat The file path of the server
(3.3) To configure JDK
Choose your computer JDK File path , Usually placed in C disc
Finally, you can set the font to the size and format you want
(4) Generate XML The configuration file
2、 The import related jar package
- To import jar package
- In the project build path after
3、 Build related packages and MVC Configuration file for
Package name specification :com/org. Company name . Project name . Module name
- com.xyf.mvc.framework: The framework package
- resources Files under the source package : Put custom MVC Configuration file for config.xml
- config.xml Code display ( Write a follow-up package 、 class 、 The basis of the code !)
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE config>
<config>
<action type="org.lisen.mvc.action.StudentAction" path="/studentAction">
<forward path="/students/studentList.jsp" redirect="false" name="students"/>
</action>
</config>
4、 adopt config.xml Format Establish relevant model classes
Class name specification : Hump nomenclature with capital letters
Model class naming :
- ConfigModel:Config Node model
- ActionModel:Action Node model
- ForwardModel:Farword Node model
5、 Custom exception
Exception class naming + Code writing ( The key is the exception name )
- ActionDuplicateDefinitionException:Action There is a duplicate definition exception in the element
public class ActionDuplicateDefinitionException extends RuntimeException {
public ActionDuplicateDefinitionException() {
super();
}
public ActionDuplicateDefinitionException(String msg) {
super(msg);
}
public ActionDuplicateDefinitionException(String msg, Throwable c) {
super(msg, c);
}
}
- ActionNotFoundException:
public class ActionNotFoundException extends RuntimeException {
public ActionNotFoundException() {
super();
}
public ActionNotFoundException(String msg) {
super(msg);
}
public ActionNotFoundException(String msg, Throwable c) {
super(msg, c);
}
}
- ForwardDuplicateDefinitionException:Forward There is a duplicate definition exception in the element
public class ForwardDuplicateDefinitionException extends RuntimeException {
public ForwardDuplicateDefinitionException() {
super();
}
public ForwardDuplicateDefinitionException(String msg) {
super(msg);
}
public ForwardDuplicateDefinitionException(String msg, Throwable c) {
super(msg, c);
}
}
- ForwardNotFoundException:
public class ForwardNotFoundException extends RuntimeException {
public ForwardNotFoundException() {
super();
}
public ForwardNotFoundException(String msg) {
super(msg);
}
public ForwardNotFoundException(String msg, Throwable c) {
super(msg, c);
}
}
5、 Observe MVC Configuration file for config.xml To write code
Observe config.xml You know
- One config There can be multiple nodes action node
- action Nodes have type and path Two attributes
- action Node has forward node
- forward Nodes have three attributes ......
6、 Model class code writing
The root node ConfigModel class
public class ConfigModel {
// One config There can be multiple nodes action node
// discharge key==path and value==ActionModel class / object : Find action
// initialization :new HashMap<>()
private Map<String, ActionModel> actionMap=new HashMap<>();
/**
* take path Put in key, keep path No repetition
* Traverse ActionModel object , adopt ActionModel Object acquisition path attribute
* @param Pass in ActionModel This class / object
*/
public void put(ActionModel action) {
if(actionMap.containsKey(action.getPath())) {
throw new ActionDuplicateDefinitionException("Action path= "+action.getPath()+" Duplicate definition");
}
actionMap.put(action.getPath(), action);
}
/**
* look for path
* @param Pass in path
* @return Can't find path Throw an exception , Find and return path
*/
public ActionModel find(String path) {
if(!actionMap.containsKey(path)) {
throw new ActionNotFoundException("Action path ="+path+" not found");
}
return actionMap.get(path);
}
}
ActionModel class
public class ActionModel {
// There are two nodes
private String type;
private String path;
// Contains elements forward: adopt action find forward
private Map<String, ForwardModel> forwardMap =new HashMap<>();
// take name Put in key, keep name No repetition
public void put(ForwardModel forward) {
if(forwardMap.containsKey(forward.getName())) {
throw new ForwardDuplicateDefinitionException("forward name = "+forward.getName()+" DuplicateDefinition");
}
forwardMap.put(forward.getName(), forward);
}
// look for name
public ForwardModel find(String name) {
if(!forwardMap.containsKey(name)) {
throw new ForwardNotFoundException("forward name ="+name+" not found");
}
return forwardMap.get(name);
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
@Override
public String toString() {
return "ActionModel [type=" + type + ", path=" + path + ", forwardMap=" + forwardMap + "]";
}
}
ForwardModel class
public class ForwardModel extends RuntimeException{
// Three attributes
private String name;
private String path;
private boolean redirect;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public boolean isRedirect() {
return redirect;
}
public void setRedirect(boolean redirect) {
this.redirect = redirect;
}
// take redirect Convert string in to boolean Method of type
public void setRedirect(String redirect) {
//this= The current class
this.redirect =Boolean.valueOf(redirect);
}
@Override
public String toString() {
return "ForwardModel [name=" + name + ", path=" + path + ", redirect=" + redirect + "]";
}
}
7、 Factory ConfigModelFactory To write
Write factory class ConfigModelFactory The purpose of is to use the singleton pattern in this class , And only for XML Read the contents of the file once , After reading, put it into the model object written in the previous step
/**
* Single instance factory class
* Let's analyze XML The code of is executed only once
*/
@SuppressWarnings("unchecked")
public final class ConfigModelFactory {
// The singleton pattern
private ConfigModelFactory() {}
// Root node model
private static ConfigModel config = new ConfigModel();
// Read only once config Data in , And fill in the model
static {
try {
// read
InputStream is=XmlReader.class.getResourceAsStream("/config.xml");
SAXReader reader=new SAXReader();
Document doc = reader.read(is);
// Get the node under the root element through the root element action(xml The number structure in !)
Element rootElement = doc.getRootElement();
List<Element> actions = rootElement.selectNodes("action");
for (Element e : actions) {
String path = e.attributeValue("path");
String type = e.attributeValue("type");
// Put it in the model
ActionModel action=new ActionModel();
action.setPath(path);
action.setType(type);
// adopt action Element acquisition actions The nodes below forward
List<Element> forward1 = e.selectNodes("forward");
for (Element f : forward1) {
String name = f.attributeValue("name");
String fPath = f.attributeValue("path");
String redirect = f.attributeValue("redirect");
// Put it in the model
ForwardModel forward=new ForwardModel();
forward.setName(name);
forward.setPath(fPath);
forward.setRedirect(redirect);
// take forward Put in action
action.put(forward);
}
// After the cycle is completed action Put in the root node
config.put(action);
}
} catch (DocumentException e) {
e.printStackTrace();
}
}
public static ConfigModel getConfig() {
return config;
}
// test
public static void main(String[] args) {
ConfigModel config = ConfigModelFactory.getConfig();
// adopt action Medium path(xml There is /) look for action
ActionModel action = config.find("/studentAction");
System.out.println(action);
// adopt forward Medium name look for forward,xml No middle /
ForwardModel forward = action.find("students");
System.out.println(forward);
}
}
Summary : It's right to be here config.xml The modeling operation of the file has been completed , But there are still some small bug, For example, if you are in config.xml Of path No incoming from “/”, Will also successfully model , This is obviously not right , So please look forward to the next article (●'◡'●)
边栏推荐
- 【网络安全】sql注入语法汇总
- TPG x AIDU | AI leading talent recruitment plan in progress!
- 社会责任·价值共创,中关村网络安全与信息化产业联盟对话网信企业家海泰方圆董事长姜海舟先生
- 最长上升子序列模型 AcWing 1014. 登山
- 实现IP地址归属地显示功能、号码归属地查询
- 供应链供需预估-[时间序列]
- "Song of ice and fire" in the eleventh issue of "open source Roundtable" -- how to balance the natural contradiction between open source and security?
- 566. Reshaping the matrix
- 2022-7-6 Leetcode 977. Square of ordered array
- 请问,redis没有消费消息,都在redis里堆着是怎么回事?用的是cerely 。
猜你喜欢
室內ROS機器人導航調試記錄(膨脹半徑的選取經驗)
566. 重塑矩阵
flask session伪造之hctf admin
XML文件的解析操作
Introduction to database system - Chapter 1 introduction [conceptual model, hierarchical model and three-level mode (external mode, mode, internal mode)]
[fortress machine] what is the difference between cloud fortress machine and ordinary fortress machine?
交付效率提升52倍,运营效率提升10倍,看《金融云原生技术实践案例汇编》(附下载)
Supply chain supply and demand estimation - [time series]
118. 杨辉三角
带你掌握三层架构(建议收藏)
随机推荐
[1] ROS2基础知识-操作命令总结版
[untitled]
118. Yanghui triangle
Redis 核心数据结构 & Redis 6 新特性详
Leecode3. Longest substring without repeated characters
Is the compass stock software reliable? Is it safe to trade stocks?
SSRF漏洞file伪协议之[网鼎杯 2018]Fakebook1
Learning breakout 2 - about effective learning methods
SSRF vulnerability file pseudo protocol [netding Cup 2018] fakebook1
Introduction to database system - Chapter 1 introduction [conceptual model, hierarchical model and three-level mode (external mode, mode, internal mode)]
干货|总结那些漏洞工具的联动使用
Redis can only cache? Too out!
【日常训练--腾讯精选50】231. 2 的幂
Laravel5 call to undefined function OpenSSL cipher IV length() error php7 failed to open OpenSSL extension
The reason why data truncated for column 'xxx' at row 1 appears in the MySQL import file
call undefined function openssl_cipher_iv_length
648. Word replacement: the classic application of dictionary tree
Move base parameter analysis and experience summary
Realization of search box effect [daily question]
Laravel5 call to undefined function openssl cipher iv length() 报错 PHP7开启OpenSSL扩展失败