I am inspired from w3schools try it yourself editor. It is better to give an option to users to try themselves.
This below Try It Your Self editor was built upon HTML, JavaScript and Java. You can find the below diagram for program flow.

<textarea class="code_input" id="textareaCode" wrap="logical" rows="30" cols="50">
...
</textarea>

Form to Submit the code to Server :

Here the "target" attribute was specified as "view" so the output of this form will be displayed in "view" named iframe. 
<form style="margin:0px;display:none;" action="/TryItYourSelf" method="post" target="view" id="tryitform" name="tryitform" onsubmit="validateForm();">
        <input type="hidden" name="code" id="code" />
        <input type="hidden" id="bt" name="bt" />
</form>

iframe for displaying result :

<iframe id="iframeResult" class="result_output" frameborder="0" name="view" src="/angular-jquery/expressions_a.html"></iframe>

JavaScript for validating form :

function validateForm()
{
var code=document.getElementById("code").value;
if (code.length>8000)
    {
    document.getElementById("code").value="<h1>Error</h1>";
    }
}

JavaScript for submitting form  to server :

function submitTryit()
{
 var t=document.getElementById("textareaCode").value;
 t=encodeURI(t);
 document.getElementById("bt").value="1";
 document.getElementById("code").value=t;
 document.getElementById("tryitform").action="/TryItYourSelf?x=" + Math.random();
 validateForm();
 document.getElementById("tryitform").submit();
}

Java Servlet to read and write the code :

Here we have to set "X-XSS-Protection" and "Content-Security-Policy" as 0 unless it will throw security exceptions and script wont run.
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class TryItYourSelf extends HttpServlet {
       
    public TryItYourSelf() {
        super();
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String code = request.getParameter("code");
        response.setHeader("X-XSS-Protection", "0");
        response.setHeader("Content-Security-Policy", "0");
        PrintWriter pw = response.getWriter();
        pw.print(java.net.URLDecoder.decode(code, "UTF-8"));
        pw.flush();
    }

}

0 comments:

Blogroll

Follow this blog by Email

Popular Posts