2

I have a Java class (Servlet). I need to display the source code; whatever the content in the servlet. This is totally for testing purpose

I know that I could do this through appending to a StringBuffer object, but I have more lines. And another alternative it write to a file. It's again the same. I should write every single line using a file writer. Is there a simple approach to this?

How can I achieve this?

public class TimeZoneValidator extends HttpServlet {
private static final long serialVersionUID = 1L;

public TimeZoneValidator() {
    super();
}

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    //I need this code to be displayed in my JSP(index.jsp) file

    request.setAttribute("oldNumberOfNghtsCalc", oldNumberOfNghtsCalc);
    request.setAttribute("newNumberOfNghtsCalc", newNumberOfNghtsCalc);
    RequestDispatcher requestDispatcher = request.getRequestDispatcher("/index.jsp");
    requestDispatcher.forward(request, response);
}

}
Jude Niroshan
  • 4,280
  • 8
  • 40
  • 62
  • 1
    This smells like an [XY problem](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem) question. Why do you want to display your source code? – gla3dr Oct 01 '15 at 16:36
  • You can add .java sources into your web app into WEB-INF/classes and then read them from .class files as resources. Can't make working example now. I'll try to do it later. – rsutormin Oct 01 '15 at 16:59
  • See also https://stackoverflow.com/questions/132052/servlet-for-serving-static-content for servlet code samples on serving static resources. – Vadzim Apr 05 '18 at 09:31

1 Answers1

0

You can use code like this to load java source code of your class into String value:

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    InputStream is = this.getClass().getResourceAsStream(this.getClass().getSimpleName() + ".java");
    if (is == null) { // Eclipse doesn't want to copy .java files into binary folder
        // So in developer mode we have to read it from "src" folder
        is = new FileInputStream(new File("src", this.getClass().getName().replace(".", "/") + ".java"));
    }
    IOUtils.copy(is, baos);
    is.close();
    baos.close();
    String javaSourceCode = new String(baos.toByteArray(), Charset.forName("utf-8"));

Here is a trick with reading java code from src when you run your project from Eclipse and it doesn't copy .java files into classes. But make sure you copy them manually in your build script (maven, ant) as resources when you prepare .war file.

rsutormin
  • 1,629
  • 2
  • 17
  • 21
  • This would not work in servlet container unless you somehow force build tool to also include java sources inside the war. – Vadzim Apr 04 '18 at 20:17
  • Here is how to include java sources with maven: https://stackoverflow.com/questions/4264359/maven-create-jar-file-with-both-class-and-java-files – Vadzim Apr 05 '18 at 09:41