How to do Auto Refresh in Servlet

Auto Refresh in Servlet

In this tutorial, We will show you example program about, How to do an auto refresh in servlet. The program has been tested and shared in the post.

Project Structure

Auto Refresh in Servlet

Servlet Class (AutoRefreshServlet.java)

package com.dineshkrish.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

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(urlPatterns = "/home")
public class AutoRefreshServlet extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		PrintWriter out = resp.getWriter();
		
		resp.setHeader("Refresh", "1");
		
		resp.setContentType("text/html");
		
		out.println("<html><body>");
		
		out.println("<center>");
		
		out.println("<h1>Auto Refresh Page in Servlet</h1>");
		
		Date currentDate = new Date();
		
		DateFormat df = new SimpleDateFormat("hh:mm:ss a");
		
		out.println("<h5>"+df.format(currentDate)+"</h5>");
		
		out.println("</center>");
		
		out.println("</body></html>");
		
		out.close();

	}

}

Configuration (web.xml)

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://xmlns.jcp.org/xml/ns/javaee"
	xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
	id="WebApp_ID" version="3.1">
	
	<display-name>AutoRefresh</display-name>
	
	<welcome-file-list>
		<welcome-file>home</welcome-file>
	</welcome-file-list>
	
</web-app>

Output

Auto Refresh in Servlet

References

1. HttpServletRequest Interface
2. HttpServletResponse Interface
3. HttpServletResponse setHeader() method

Hello, folks, I am a founder of dineshkrish.com. I love Java and Open source technologies, If you find my tutorials are useful, please consider making donations to these charities.