How to do it...

Let's build the features on which this recipe is based:

  1. Firstly, let's start with our servlet, which will load on server startup:
@WebServlet(name = "LoadOnStartupServlet", urlPatterns = {"/LoadOnStartupServlet"}, 
loadOnStartup = 1)
public class LoadOnStartupServlet extends HttpServlet {

@Override
public void init() throws ServletException {
System.out.println("*******SERVLET LOADED
WITH SERVER's STARTUP*******");
}

}
  1. Next, we add a servlet with some parameters for its own initialization:
@WebServlet(name = "InitConfigServlet", urlPatterns = {"/InitConfigServlet"}, 
initParams = {
@WebInitParam(name = "key1", value = "value1"),
@WebInitParam(name = "key2", value = "value2"),
@WebInitParam(name = "key3", value = "value3"),
@WebInitParam(name = "key4", value = "value4"),
@WebInitParam(name = "key5", value = "value5")
}
)
public class InitConfigServlet extends HttpServlet {

Map<String, String> param = new HashMap<>();

@Override
protected void doPost(HttpServletRequest req,
HttpServletResponse resp)
throws ServletException, IOException {
doProcess(req, resp);
}

@Override
protected void doGet(HttpServletRequest req,
HttpServletResponse resp)
throws ServletException, IOException {
doProcess(req, resp);
}

private void doProcess(HttpServletRequest req,
HttpServletResponse resp)
throws IOException{
resp.setContentType("text/html");
PrintWriter out = resp.getWriter();

if (param.isEmpty()){
out.println("No params to show");
} else{
param.forEach((k,v) -> out.println("param: " + k + ",
value: " + v + "<br />"));
}
}

@Override
public void init(ServletConfig config) throws ServletException {
System.out.println("init");
List<String> list =
Collections.list(config.getInitParameterNames());
list.forEach((key) -> {
param.put(key, config.getInitParameter(key));
});
}

}
  1. Then, we implement our asynchronous servlet, as follows:
@WebServlet(urlPatterns = "/AsyncServlet", asyncSupported = true)
public class AsyncServlet extends HttpServlet {

private static final long serialVersionUID = 1L;

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

long startTime = System.currentTimeMillis();
System.out.println("AsyncServlet Begin, Name="
+ Thread.currentThread().getName() + ", ID="
+ Thread.currentThread().getId());

String time = request.getParameter("timestamp");
AsyncContext asyncCtx = request.startAsync();

asyncCtx.start(() -> {
try {
Thread.sleep(Long.valueOf(time));
long endTime = System.currentTimeMillis();
long timeElapsed = endTime - startTime;
System.out.println("AsyncServlet Finish, Name="
+ Thread.currentThread().getName() + ", ID="
+ Thread.currentThread().getId() + ", Duration="
+ timeElapsed + " milliseconds.");

asyncCtx.getResponse().getWriter().write
("Async process time: " + timeElapsed + " milliseconds");
asyncCtx.complete();
} catch (InterruptedException | IOException ex) {
System.err.println(ex.getMessage());
}
});
}
}
  1. Finally, we need a simple web page to try all of these servlets:
<body>
<a href="${pageContext.request.contextPath}/InitConfigServlet">
InitConfigServlet</a>
<br />
<br />
<form action="${pageContext.request.contextPath}/AsyncServlet"
method="GET">
<h2>AsyncServlet</h2>
Milliseconds
<br />
<input type="number" id="timestamp" name="timestamp"
style="width: 200px" value="5000"/>
<button type="submit">Submit</button>
</form>

</body>

After this point, you are ready to try it.

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

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