рд╕рд░реНрд╡рд▓реЗрдЯреНрд╕ - рдкреНрд░рддрд┐рдмрд┐рдВрдм рдХреЗ рд╕рд╛рде рдПрдХ рдЫреЛрдЯреА рд╕реА рдЪрд╛рд▓

рдЙрджреНрджреЗрд╢реНрдп:


рдЖрдкрдХреЛ рдПрдХ рд╕рд░реНрд╡рд▓реЗрдЯ рд▓рд┐рдЦрдирд╛ рд╣реЛрдЧрд╛ рдЬрд┐рд╕рдореЗрдВ рдЙрди рддрд░реАрдХреЛрдВ рдХрд╛ рдПрдХ рд╕рдореВрд╣ рд╣реЛ, рдЬрд┐рдирдХреЗ рдирд╛рдо URL рд╕реЗ рдореЗрд▓ рдЦрд╛рддреЗ рд╣реИрдВред
рдЙрджрд╛рд╣рд░рдг рдХреЗ рд▓рд┐рдП, рд╣рдорд╛рд░реЗ рдкрд╛рд╕ 3 URL рд╣реИрдВ:

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


рдЗрд╕ рддрд░рд╣ UserServiceServlet рд╕рд░реНрд╡рд▓реЗрдЯ рджреНрд╡рд╛рд░рд╛ рдирд┐рдпрдВрддреНрд░рд┐рдд:



 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) { //.... } } 


рдпрд╣ рдХреИрд╕реЗ рдХрд░реЗрдВ?



рд╕рдмрд╕реЗ рдкрд╣рд▓реЗ, рд╣рдо рдореВрд▓ рд╕рд░реНрд╡рд▓реЗрдЯ рд▓рд┐рдЦрддреЗ рд╣реИрдВ:


 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); } } 


рдЕрдЧрд▓рд╛, рдЕрдкрдирд╛ рд╕рд░реНрд╡рд▓реЗрдЯ рд▓рд┐рдЦреЗрдВ:


 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) { //.... } } 


рдФрд░ 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> 


рдЕрдм рдЖрдк рдЕрдкрдиреЗ рд╕рд░реНрд╡рд▓реЗрдЯ рдореЗрдВ рдХреЛрдИ рднреА рд╡рд┐рдзрд┐ рдмрдирд╛ рд╕рдХрддреЗ рд╣реИрдВ! рддрд░реНрдХ рдХреЛ рдЕрд▓рдЧ рдХрд░рдирд╛ рдХрд╛рдлреА рд╕рд░рд▓ рд╣реИ! рд╕реМрднрд╛рдЧреНрдп рд╣реИ ;-)

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


All Articles