springMVC
-
什么是springMVC?
它是基于MVC开发模式的框架,用来优化控制器,它是spring家族的一员,它具备IOC和AOP
-
什么是MVC
它是一种开发模式,它是模型视图控制器的简称,所有的web应用都是基于MVC开发
M: 模型层 包含实体类,业务逻辑层,数据访问层
V:视图层 html,javascript,vue 等都是视图层,用来显示数据
C:控制器 它是用来接收客户的请求,并且返回响应到客户端的组件,servlet就是组件
-
示意图
-
springMVC的优点
-
轻量级,基于MVC的框架
-
易于上手,容易理解,功能强大
-
它具备IOC和AOP
-
完全基于注解开发
-
-
时序图
-
springMVC的执行流程
-
基于注解的springmvc的框架开发步骤
-
新建项目,选择webapp模板
-
修改目录,添加缺失的目录并修改属性
-
修改pom.xml文件,添加springmvc的依赖,添加servlet依赖
-
添加springmvc.xml文件,指定包扫描,添加视图解析器
-
新建web.xml并且注册soringmvc框架(所有的请求都是来自srvlet)
-
新建index.jsp页面,发送请求给服务器
-
开发控制器(srvlet)它是一个普通类
-
添加tomcat进行功能测试
-
-
web请求分析
核心处理器
index.jsp <------> dispatcherServlet <------->springmvc的处理器是一个普通类
one.jsp<---------->dispatcherServlet <------->springmvc的处理器是一个普通类
dispatcherServlet 要在web.xml文件中注册才可以使用
-
注册springmvc框架
-
开发index.jsp
-
@RequestMappering 注解详解
此注解可加在方法上,是为此方法注册一个可以访问的名称
此注解可以加在类上,相当于是包名(虚拟路径)
-
@RequestMappering 可以区分get 和post 请求
-
springmvc.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd"> <!-- 添加包扫描--> <context:component-scan base-package="com.lgy.controller"> </context:component-scan> <!-- 添加视图解析器--> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <!-- 设置前缀--> <property name="prefix" value="/admin/"></property> <!-- 设置后缀 --> <property name="suffix" value=".jsp"></property> </bean> </beans>
-
web.xml
<?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>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springmvc.xml</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name> <!-- 拦截请求 指定什么样的请求 .action 请求才会被拦截 --> <url-pattern>*.action</url-pattern> </servlet-mapping> </web-app>
-
DemoAction.java
package com.lgy.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @Controller @RequestMapping("/user") public class DemoAction { @RequestMapping("/demo") public String demo(){ System.out.println("服务器被访问....."); return "main"; } }
-
配置tomcat测试