Reputation: 11
I am trying to use a Servlet with my JSP file using the MVC model, to be able to continuously update the UI without refreshing the page, when the output of the doGet and doSet change.
I have tried to use a timer inside the Servlet (didn't work) and also I tried to use a timer in the JSP file but it didn't work either. I thought it would help to call 'doGet' every 2 seconds to update the output I see on the screen when I run the program. But the only time the output changes is when i manually refresh the website. I expect for this easy program to be able to change and see when I run the program, between the strings "blue" and "red".
The Servlet :
public class Servlet2 extends HttpServlet implements Servlet {
String msg = "blue";
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
request.setAttribute("state", changeColor());
request.getRequestDispatcher("/test.jsp").forward(request, response);
}
public String changeColor(){
if(msg.equals("red"))
msg = "blue";
else msg = "red";
return msg;
}
@Override
protected void doGet(
HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
@Override
protected void doPost(
HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
}
And the JSP file:
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
ID: <%=(String)request.getAttribute("state")%><br>
</body>
</html>
Upvotes: 1
Views: 2229
Reputation: 1225
As you already found out, this is not possible.
http://host/yourServlet
" your browser will open a connection to
the host
and asks for the yourServlet
part.doGet
) and returns anything which is outputted from the servlet code or jsp. To achieve your change of "red" to "blue", you may reload your page automatically by using a html header (meta http-equiv="refresh"
)/javascript (How to reload a page using JavaScript) or you utilize javascript to ask your servlet for the current value of state
(jQuery Ajax POST example with PHP).
Upvotes: 2