nikk nikk - 11 months ago 47
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:

public class MyApp extends HttpServlet
HttpSession session = request.getSession(true);
PrintWriter out = response.getWriter();

I have designed a simple template (
) 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


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"
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "">
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Sample Page</title>
<b>Time Now:</b> ${requestScope["time"]}

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


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;

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:


The output is as shown below:

enter image description here