Syntaxhighlighter2.1.364 dynamic code highlighting

Source: Internet
Author: User
Tags blank page

In the Application Scenario, upload an XML file for a file and Click Preview. In this case, upload the XML file to the server, read the XML file, format the returned JSON data, obtain the JSON file, load it to the page, and use the syntaxhighlighter plug-in to dynamically highlight the XML code uploaded in this section. The key code is as follows:

 

First, upload and rename the file, and then convert the uploaded file into JSON format. The Code is as follows:

@ Requestmapping (value = "fileupload. s ", method = requestmethod. post) // Public String fileupload (@ requestparam ("file") multipartfile file) {public void fileupload (httpservletresponse response, httpservletrequest request) {webresult result = new webresult (); result. setresult (webresult. web_result_fail); multiparthttpservletrequest = (multiparthttpservletrequest) request; // mu Ltiparthttpservletrequest multiparthttpservletrequest = new defaultmultiparthttpservletrequest (request); multipartfile file = multiparthttpservletrequest. getFile ("exmlpath"); string filename = new simpledateformat ("yyyymmddhhmmss "). format (new date () + file. getoriginalfilename (). substring (file. getoriginalfilename (). indexof ('. '); // determines whether the object is null if (! File. isempty () {try {// file storage path string filepath = request. getsession (). getservletcontext (). getrealpath ("/") + getpicupload () + filename; file dirpath = new file (request. getsession (). getservletcontext (). getrealpath ("/") + getpicupload (); If (! Dirpath. exists () {dirpath. mkdirs ();} // save the file. transferto (new file (filepath); // resource res = new servletcontextresource (contextloader. getcurrentwebapplicationcontext (). getservletcontext (), "/upload/type. XML "); resource res = new servletcontextresource (request. getsession (). getservletcontext (), getpicupload () + filename); inputstream stream = res. getinputstream (); bufferedreader BR = new bufferedreader (New inputstreamreader (stream, "GBK"); string temp = NULL; stringbuffer sb = new stringbuffer (); temp = Br. Readline (); While (temp! = NULL) {sb. append (temp); temp = BR. readline ();} Try {jsongenerator generator = objectmapper. getjsonfactory (). createjsongenerator (response. getoutputstream (), jsonencoding. utf8); result. setname (filename); result. setreason (xmlformat. format (sb. tostring (); result. setresult (webresult. web_result_success); objectmapper. writevalue (generator, result);} catch (ioexception e) {logger. error ("Upload Failed: JSON convertion error. ") ;}} catch (exception e) {// E. printstacktrace (); logger. Error (" File Upload error! Error details: "+ E. getlocalizedmessage ());}}}

The format code is as follows:

Public class xmlformat {public static string format (string Str) {// system. out. println ("str:" + Str); saxreader reader = new saxreader (); // system. out. println (Reader); // Note: Create a string of Character Input streams stringreader in = new stringreader (STR); stringwriter out = NULL; try {document DOC = reader. read (in); // system. out. println (Doc. getrootelement (); // Note: Create output format outputformat formater = outputformat. createpunt Yprint (); // formater = outputformat. createcompactformat (); // Note: Set the XML output code formater. setencoding ("UTF-8"); // Note: Create output (target) out = new stringwriter (); // Note: Create output stream xmlwriter writer = new xmlwriter (Out, formater); // Note: output formatted strings to the target, after execution. The formatted string is saved in the out. Writer. Write (DOC); writer. Close () ;}catch (incluentexception e) {// E. printstacktrace (); Return "XML format error. Please check carefully! Details: "+ E. getlocalizedmessage ();} catch (ioexception e) {// E. printstacktrace (); Return" Upload Io error. Please check carefully! Details: "+ E. getlocalizedmessage () ;}// Note: return the formatted return out result. tostring ();} public static void main (string [] ARGs) throws exception {string head = "<? XML version = \ "1.0 \" encoding = \ "GBK \"?> "; String STR = "<requestdata> 

Then, the ajaxfileupload plug-in is used on the page. Ajax uploads the selected XML and accepts the JSON returned by the server. The Code is as follows:

Jquery. ajaxfileupload ({URL: 'fileupload. s ', secureuri: false, fileelementid: 'exmlpath', datatype: 'json', success: function (data, status) {// when you select a file for multiple uploads, you must first clear the HTML content of the DIV xmlpre, otherwise, the HTML after syntaxhighlighter rendering will not change to jquery ("# xmlpre" ).html ("<div> <PRE id = 'xmlcontnt 'class = 'brush: XML; '> </PRE> </div> "); jquery (" # xmlpre "). removeattr ("style", ""); jquery ("# xmlpre "). removeattr ("class ","");//---------------------------- ------------------------------------------- DATA = jquery. parsejson (jquery (data ). text (); // convert the JSON returned by the ajaxfileupload plug-in, which encapsulates a pre label if (data. result = 0) {$ ("# xmlname "). val (data. name); // alert (data. reason); // console. log (data. reason); $ ("# xmlcontnt "). text (data. reason); // put XML in JSON format into the DIV of the blank page, syntaxhighlighter. highlight (); // call the highlighting method of the plug-in to render the highlighted jquery ("# xmlpre "). dialog ({// The DIV page where the highlighted code is located. It is displayed in the pop-up layer to preview minheig. Ht: 300, width: 650, position: "TOP", title: "Upload XML preview"}); jquery ("# xmlpre "). dialog ('open'); // $ ('. theme-popover-mask '). fadein (100); // $ ('. theme-popover '). slidedown (200);} else if (data. result = 1) {alert ("Upload Failed! ");} Else {alert (" Unknown error! ") ;}}, Error: function (s, XML, status, e) {alert (S, XML, status, e )}});

Page code of the pop-up layer:

<div id="xmlPre" style="display:none;border: 1">    <pre >        <pre id="xmlcontnt" class="brush: xml;">        </pre>    </pre></div>


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.