Java EE 8 Design Patterns and Best Practices
上QQ阅读APP看书,第一时间看更新

Implementing DownloadFrontController

Here, we have the implementation of DownloadFrontController, which is a Servlet used to download files:

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(name = "DownloadFrontController", urlPatterns = "/download/*")
public class DownloadFrontController extends HttpServlet {



protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
processRequest(request,response);
}

protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
processRequest(request,response);
}

protected void processRequest(HttpServletRequest
request, HttpServletResponse
response)
throws ServletException, java.io.IOException {

//If user is logged the request is sent to
ApplicationController,
// then one error 401 is sent to client.
if(Objects.nonNull(request.getSession().getAttribute("USER"))) {

//Send the request to ApplicationController
new DownloadApplicationController(request,
response).process();

}

else {
response.sendError(401);
}
}
}

In the preceding block of code, we have the DownloadFrontController class with the logic to process a request. This class is a servlet that responds to all requests sent to /download/* using the following line of code:

@WebServlet(name = "DownloadFrontController", urlPatterns = "/download/*")

All GET requests or POST requests are sent to the processRequest method, inside which we have the code to send the request to DownloadApplicationController. The following line of code does just that:

//Send the request to ApplicationController
new DownloadApplicationController(request, response).process();