上QQ阅读APP看书,第一时间看更新
How to do it...
You need to perform the following steps to try this recipe:
- 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());
}
}
}
- 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.