SpringMVC02:回顾Servlet
回顾Servlet
-
新建一个Maven工程当做父工程!pom依赖!
<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>
-
建立一个Moudle:springmvc-01-servlet , 添加Web app的支持!
-
导入servlet 和 jsp 的 jar 依赖(父项目有,其实可以不写)
<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>
-
编写一个Servlet类,用来处理用户的请求
package com.edgar.servlet; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; public class HelloServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // 1.获取前端参数 String method = req.getParameter("method"); if ("add".equals(method)) { req.getSession().setAttribute("msg","执行了add方法"); } if ("delete".equals(method)) { req.getSession().setAttribute("msg","执行了delete方法"); } // 2.调用业务处理层 // 3.视图转发或者重定向 req.getRequestDispatcher("/WEB-INF/jsp/test.jsp").forward(req,resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
-
编写test.jsp,在WEB-INF目录下新建一个jsp的文件夹,新建test.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> ${msg} </body> </html>
-
在web.xml中注册Servlet
<?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>HelloServlet</servlet-name> <servlet-class>com.edgar.servlet.HelloServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>HelloServlet</servlet-name> <url-pattern>/hello</url-pattern> </servlet-mapping> </web-app>
-
配置Tomcat,并启动测试
-
- localhost:8080/hello?method=add
- localhost:8080/hello?method=delete
MVC框架要做哪些事情
- 将url映射到java类或java类的方法
- 封装用户提交的数据
- 处理请求--调用相关的业务处理--封装响应数据
- 将响应的数据进行渲染。jsp、html等表示层数据。
说明:
常见的服务器端MVC框架有:Structs、Spring MVC、ASP.NET MVC、Zend Framework、JSF;常见前端MVC框架:Vue、angularjs、react、backbone;由MVC演化出了另外一些模式如:MVP、MVVM等等....