# framework-custom **Repository Path**: gmarshal/framework-custom ## Basic Information - **Project Name**: framework-custom - **Description**: 【待删除】基于Servlet模仿MVC架构 - 无框架framework-custom-base(最基础版)framework-custom-plus(仿Spring) - **Primary Language**: Java - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 1 - **Forks**: 0 - **Created**: 2018-05-10 - **Last Updated**: 2020-12-19 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # 基于Servlet模仿MVC架构 - 无框架 * framework-custom-base(最基础版) * framework-custom-plus(仿Spring) ## Servlet简介 Servlet是对Web浏览器或其他HTTP客服端程序发出的请求进行处理的程序。 其中Servlet对象需要放在Servlet容器(Tomcat)中才能运行 ## Servlet生命周期 先看一下Servlet的源码 ``` public interface Servlet { void init(ServletConfig var1) throws ServletException; ServletConfig getServletConfig(); void service(ServletRequest var1, ServletResponse var2) throws ServletException, IOException; String getServletInfo(); void destroy(); } ``` 可以了解到Servlet的生命周期 * Servlet 调用 init () 方法初始化。 * Servlet 调用 service() 方法处理请求。 * Servlet 调用 destroy() 方法结束。 * 最后,Servlet 由 JVM 的垃圾回收器进行垃圾回收。 ## HttpServlet简介 Servlet的框架是由两个Java包组成: * javax.servlet * 定义了所有的Servlet类都必须实现或扩展的的通用接口和类。 * javax.servlet.http。 * 定义了采用HTTP通信协议的HttpServlet类 可以通过查看HttpServlet源码,它提供了与Http请求方式相对应的方法 ``` doDelete() doGet() doOptions() doPost() doPut() doTrace() ``` 为了方便,framework-custom 系列代码中只使用了 `doGet()` 与 `doPost()` 下面我们尝试通过HttpServlet搭建一个Web项目 ## 搭建Web项目 ![Alt text](./doc/HttpServlet.png) 这里我们先实现jsp的跳转 程序总共需要使用2个jar包,为 servlet-api 与 jstl(jsp需要使用到jstl) #### pom.xml >这里使用的是Maven,如果不想使用Maven则直接下载对应的jar包放入程序并引用即可) ``` javax.servlet servlet-api 3.0-alpha-1 jstl jstl 1.2 ``` #### web.xml ``` DemoJspServlet com.foruo.modules.demo.controller.DemoJspServlet DemoJspServlet /jsp ``` #### 自定义Servlet(DemoJspServlet) ``` /** * 跳转页面 * @author GaoYuan * @date 2018/5/10 下午3:24 */ public class DemoJspServlet extends HttpServlet{ DemoService demoService = new DemoService(); @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 设置响应内容类型 response.setCharacterEncoding("UTF-8"); try { // 获取参数 String id = request.getParameter("id"); // 这里封装了获取对象的方法 DemoEntity demoEntity = demoService.get(id); // 将返回的对象存放至request request.setAttribute("demoEntity",demoEntity); // 跳转页面 RequestDispatcher rd = request.getRequestDispatcher("demo" + ".jsp"); rd.forward(request, response); }catch (Exception e){ e.printStackTrace(); } } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doGet(request,response); } } ``` #### 启动Tomcat容器 打包或者配置tomcat(省略) #### 访问网址 http://localhost:8080/项目名/jsp?id=1 ![Alt text](./doc/jsp.png) 至此 基于 HttpServlet 的简单Web项目搭建完成 ## 源码: https://gitee.com/gmarshal/framework-custom 里面包含以上例子源码,同时也包含基于以上代码更进一步封装的类似Spring框架的相关代码,有兴趣的可以看看。 ## 博客: https://my.oschina.net/gmarshal/blog/1810556