当前位置:网站首页>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 (●'◡'●)
边栏推荐
- What are the principles for distinguishing the security objectives and implementation methods that cloud computing security expansion requires to focus on?
- 2022-7-6 beginner redis (I) download, install and run redis under Linux
- js 获取当前时间 年月日,uniapp定位 小程序打开地图选择地点
- AI talent cultivation new ideas, this live broadcast has what you care about
- Thread pool reject policy best practices
- 2022-7-6 Leetcode 977.有序数组的平方
- Social responsibility · value co creation, Zhongguancun network security and Information Industry Alliance dialogue, wechat entrepreneur Haitai Fangyuan, chairman Mr. Jiang Haizhou
- Navicat run SQL file import data incomplete or import failed
- 2022-7-7 Leetcode 844.比较含退格的字符串
- 3D Detection: 3D Box和点云 快速可视化
猜你喜欢
js 获取当前时间 年月日,uniapp定位 小程序打开地图选择地点
社会责任·价值共创,中关村网络安全与信息化产业联盟对话网信企业家海泰方圆董事长姜海舟先生
2022-7-7 Leetcode 34. Find the first and last positions of elements in a sorted array
作战图鉴:12大场景详述容器安全建设要求
干货|总结那些漏洞工具的联动使用
AI人才培育新思路,这场直播有你关心的
室內ROS機器人導航調試記錄(膨脹半徑的選取經驗)
Social responsibility · value co creation, Zhongguancun network security and Information Industry Alliance dialogue, wechat entrepreneur Haitai Fangyuan, chairman Mr. Jiang Haizhou
Use day JS let time (displayed as minutes, hours, days, months, and so on)
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
随机推荐
Vmware 与主机之间传输文件
PHP中用下划线开头的变量含义
SSRF vulnerability file pseudo protocol [netding Cup 2018] fakebook1
为租客提供帮助
请问,在使用flink sql sink数据到kafka的时候出现执行成功,但是kafka里面没有数
118. Yanghui triangle
Realization of search box effect [daily question]
Data refresh of recyclerview
Redis只能做缓存?太out了!
Enregistrement de la navigation et de la mise en service du robot ROS intérieur (expérience de sélection du rayon de dilatation)
请问,PTS对数据库压测有好方案么?
Selenium库
Is the spare money in your hand better to fry stocks or buy financial products?
Laravel5 call to undefined function openssl cipher iv length() 报错 PHP7开启OpenSSL扩展失败
请问,我kafka 3个分区,flinksql 任务中 写了 join操作,,我怎么单独给join
AI人才培育新思路,这场直播有你关心的
【网络安全】sql注入语法汇总
Wired network IP address of VMware shared host
How to check the ram and ROM usage of MCU through Keil
Seven propagation behaviors of transactions