开发工具eclipsehtml
jdk-1.8.0_72前端
tomcat-9.0.5java
前端目录git
1.可以实现用户的登陆和注册github
2.可以实现对用户信息的增删查改web
3.登陆过一次的用户保存登陆记录,也就是记录sessionajax
因为代码量太多了,我就把这个项目放到了github上 https://github.com/chenCmengmengda/javaweb_usertomcat
接下来我把最最最核心的部分贴出来session
首先咱们都知道HttpServlet这个类中已经帮咱们实现了doGet和doPost,但是若是请求的后台url一多,不可能每一个都单独写成一个类,因此这两个方法根本不可取,咱们要的是一个类中的多个方法都能被咱们以url传参的形式访问。eclipse
例如:http://localhost:8080/demo1/xxx?method=login
因而我在资料中翻到了这么一段话。
注意蓝色字体,HttpServlet的实现关键在于覆盖了service方法,所以咱们只要本身写一个类覆盖HttpServlet中的service方法就OK了
其实不少代码只要照搬HttpServlet就OK了,想要实现咱们的功能,那么就加上反射的思路进去就OK了
1 public class BaseServlet extends HttpServlet { 2 /* 3 * 它会根据请求中的m,来决定调用本类的哪一个方法 4 */ 5 protected void service(HttpServletRequest req, HttpServletResponse res) 6 throws ServletException, IOException { 7 req.setCharacterEncoding("UTF-8"); 8 res.setContentType("text/html;charset=utf-8"); 9 10 // 例如:http://localhost:8080/demo1/xxx?method=login 11 String methodName = req.getParameter("method");// 它是一个方法名称 12 // System.out.println(methodName); 13 14 // 当没用指定要调用的方法时,那么默认请求的是execute()方法。 15 if(methodName == null || methodName.isEmpty()) { 16 methodName = "execute"; 17 } 18 Class c = this.getClass(); 19 try { 20 // 经过方法名称获取方法的反射对象 21 Method m = c.getMethod(methodName, HttpServletRequest.class, 22 HttpServletResponse.class); 23 // 反射方法目标方法,也就是说,若是methodName为add,那么就调用add方法。 24 String result = (String) m.invoke(this, req, res); 25 // 经过返回值完成请求转发 26 if(result != null && !result.isEmpty()) { 27 req.getRequestDispatcher(result).forward(req, res); 28 } 29 } catch (Exception e) { 30 throw new ServletException(e); 31 } 32 } 33 }
有了这个类以后,咱们本身就能够建立一个controller的包
里面的类继承上面的BaseServlet类
OK,本次案例到此结束,更多的细节请去看github中的源代码
若是有幸这篇随笔能被某位路人朋友看到,笔者此谢谢观看啦