Tabla de contenido
Reglas de sintaxis de nomenclatura de elementos de etiqueta:
En segundo lugar, el análisis de XML
1. Tres ubicaciones de configuración y métodos de lectura de archivos de configuración en Java
Crear modelos: ConfigModel, ActionModel, ForwardModel
1. dtd
1. Comprender xml
Pregunta: ¿Qué es xml? ¿Por qué estudiar xml? El papel de xml?
DTD significa Definición de tipo de documento en inglés y significa "definición de clase de documento" en chino.
DTD es un conjunto de reglas gramaticales sobre etiquetas, que establece qué etiquetas se pueden usar en XML, qué etiquetas tienen atributos y cuál es el orden en que aparecen las etiquetas.
DTD tiene dos tareas:
1. Ayuda para escribir código legal;
2. Deje que el navegador muestre el código correctamente.
- XML significa Lenguaje de marcado extensible ( Extensible Markup Language )
- XML es un lenguaje de marcas , muy parecido a HTML
- XML está diseñado para transmitir datos , no mostrarlos
- Las etiquetas XML no están predefinidas. Necesita definir sus propias etiquetas .
- XML está diseñado para ser autodescriptivo .
- XML es una recomendación W3C
Archivo de configuración mvc de aprendizaje posterior
Con el fin de facilitar el intercambio de datos y la comunicación entre diferentes aplicaciones y diferentes plataformas.
Función: transmisión de datos de red.
almacenamiento de datos
archivo de configuración
2, formato de sintaxis xml
- tiene exactamente un elemento raíz
- las etiquetas xml distinguen entre mayúsculas y minúsculas
- Uso correcto de etiquetas de cierre, etiquetas anidadas
- Usar nombres de etiquetas válidos
- definir propiedades válidas
- Etiqueta de inicio (etiqueta abierta): <nombre de etiqueta>
- Etiqueta de cierre (etiqueta de cierre): </tagname>
Por ejemplo: <nombre>Zhangsan</nombre>
3. Definición de elementos
Reglas de sintaxis de nomenclatura de elementos de etiqueta:
1. El nombre puede contener letras, números y otros caracteres
2. El nombre no puede comenzar con números o signos de puntuación
3. El nombre no puede comenzar con los caracteres "xml" (o XML, Xml)
4. El nombre no puede contener espacios y no puede contienen dos puntos (: )
5. Los nombres distinguen entre mayúsculas y minúsculas
Añadir declaración DTD en XML <!DOCTYPE root[]>
Clasificación de elementos:
<!ELEMENT nombre-elemento (#PCDATA)> ------------Elemento de texto
<!ELEMENT nombre-elemento EMPTY> ----------------vacío Elemento
<!ELEMENT nombre-elemento (e1,e2)> ---------------- Elementos mixtos
Límites de elementos:
con ( , ) no ( | )
Veces: 0 o 1------?
0~N-------*
1~N-------+
//案例
<!DOCTYPE persons[
<!ELEMENT persons (person+)>
<!ELEMENT person (name,age,contact,br*)>
<!ELEMENT name (#PCDATA)>
<!ELEMENT age (#PCDATA)>
<!ELEMENT contact (phone|email)>
<!ELEMENT br EMPTY>
]>
3. Definición de atributo
gramática:
<!ATTLIST element-name
att_name type desc
>
Tipo de propiedad :
ID (masculino|femenino) Referencia CDATA IDREF
Descripción de propiedad:
#REQUERIDO Obligatorio
#IMPLED no requerido
'Valor predeterminado' (solo cuando el tipo es (masculino|femenino), desc puede usar el método de valor predeterminado)
//案例
<!ATTLIST person
pid ID #REQUIRED
sex (男|女) '男'
qq CDATA #IMPLIED
parent IDREF #IMPLIED
>
En segundo lugar, el análisis de XML
1. Tres ubicaciones de configuración y métodos de lectura de archivos de configuración en Java
同包:Demo1.class.getResourceAsStream(" db.properties ");
Ruta raíz : Demo1.class.getResourceAsStream(" /db.properties ");
Ruta segura de WIN-INF : context.getResourceAsStream(" /WEB-INF/db.properties ");
2, el uso de dom4j
Métodos comunes de dom4j: selectNodes selectSingleNode atributo valor getText
archivo xml de configuración
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE config[
<!ELEMENT config (action*)>
<!ELEMENT action (forward*)>
<!ELEMENT forward EMPTY>
<!ATTLIST action
path CDATA #REQUIRED
type CDATA #REQUIRED
>
<!ATTLIST forward
name CDATA #REQUIRED
path CDATA #REQUIRED
redirect (true|false) "false"
>
]>
<config>
<action path="/studentAction" type="org.lisen.mvc.action.StudentAction">
<forward name="students" path="/students/studentList.jsp" redirect="false"/>
</action>
<action path="/studentAction1" type="org.lisen.mvc.action.StudentAction">
<forward name="students1" path="/students/studentList.jsp" redirect="false"/>
</action>
<action path="/studentAction2" type="org.lisen.mvc.action.StudentAction">
<forward name="students2" path="/students/studentList.jsp" redirect="false"/>
</action>
</config>
escribe el método get
public class Demo {
public static void main(String[] args) throws Exception {
InputStream stream = Demo.class.getResourceAsStream("/config.xml");
SAXReader reader = new SAXReader();// SAXReader 读取xml文件解析
Document document = reader.read(stream);// 文档
Element element = document.getRootElement();// 获取根元素
List<Element> actions = element.selectNodes("/config/action");
for (Element action : actions) {
String path = action.attributeValue("path");
String type = action.attributeValue("type");
List<Element> forwards = action.selectNodes("forward");
for (Element forward : forwards) {
String name = forward.attributeValue("name");
String fpath = forward.attributeValue("path");
String redirect = forward.attributeValue("redirect");
System.out.println("name=" + name);
System.out.println("fpath=" + fpath);
System.out.println("redirect=" + redirect);
}
System.out.println("path=" + path);
System.out.println("type=" + type);
System.out.println("---------------");
}
}
}
Los resultados son los siguientes:
3. Modelado
1. Modelado XML
Crear modelos: ConfigModel, ActionModel, ForwardModel
Modelo de configuración
public class ConfigModel {
private Map<String, ActionModel> actionMap = new HashMap<>();
public void put(ActionModel action) {
if (actionMap.containsKey(action.getPath())) {
throw new ActionDuplicateDefinitionException("action path:" + action.getPath() + " 不能重复");
}
actionMap.put(action.getPath(), action);
}
public ActionModel find(String path) {
if (!actionMap.containsKey(path)) {
throw new ActionNotFoundException("action path:" + path + "没有找到");
}
return actionMap.get(path);
}
}
Modelo de acción
public class ActionModel {
private String path;
private String type;
private Map<String, ForwardModel> forwardMap = new HashMap<>();
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public void put(ForwardModel forward) {
if (forwardMap.containsKey(forward.getName())) {
throw new ForwardDuplicateDefinitionException("forward name:" + forward.getName() + "不能重复");
}
forwardMap.put(forward.getName(), forward);
}
public ForwardModel find(String name) {
if (!forwardMap.containsKey(name)) {
throw new ForwardNotFoundException("forward name:" + name + "不存在");
}
return forwardMap.get(name);
}
@Override
public String toString() {
return "ActionModel [path=" + path + ", type=" + type + "]";
}
}
ForwardModel
public class ForwardModel {
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;
}
public void setRedirect(String redirect) {
if ("true".equals(redirect) || "false".equals(redirect)) {
this.redirect = Boolean.valueOf(redirect);
} else {
throw new RuntimeException("属性redirect的值必须位ture或者false");
}
}
@Override
public String toString() {
return "ForwardModel [name=" + name + ", path=" + path + ", redirect=" + redirect + "]";
}
}
2. Modo de fábrica
Analizar y generar modelos
ConfigModelFactory
public final class ConfigModelFactory {
private ConfigModelFactory() {
}
private static ConfigModel config = new ConfigModel();
// 静态代码块,在类加载的时候只执行一次,在这里完成config.xml文件的解析和Config相关的
// 模型的建立,这样在整个系统运行阶段只会解析一次
static {
try {
InputStream in = ConfigModelFactory.class.getResourceAsStream("/config.xml");
SAXReader reader = new SAXReader();
Document doc = reader.read(in);
Element ce = doc.getRootElement();
List<Element> actions = ce.selectNodes("action");
for (Element action : actions) {
String path = action.attributeValue("path");
String type = action.attributeValue("type");
ActionModel actionModel = new ActionModel();
actionModel.setPath(path);
actionModel.setType(type);
List<Element> forwards = action.selectNodes("forward");
for (Element f : forwards) {
String name = f.attributeValue("name");
String fpath = f.attributeValue("path");
String redirect = f.attributeValue("redirect");
ForwardModel forwardModel = new ForwardModel();
forwardModel.setName(name);
forwardModel.setPath(fpath);
forwardModel.setRedirect(redirect);
actionModel.put(forwardModel);
}
config.put(actionModel);
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
// 获取系统的Config配置对象
public static ConfigModel getConfig() {
return config;
}
public static void main(String[] args) {
ConfigModel config = ConfigModelFactory.getConfig();
ActionModel action = config.find("/studentAction");
System.out.println(action);
ForwardModel forward = action.find("students");
System.out.println(forward);
}
}
Los resultados son los siguientes: