Service scenario: Generates XML online using scheduled tasks, stores it in the project root directory, accesses the interface, and downloads it to the local PC

The techniques involved are: 1. Scheduled tasks (I'm using Quartz here) 2. Generating XML files 3Copy the code

1. Timed tasks (I’m using Quartz here)

Here I just post my code part for the record, and I will analyze the scheduled task in detail later. This is the traditional SSM framework, so configure the relevant content in the configuration file

<bean id="createSiteMapXML" class="com.testdaily.web.util.createSiteMapXMLJob"/ > <! The above bean is the actual code that needs to be run to generate the XML file"sendGroupMsgJobDetail" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
        <property name="group" value="send_group_msg_job_detail"/>
        <property name="name" value="send_group_msg_job_detail_name"/ > <! --false: start a new task after the previous task has finished --> <property name="concurrent" value="false"/>
        <property name="targetObject">
            <ref bean="createSiteMapXML"/ > <! </property> <property name="targetMethod"> <value>SiteMapXML</value><! </property> </bean> <! -- Scheduling trigger --> <bean id="sendMsgTrigger"
          class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
        <property name="name" value="send_msg_trigger_name"/>
        <property name="group" value="send_msg_trigger"/>
        <property name="jobDetail">
            <ref bean="sendGroupMsgJobDetail" />
        </property>
        <property name="cronExpression"> <value>0 0 2 * * ? </value><! -- This is a timed task, which means that the timer is executed at 2 am --> <! --<value>*/30 * * * * ? </value>--> </property> </bean> <! -- Scheduling factory --> <bean id="scheduler" class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
        <property name="triggers">
            <list>
                <ref bean="sendMsgTrigger"/ > <! </list> </property> </bean>Copy the code

2. Generate XML files

There are four ways to parse XML files in Java, namely DOM, SAX, JDOM and DOM4J. The first two of these four ways are the system’s own, and the last two need to import JAR packages, which must have a basic understanding of XML files.

XML file is for different programs, data transfer between different platforms, different data platform data sharing function. It is stored in a tree structure.

<? xml version="1.0" encoding="UTF-8"? > <bookstore> <book id="1" size="medium"</name> <price>89</price> <language> English </language> <year>2004</year> </book> <book id="2" size="lower"> <name> <price>65</price> <language> Japanese </language> <year>2014</year> </book> <book id="3" size="large"</name> <price>99</price> <language> 英 文</language> <year>2015</year> </book> </bookstore>Copy the code

This is a simple XML file, the first line to note that this is the writing standards, and the code format for utf-8, and GBK, etc., can be modified here behind each node has a corresponding to the end node, in < > id and the size is the attribute of the node, pay attention to the need “, “its internal nodes can be understood as a child node.

Named constant nodeName() return value nodeValue() return value Element ELEMENT_NODE Element Name null Attr ATTRIBUTE_NODE attribute name Property value text TEXT_NODE#text The content of the node
Copy the code

So this is a pretty important table, and I don’t know why I set it up like this, but it’s kind of annoying to remember, especially when you’re parsing DOM, right

Let’s start by Posting the DOM code we found online:

package project_xml;
 
import java.io.File;
import java.io.IOException;
 
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Result;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
 
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
 
public class xml_dom {
 	public static void main(String[] args) {
	    xml_dom xml_dom1=new xml_dom();
	   xml_dom1.xml_dom_parse();
	    //xml_dom1.creat_xml();
	}
	
	 public void xml_dom_parse() {
		   DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
			try {
				DocumentBuilder db=dbf.newDocumentBuilder();
				Document docu=db.parse("book.xml"); / / get all the books node NodeList booklist = docu. GetElementsByTagName ("book");
	           for(int i =0; i<booklist.getLength(); i++){ Node book_item=booklist.item(i); System.out.println("The first"+(i+1)+"Book"); NamedNodeMap node_att=book_item.getAttributes(); <span style= "max-width: 100%; clear: both"font-family: Arial, Helvetica, sans-serif;"> in the NamedNodeMap < / span >for(int j=0; j<node_att.getLength(); j++){ Node node=node_att.item(j); System.out.print(node.getNodeName()+":"+node.getNodeValue()+"");
	           		System.out.println();
	           	}
	           	NodeList book_child=book_item.getChildNodes();
	           	for(int k=0; k<book_child.getLength(); k++){ Node book_child_ele=book_child.item(k);if(book_child_elel.getNodeType ()== node.element_node){// Many Spaces will be printed if not, since text is also a Node type,  //System.out.println(book_child_ele.getNodeName()+":"+book_child_ele.getFirstChild().getNodeValue()); //// text system.out.println (book_child_ele.getnodename ()+) <name></name":"+book_child_ele.getTextContent());
	           		}
	           	}
	           	System.out.println("That's the number one."+(i+1)+"Book");
	           	
	           }
			} catch (ParserConfigurationException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (SAXException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	 
	 public void creat_xml() { try { DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance(); DocumentBuilder db=dbf.newDocumentBuilder(); Document document=db.newDocument(); // Standalone can be set totrue, so as not to show, say mean don't need to show document. The document setXmlStandalone (true);
			Element bookstore=document.createElement("bookstore");
			Element book=document.createElement("book");
			Element name=document.createElement("name");
			name.setTextContent("Andersen's Fairy Tales");
			book.setAttribute("id"."1");
			book.setAttribute("size"."lower");
			book.appendChild(name);
			bookstore.appendChild(book);
			document.appendChild(bookstore);
			TransformerFactory tf=TransformerFactory.newInstance();
			Transformer transformer=tf.newTransformer();
			transformer.setOutputProperty(OutputKeys.INDENT, "yes");
			transformer.transform(new DOMSource(document), new StreamResult(new File("book1.xml"))); } catch (ParserConfigurationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (TransformerConfigurationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (TransformerException e) { // TODO Auto-generated catch block e.printStackTrace(); }}}Copy the code

DOM4J is used in my project. Here is some code:

Try {/ / 1, to create a document object document document. = DocumentHelper createDocument (); // create root Element RSS = document.addelement ("urlset"); // add version attribute to RSS node // rss.addattribute ("version"."1.0"); Element postingChannel = rss.addelement ("url");
            Element postingtitle = postingchannel.addElement("loc");
            postingtitle.setText("http://www.shenxuanxiao.cn/article-"+postingId+".html");
            Element postingtitle1 = postingchannel.addElement("lastmod");
            postingtitle1.setText(time);
            Element postingtitle2 = postingchannel.addElement("changefreq");
            postingtitle2.setText("daily");
            Element postingtitle3 = postingchannel.addElement("priority");
            postingtitle3.setText("0.8"); / / 5, set up to generate XML format OutputFormat format. = OutputFormat createPrettyPrint (); // Set format.setencoding ("UTF-8");
            String filePath= ClassUtils.getDefaultClassLoader().getResource("").getPath(); File File = new File(filePath+"SiteMap.xml"); XMLWriter writer = new XMLWriter(new FileOutputStream(file), format); SetEscapeText (writer.setescapetext ())false);
            writer.write(document);
            writer.close();
            System.out.println("Sitemap.xml generated successfully");
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("Failed to generate sitemap.xml");
        }    
Copy the code

To learn about the other three, read: juejin.cn/post/684490…

3, download the relative path of the project files

According to business requirements, I here is direct access interface, download project internal files, all just need to determine the path of the file, the following is the implementation code

@RequestMapping(value = "/downloadSiteMapXML", method = {RequestMethod.GET})
    @ResponseBody
    public void downloadSiteMapXML(HttpServletRequest request, HttpServletResponse response  ){
        try{
            String filePath= ClassUtils.getDefaultClassLoader().getResource("").getPath(); // The root directory of the project String resultFileName ="SiteMap.xml"; ResultFileName = URLEncoder. Encode (resultFileName,"UTF-8"); / / set the character set response. SetCharacterEncoding ("UTF-8");
            response.setHeader("Content-disposition"."attachment; filename="+ resultFileName); // Set output header response.setContentType("application/msexcel"); // Define output type // Input stream: local file path DataInputStreamin = new DataInputStream(
                    new FileInputStream(new File(filePath+ "SiteMap.xml"))); OutputStream out = response.getOutputStream(); // Output file int bytes = 0; byte[] bufferOut = new byte[1024];while((bytes = in.read(bufferOut)) ! = -1) { out.write(bufferOut, 0, bytes); } out.close(); in.close(); } catch(Exception e){ e.printStackTrace(); response.reset(); try { OutputStreamWriter writer = new OutputStreamWriter(response.getOutputStream(),"UTF-8");
                String data = ""; writer.write(data); writer.close(); } catch (IOException e1) { e1.printStackTrace(); }}}Copy the code