JSP practical tutorial-Implementation of simple page editor (with source code), jsp practical tutorial

Source: Internet
Author: User
Tags form post

JSP practical tutorial-Implementation of simple page editor (with source code), jsp practical tutorial


Implementing a simple page editor is a frequently encountered requirement when learning jsp. I found that there is not much convenient information on the Internet, so I would like to summarize it myself, this article describes in detail the implementation of JSP simple page editor. Let's take a look at the detailed introduction below:


Provides a page with text content such as "help" and "Copyright". Features: static pages that do not need to be read from the database. They only deal with frequent changes to words. There is no complex interaction and JavaScript is not required; no image, no file upload required.

Solution: provides a single page and simple background management, with a single function. It only edits the page (only modifies the font, size, bold, italic, and other functions ).
Implementation idea: Display in JSP only. log on to the management interface using HTTP Basic and write an HTML editor in JavaScript to modify the page content. Directly modify the server disk file.

The page is shown in the following figure.

It is worth mentioning that the default Java Syntax of JSP in Tomcat 7 is still 1.6. The code embedded with the Java 1.7 feature in JSP will throw the "Resource specification not allowed here for source level below 1.7" exception. Modify the configuration file in Tomcat/conf/web. xml and find the <servlet> node (<servlet-name>jsp</servlet-name>And add the last two init-param nodes. Note:<servlet-name>jsp</servlet-name> It is not a default node (similar ).

<servlet>   <servlet-name>jsp</servlet-name>   <servlet-class>org.apache.jasper.servlet.JspServlet</servlet-class>   <init-param>    <param-name>fork</param-name>    <param-value>false</param-value>   </init-param>   <init-param>    <param-name>xpoweredBy</param-name>    <param-value>false</param-value>   </init-param>     <init-param>    <param-name>compilerSourceVM</param-name>    <param-value>1.7</param-value>   </init-param>   <init-param>    <param-name>compilerTargetVM</param-name>    <param-value>1.7</param-value>   </init-param>     <load-on-startup>3</load-on-startup>  </servlet> 

The accessed jsp actually only has two/index. jsp and/admin/index. jsp, which are static pages and background editing pages respectively. /Admin/action. jsp is used to receive the saved action. The data is sent from the form POST. Functions. jsp is all the business logic code.%@include file="functions.jsp"% It cannot be accessed by external URLs separately.

Let's first look at/index. jsp.

<% @ Page pageEncoding = "UTF-8" %> 

This JSP is not specific to General JSP, but do you notice the following two Annotations:<!-- Editable AREA|START --> And<!-- Editable AREA|END --> -- This is the agreed "editable" range. Of course, you can also use a custom HTML Tag, as long as a range is defined. A webpage is nothing more than HTML. For the content to be edited, we can define a range to specify which areas need to be edited. Why can't all pages be edited? It is because we do not want users to edit other parts of the page. In case of errors caused by the key points modified, it is not good.

Okay. How can I edit this/index. jsp? This is done by using Java to read disks. Log on to/admin/index. jsp first. Here we use HTTP Basic Authorization for user authentication, without the need for a database. To change the account password, open admin/functions. jsp and edit the header:

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

However, I encountered a small problem when debugging HTTP Basic Authorization, that is, the pop-up dialog box in the browser. I do not know how to modify the prompt text. I have tried several methods, either not to display or garbled. If you know more, please let us know!

Action. jsp must also be used as an authentication restriction. Otherwise, a vulnerability may cause others to 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); ou T. println ("<script> alert ('modified successfully! '); Window. location = document. referrer; </script> ");} else {out. println ("method error") ;}} else {%> 

Click Save to modify the page.

How to edit HTML? This answer must be clear to everyone. You can use the HTML visual editor online, instead of Dreamweaver, FrontPage, VS Web, and so on. The old people used FCKEditror and TinyMCE Editor. I don't know if I like to use them in China in recent years. Now I write the code myself, and the function is relatively simple.

The core logic is implemented through the following code.

<% @ Page pageEncoding = "UTF-8" import = "sun. misc. BASE64Decoder, java. io. *" %> <%! Public static final String userid = "admin", pwd = "86006966 "; // check whether HTTP Basic Authentication/*** Null String ** @ param str * @ return */public static boolean isEmptyString (String str) {return str = null | str. trim (). isEmpty ();}/*** illegal array ** @ param arr * @ return */public static boolean isBadArray (String [] arr) {return arr = null | arr. length! = 2 ;} /***** @ param authorization * after authentication, the Authorization header information is attached to each HTTP Request * @ param username * @ param password * @ return true = authentication successful/ false = authentication required */public static boolean checkAuth (String authorization, string username, String password) {if (isEmptyString (authorization) return false; String [] basicArray = authorization. split ("\ s +"); if (isBadArray (basicArray) return false; String idpa Ss = 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]);} /*** Start editable ID */private final static String startToken = "<! -- Editable AREA | START --> ";/*** end Editable ID */private final static String endToken =" <! -- Editable AREA | END --> ";/*** obtain the Region ID that can be edited on the page. ** @ Param fullFilePath * Complete jsp file path * @ return editable content * @ throws IOException */public static String read_jsp_fileContent (String fullFilePath) throws IOException {String jsp_fileContent = readFile (fullFilePath); int start = jsp_fileContent.indexOf (startToken), end = token (endToken); try {jsp_fileContent = jsp_fileContent.substring (start + startToken. length (), end);} catch (Str IngIndexOutOfBoundsException e) {jsp_fileContent = null; String msg = "page file" + fullFilePath + "contains no identifier for the Editable area. Please refer to: "+ startToken +"/"+ endToken; throw new IOException (msg);} return jsp_fileContent;}/*** request with file parameters, convert it to the actual disk file path ** @ param rawFullFilePath * the path of the disk file submitted by the URL, the file name may not be included or many url parameters * @ return are added to the complete disk file path */static String getFullPathByRequestUrl (String rawFullFilePath) {if (rawFullFilePath. indexOf (". jsp ") =-1) rawFullFilePath + ="/index. jsp "; // Add the extension if (rawFullFilePath. indexOf ("? ")! =-1) // remove the url parameter rawFullFilePath = rawFullFilePath. replaceAll ("\\?. * $ "," "); Return rawFullFilePath ;} /*** Save the page to be modified ** @ param rawFullFilePath * Actual disk file path * @ param newContent * newly submitted content * @ throws IOException */public static void save_jsp_fileContent (string rawFullFilePath, string newContent) throws IOException {String fullFilePath = getFullPathByRequestUrl (rawFullFilePath); // The actual disk file path String jsp_fileContent = readFile (fullFilePath), toDel_fileContent = read_js P_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 ("the identifier of the Editable area is not marked in the page file. See startToken/endTpoken ");}/*** Read File ** @ param filename * @ return * @ throws IOException */public static String readFile (String filename) throws IOException {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 ("retrieve file outflow Token! "+ Filename); throw e ;}/ *** the file cannot be written using FileWriter, the reason is that Chinese characters are garbled ** @ param filename * @ param content * @ throws IOException */public static void save2file (String filename, String content) throws IOException {try (FileOutputStream out = new FileOutputStream (filename); // OutputStreramWriter converts the Output Response stream to a byte stream output (the response 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 to replace it with an absolute address and convert it to an absolute address, and convert the slash ** @ param relativePath * relative address * @ return absolute address */public String Mappath (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 ;}%>

The user logs on to the simple background with the account and password. The page content can be modified through the visual editor. The modification immediately produces results, simple and Convenient-opening the page to allow independent editing will improve efficiency-Reduce the number of changes back and forth.

Download the complete source code: http://xiazai.jb51.net/201707/yuanma/jsp-page (jb51.netw..rar


The above is all the content of this article. I hope the content of this article will help you in your study or work. If you have any questions, please leave a message, thank you for your support.

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.