JSP Utility Simple Page Editor

Source: Internet
Author: User
Tags readfile

Full source Download: HTTP://PAN.BAIDU.COM/S/1BPKHNNP (Baidu Cloud provided)

requirements: provide a page, put "help", "copyright" text content, features: static pages, do not need to read the database, but to deal with the wording of the frequent changes; no complicated interactions, no JavaScript, no images, no file uploads.

the solution: provide a page and simple background management, single function, just edit the page (just modify the font, size, bold, italic, etc.).

implementation ideas: Pure JSP Display, the management interface with HTTP Basic login, through a JS written HTML editor to modify the content of the page. Modify the server disk file directly.

The interface is as follows , and the right image is background editing.

It's worth mentioning that the JSP default Java syntax for Tomcat 7 is still 1.6. The code that embeds the Java 1.7 feature in the JSP will throw the exception "Resource specification not allowed here for source level below 1.7". So we need to modify the configuration file inside the Tomcat/conf/web.xml, find the <servlet> node, add the following bold section. Note that it is a JSP node, not the default node (very similar).

 <servlet> <servlet-name>jsp</servlet-name> <servlet-clas S>org.apache.jasper.servlet.jspservlet</servlet-class> <init-param> <param-name>for k</param-name> <param-value>false</param-value> </init-param> <init-pa         Ram> <param-name>xpoweredBy</param-name> <param-value>false</param-value> </init-param><strong> <init-param> <param-name>compilersourcevm</para            m-name> <param-value>1.7</param-value> </init-param> <init-param>        <param-name>compilerTargetVM</param-name> <param-value>1.7</param-value> </init-param></strong> <load-on-startup>3</load-on-startup> </servlet> 

In fact, only two/index.jsp and/admin/index.jsp are accessed, which are static pages and background editing pages. The/admin/action.jsp is used to receive the saved action, and the data is POST from the form. Functions.jsp is the entire business logic code, through the <% @include file= "functions.jsp"%> it cannot be accessed separately from the outside URL.

Let's look at/index.jsp first.

<% @page pageencoding= "UTF-8"%>

This JSP and the general JSP does not have the specificity, but everybody has not noticed two paragraphs annotation:<!--Editable area| START-and <!--Editable area| END-->--This is the "editable" scope we agreed on. Of course, using a custom HTML Tag is also possible, as long as you define a range. A Web page, nothing more than HTML. For what you want to edit, we define a scope that indicates which areas need to be edited. As for why not all pages can be edited? Because we do not want users to edit the rest of the page, in case the change of the key place caused the error, it is not good.

Well, how do you make this/index.jsp editor? is to use Java to read the disk method to do. Before this, you'll have to log in to/admin/index.jsp. Here we use HTTP Basic Authorization to do user authentication, no database. If you need to change the account password, open admin/functions.jsp, edit the header section can:

<%!
public static final String userid = "admin", pwd = "123123";
....
%>

But I debug HTTP Basic Authorization encountered a small problem, is the browser pop-up dialog box, do not know how to modify the hint text, tried several methods, either do not display, or garbled. If you know the children's shoes please also inform one or two!


Action.jsp also to be a certification limit, or it is a loophole can let others POST any data to the page.

<% @page pageencoding= "UTF-8"%><% @include file= "functions.jsp"%><%if (Checkauth (Request.getheader (" Authorization "), UserID, pwd) {  request.setcharacterencoding (" Utf-8 "), if (Request.getmethod (). Equalsignorecase ("POST")) {String contentbody = Request.getparameter ("contentbody"), Path = Mappath (geteditjsp ( request)); System.out.println ("Path:::" + path); save_jsp_filecontent (path, contentbody); Out.println ("<script>alert (' Modified successfully! '); window.location = document.referrer;</script> ");} else {out.println ("method Error");}} else {%>

Modify the next page, click Save to modify the page.


As for how HTML is edited? This answer must be clear to everyone, using the HTML visual editor, online, rather than Dreamweaver, FrontPage, VS Web. Old people used to have fckeditror Ah, TinyMCE Editor, in recent years seems to like to use domestic, I do not know. Now the use of this is my own writing, the function is relatively single.

The

Core logic is done with the following code.

<% @page pageencoding= "UTF-8" import= "Sun.misc.BASE64Decoder, java.io.*"%><%!public static final String UserID = "Admin", pwd = "86006966";//Check HTTP Basic authentication/** * is empty string * * @param str * @return */public static Boolean isemp Tystring (String str) {return str = = NULL | | Str.trim (). IsEmpty ();} /** * is not an illegal array * * @param arr * @return */public static Boolean Isbadarray (string[] arr) {return arr = = NULL | | arr.lengt H! = 2;} /** * * @param authorization * Authentication each HTTP request will be accompanied by authorization header information * @param username * username * @param Password * Password * @return true = Authentication Successful/False = Requires authentication */public static Boolean Checkauth (String authorization, Strin G username, String password) {if (isemptystring (authorization)) return false; string[] Basicarray = Authorization.split ("\\s+"), if (Isbadarray (Basicarray)) return false;  String idpass = null;try {byte[] buf = new Base64decoder (). Decodebuffer (Basicarray[1]); idpass = new String (buf, "UTF-8");} catch (IOException e) {e.printstacktrAce (); return false;} if (isemptystring (Idpass)) return false; string[] Idpassarray = Idpass.split (":"), if (Isbadarray (Idpassarray)) return False;return Username.equalsignorecase ( Idpassarray[0]) && password.equalsignorecase (idpassarray[1]);} /** * Editable identity start */private final static String Starttoken = "<!--Editable area| START-to ";/** * Editable logo end */private final static String Endtoken =" <!--Editable area| END-to ";/** * based on the identification of editable regions in the page, take them out. * * @param fullfilepath * Full jsp file path * @return Editable content * @throws ioexception */public static String Read_jsp_f Ilecontent (String fullfilepath) throws IOException {string jsp_filecontent = ReadFile (fullfilepath); int start = Jsp_ Filecontent.indexof (starttoken), end = Jsp_filecontent.indexof (Endtoken); try {jsp_filecontent = jsp_ Filecontent.substring (start + starttoken.length (), end);} catch (Stringindexoutofboundsexception e) {jsp_filecontent = null; String msg = "page file" + Fullfilepath + "does not mark the identification of editable regions. Please refer to: "+ Starttoken +"/"+ EndToKen;throw new IOException (msg);} return jsp_filecontent;} /** * Request attached file parameter, convert it to real disk file path * * @param rawfullfilepath * URL submitted over the disk file path, may not contain file name or add a lot of URL parameters * @return Full disk File path */static string Getfullpathbyrequesturl (String rawfullfilepath) {if (Rawfullfilepath.indexof (". jsp") = = = 1) Rawfullfilepath + = "/index.jsp"; Plus the extension if (Rawfullfilepath.indexof ("?")! =-1)//Remove URL parameter Rawfullfilepath = rawfullfilepath.replaceall ("\ \?. *$ "," "); return Rawfullfilepath;} /** * Save the page you want to modify * * @param rawfullfilepath * Real Disk File path * @param newcontent * NEW submissions * @throws IOEXCE ption */public static void Save_jsp_filecontent (String rawfullfilepath, String newcontent) throws IOException {string ful Lfilepath = Getfullpathbyrequesturl (Rawfullfilepath); True disk File path string jsp_filecontent = ReadFile (fullfilepath), todel_filecontent = Read_jsp_filecontent (Fullfilepath); /Read old content//system.out.println (jsp_filecontent);//system.out.println (todel_filecontent); if (todel_filecontent! = null ) {JSP_filecontent = Jsp_filecontent.replace (todel_filecontent, newcontent); Save2file (Fullfilepath, jsp_fileContent); Save new Content} else {throw new IOException ("There is no label for the editable region in the paging file. Please refer to: Starttoken/endtpoken ");}} /** * Read File * * @param filename * @return * @throws ioexception */public static string ReadFile (String filename) throws IO Exception {File File = new file (filename), if (!file.exists ()) throw new FileNotFoundException (filename + "does not exist!) ") Try (FileInputStream is = new FileInputStream (file);) {String line = null; StringBuilder result = new StringBuilder (); try (inputstreamreader isreader = new InputStreamReader (IS, "UTF-8"); BufferedReader reader = new BufferedReader (isreader);) {while (line = Reader.readline ())! = null) {result.append (line); Result.append (' \ n ');}} catch (IOException e) {System.err.println (e);} return result.tostring ();} catch (IOException e) {System.err.println ("read the file out of the wrong!") "+ filename"; throw e;}} /** * Write file can not use FileWriter, because it will be garbled in Chinese * * @param filename * @param content * @throws IOEXCEPtion */public static void Save2file (string filename, string content) throws IOException {try (fileoutputstream out = new F Ileoutputstream (filename);//Outputstreramwriter the output character into a byte stream output (the character stream is buffered) OutputStreamWriter writer = new OutputStreamWriter (out, "UTF8");) {writer.write (content);} catch (IOException e) {System.err.println ("Write file" + filename + "failed"); throw e;}} /** * Enter a relative address, add the absolute address to the relative address to convert to an absolute address, and convert the slash * * @param relativepath * Relative address * @return Absolute address */public String Mappat H (String relativepath) {string absoluteaddress = Getservletcontext (). Getrealpath (RelativePath);//Absolute address if ( absoluteaddress = null) absoluteaddress = absoluteaddress.replace (' \ \ ', '/'); return absoluteaddress;} Public String geteditjsp (HttpServletRequest request) {String URI = Request.getrequesturi (). ReplaceAll ("admin/\\w+", " Index "); URI = Uri.replace (Request.getcontextpath ()," "); return URI;} %>

Users with account password login simple backstage, through the visual editor can modify the content of the page, immediately modify, immediately produce effect, simple and fast-open the page to allow self-editing this will improve efficiency-reduce the number of changes back and forth.

Shortcomings, please also point out.

JSP Utility Simple Page Editor

Related Article

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.