spring MVC
狂神说springMVC笔记
回顾MVC架构
MVC架构
MVC是一种架构模式,主要作用是降低了视图与业务逻辑间的双向耦合
==模型model、视图view、控制器controller==缩写
- model:数据模型,,一般分为数据层(dao层)和服务层(service层)调用dao层执行业务
- view:负责模型的展示,即前端页面
- controller:接收用户请求,交给模型处理,处理完将模型数据交给视图,由视图负责展示。控制器的任务就是在视图展示和模型处理之间进行调度
最经典的MVC架构
JSP+Servlet+JavaBean

参考文章
SpringMVC学前回顾
回顾servlet

1. 新建maven项目,导入pom依赖
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.1.9.RELEASE</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>2.5</version> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>jsp-api</artifactId> <version>2.2</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> </dependencies>
|
2.创建module:springMVC-01-servlet
右键添加Framework支持

选择web application

3.pom.xml导入servlet 和 jsp 的 jar 依赖
1 2 3 4 5 6 7 8 9 10
| <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>2.5</version> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>jsp-api</artifactId> <version>2.2</version> </dependency>
|
4.编写servlet类HelloServelt,处理用户的请求
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| public class HelloServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String method = req.getParameter("method"); if (method.equals("add")){ req.getSession().setAttribute("msg","执行了add方法"); } if (method.equals("delete")){ req.getSession().setAttribute("msg","执行了delete方法"); }
req.getRequestDispatcher("/WEB-INF/jsp/test.jsp").forward(req,resp); }
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
|
5.编写test.jsp,在WEB-INF目录下新建jsp文件夹,新建test.jsp
1 2 3 4 5 6 7 8 9 10 11
| <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body>
${msg}
</body> </html>
|
6.web.xml中注册servlet
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" version="4.0"> <servlet> <servlet-name>hello</servlet-name> <servlet-class>com.nuc.servlet.HelloServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>hello</servlet-name> <url-pattern>/hello</url-pattern> </servlet-mapping>
</web-app>
|
7.配置Tomcat,进行测试
- localhost:8080/hello?method=add
- localhost:8080/hello?method=delete


spring MVC执行原理
