当前位置:网站首页>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 (●'◡'●)
边栏推荐
- 2022-7-6 Leetcode27. Remove the element - I haven't done the problem for a long time. It's such an embarrassing day for double pointers
- Cargo placement problem
- 【AI实战】应用xgboost.XGBRegressor搭建空气质量预测模型(二)
- Oracle advanced (V) schema solution
- 3D detection: fast visualization of 3D box and point cloud
- 干货|总结那些漏洞工具的联动使用
- DID登陆-MetaMask
- 118. 杨辉三角
- Huawei image address
- Dry goods | summarize the linkage use of those vulnerability tools
猜你喜欢

2022-7-7 Leetcode 34. Find the first and last positions of elements in a sorted array

XML文件的解析操作

Navicat运行sql文件导入数据不全或导入失败

为租客提供帮助

"New red flag Cup" desktop application creativity competition 2022

室内ROS机器人导航调试记录(膨胀半径的选取经验)

2022-7-6 Leetcode27.移除元素——太久没有做题了,为双指针如此狼狈的一天

Indoor ROS robot navigation commissioning record (experience in selecting expansion radius)

566. 重塑矩阵

MySQL error 28 and solution
随机推荐
LeetCode简单题分享(20)
Wired network IP address of VMware shared host
call undefined function openssl_ cipher_ iv_ length
docker部署oracle
. Net core about redis pipeline and transactions
MySQL "invalid use of null value" solution
postgresql array类型,每一项拼接
Regular expression integer positive integer some basic expressions
现在网上开户安全么?那么网上开户选哪个证券公司?
【日常训练】648. 单词替换
Toraw and markraw
118. 杨辉三角
Laravel form builder uses
Navicat run SQL file import data incomplete or import failed
Is the spare money in your hand better to fry stocks or buy financial products?
The delivery efficiency is increased by 52 times, and the operation efficiency is increased by 10 times. See the compilation of practical cases of financial cloud native technology (with download)
What are the principles for distinguishing the security objectives and implementation methods that cloud computing security expansion requires to focus on?
Vmware 与主机之间传输文件
Supply chain supply and demand estimation - [time series]
Use day JS let time (displayed as minutes, hours, days, months, and so on)