Automated Time-Based Reload Response in Java Web Servlet comes into the picture while working with Java Servlets, we need a mechanism for page auto-reload according to our need. This automated refresh can be created in the Java servlet itself as a response. In webpages, there is a need where without clicking any button or link, the page should be auto refreshed or forwarded to a new webpage after a specific time or interval.
So here we will send a response by setting a header for reloading to a new URL after a specific time.
Approach for IDE :
- You need to install an IDE and a Web Server for running below servlet.
- It is suggested to create a project with default configurations. It will handle servlet mapping and web.xml.
- Then Create a new Servlet Named auto-reload and copy the below-given code in the servlet.
- Create another servlet named reloadedpage, which will be the output page.
- You can configure these Servlets into web.xml for dynamic mapping.
- Deploy project on Web Server and locate given URL on the browser (change project with your actual project name) http://localhost:8080/project/autoreload.
Java
import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class autoreload extends HttpServlet { // Current Webpage public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType( "text/html;charset=UTF-8" ); try (PrintWriter out = response.getWriter()) { out.println( "<!DOCTYPE html>" ); out.println( "<html>" ); out.println( "<head>" ); out.println( "<title>Auto-Reload</title>" ); out.println( "</head>" ); out.println( "<body>" ); out.println( "<h1>This webpage will be reloaded to a new page in 5 Seconds...</h1>" ); // response.setHeader("Refresh","5"); // Just Refresh Current Webpage After 5 Seconds response.setHeader( "Refresh" , "5;url=reloadedpage" ); // Refresh This Page to New URL after 5 Seconds // Here Time can be set in seconds so you can // change 5 to another number according to your // need also You can change URL of new Webpage // like here i have written URL for index page out.println( "</body>" ); out.println( "</html>" ); } } } |
Here we can change time and URL according to our need in the above program.
- You can also add this functionality to any of your Servlets without creating a new one.
- You just have to include below given line : response.setHeader(“Refresh”,”5;url=reloadedpage”);
Output :