📜 ⬆️ ⬇️

Servlet - a little trick with Reflection

Task:


You need to write a servlet that contains a bunch of methods whose names match the URL.
For example, we have 3 URLs:

myhost/userservice/registration
myhost/userservice/login
myhost/userservice/anotherAction


that the UserServiceServlet servlet handles, like this:


')
 public class UserServiceServlet extends HttpServlet { public void registration(HttpServletRequest request, HttpServletResponse response) { //.... } public void login(HttpServletRequest request, HttpServletResponse response) { //.... } public void anotherAction(HttpServletRequest request, HttpServletResponse response) { //.... } } 


How to do it?



First of all we write the base servlet:


 public class BaseServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { try { String method = getMethod(req); //  ,  "login"  "trampampam"; if (method != null && !"".equals(method)) { callMethod(method, req, resp); //   } } catch (Exception e) { // log exception req.getRequestDispatcher(WebPages.PAGE_404).forward(req, resp); } } private String getMethod(HttpServletRequest request) { String method = request.getPathInfo(); // ,  "/login" if (!"".equals(method)) { return method.substring(1, method.length()); //    "/" } return null; } private void callMethod(String method, HttpServletRequest request, HttpServletResponse response) throws Exception //          this.getClass().getDeclaredMethod(method, HttpServletRequest.class, HttpServletResponse.class).invoke(this, request, response); } } 


Then we write our servlet:


 public class UserServiceServlet extends BaseServlet { public void registration(HttpServletRequest request, HttpServletResponse response) { //.... } public void login(HttpServletRequest request, HttpServletResponse response) { //.... } public void anotherAction(HttpServletRequest request, HttpServletResponse response) { //.... } } 


and in web.xml:


 <servlet> <servlet-name>User</servlet-name> <servlet-class>mypackage.UserServiceServlet</servlet-class> </servlet><servlet-mapping> <servlet-name>User</servlet-name> <url-pattern>/userservice/*</url-pattern> </servlet-mapping> 


Now you can create arbitrary methods in your servlet! To separate the logic, it turns out, is simple enough Good luck! ;-)

Source: https://habr.com/ru/post/119648/


All Articles