How to do it...

You need to perform the following steps to try this recipe:

  1. We will create a servlet:
@WebServlet(name = "ServerPush", urlPatterns = {"/ServerPush"})
public class ServerPush extends HttpServlet {

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

PushBuilder pb = request.newPushBuilder();
if (pb != null) {
pb.path("images/javaee-logo.png")
.addHeader("content-type", "image/png")
.push();
}

try (PrintWriter writer = response.getWriter();) {
StringBuilder html = new StringBuilder();
html.append("<html>");
html.append("<center>");
html.append("<img src='images/javaee-logo.png'><br>");
html.append("<h2>Image pushed by ServerPush</h2>");
html.append("</center>");
html.append("</html>");
writer.write(html.toString());
}
}
}

  1. To try it, run the project in a Jakarta EE 8 server and open this URL:
https://localhost:8181/ch01-servlet/ServerPush

Let's now see how this works.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
13.58.137.218