nikk nikk - 5 months ago 17
HTML Question

Java Web servlet: writing plain text on an existing html template file

I have Webservlet in Java (Eclpise EE) that dynamically prints a text as follows:

@WebServlet("/test")
public class MyApp extends HttpServlet
{
HttpSession session = request.getSession(true);
response.setContentType("text/plain");
PrintWriter out = response.getWriter();
out.println(ProcessEvent());
}


I have designed a simple template (
default.html
) file with a color background and an image on one side. The html is part of the project in Eclipse.

How can I get the application to print on this default.html file instead of printing the text plain as is on blank page via
out.println()
?

Answer

If you want a super simple web application where a JSP page would be used as view technology and Servlet would supply the business logic, following example might help you:

Step 1: Create following sample.jsp in /WebContent/WEB-INF/templates of Eclipse's Dynamic Web Project

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Sample Page</title>
</head>
<body>
<b>Time Now:</b> ${requestScope["time"]}
</body>
</html>

Step 2: Create following Servlet to supply the business logic for the JSP page:

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@WebServlet("/test")
public class MyApp extends HttpServlet {
    private static final long serialVersionUID = 1L;


    public MyApp() {
    }

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

    request.setAttribute("time", new Date()); // 'time' would be  shown on JSP page             
    RequestDispatcher view = request.getRequestDispatcher("WEB-INF/templates/sample.jsp");      
    view.forward(request, response);
    }

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

}

Step 3: Call the above Servlet by hitting following URL:

http://localhost:8080/mywebapp/test

The output is as shown below:

enter image description here