spring boot 学习3 web MVC核心与视图

内容:理解、认识、简化

servlet

特点:请求响应式(Request/Response)、屏蔽网络通讯细节、有完整的生命周期

职责:处理请求(handler等)、资源管理(连接数据库、redis)、视图渲染(html等)

 

核心组件:

处理器管理

  • 映射:HandlerMapping
  • 适配器:HandlerAdapter
  • 执行:HandlerExecutionChain
  • 视图解析:ViewResolver
  • 国际化:LocaleResolver、LocaleContextResolver
  • 个性化:ThemeResolver
  • 异常处理:HandlerExceptionResolver

 

 核心主键bean

组件 Bean 类型说明
HandlerMapping映射请求(Request)到处理器(Handler)加上其关联的拦截(HandlerInterceptor)列表。(就是url映射目录和拦截器)
HandlerAdapter调用请求处理器(Handler)无需关注其中实际的调用细节。调用注解实现的 Controller 。(适配器)
HandlerExceptionResolver解析异常,可能策略是将异常处理映射到其他处理(Handlers) 、或到某个 HTML错误页面
ViewResolver 从处理器(Handler)返回字符类型的逻辑视图名称解析出实际的 View 对象
LocaleResolver,LocaleContextResolver实现国际化视图
MultipartResolver 解析多部分请求(如 Web 浏览器文件上传)的抽象实现

 

 

 

 

 

 

 

 

 

xml方式实现mvc

web.xml(webapp.WEB-INF.web.xml) 配置DispatcherServlet,指定xml扫描路径

<web-app>
    <servlet>
        <servlet-name>app</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup><!-- 优先级 -->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/app-context.xml</param-value>
        </init-param>
    </servlet>

    <servlet-mapping>
        <servlet-name>app</servlet-name>
        <url-pattern>/</url-pattern><!-- 匹配所有路径 -->
    </servlet-mapping>
</web-app>

 配置 Web MVC 组件(指定扫描范围,设置:HandlerMapping,HandlerAdapter,ViewResolver 

<?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.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">

    <context:component-scan base-package="com.imooc.web"/>

    <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/>

    <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"/>

    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

</beans>

添加controller

@Controller
public class HelloWorldController {

    @RequestMapping("")
    public String index(@RequestParam int value, Model model) {
        return "index";
    }

}

Web MVC 注解驱动

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
        </dependency>

        <!-- Spring Web MVC 依赖 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
        </dependency>

老式非 spring boot 没有内嵌tomcat 需要放入tomcat才能使用。

注解驱动:

@EnableWebMvc 默认配置了HandlerMapping,HandlerAdapter的bean

实现WebMvcConfigurer 自定义url拦截器

@Configuration
@EnableWebMvc
public class WebMvcConfig implements WebMvcConfigurer {

    @Bean
    public ViewResolver viewResolver(){
        InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
        viewResolver.setViewClass(JstlView.class);
        viewResolver.setPrefix("/WEB-INF/jsp/");
        viewResolver.setSuffix(".jsp");
        return viewResolver;
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new HandlerInterceptor() {
            @Override
            public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
                System.out.println("拦截中...");
                return true;
            }
        });
    }
}

常用注解

@ModelAttribute注册模型属性(可以在jsp页面读取这些属性)
@RequestHeader读取请求头
@CookieValue读取 Cookie
@Valid 、 @Validated校验参数
@ExceptionHandler注解处理,异常时处理
 @ControllerAdvice切面通知(通过代理模式添加通知数据)

 

 

 

 

 

 

 

//代理的HelloWorldController这个类里的通知
@ControllerAdvice(assignableTypes = HelloWorldController.class)
public class HelloWorldControllerAdvice {

    @ModelAttribute("acceptLanguage")
    public String acceptLanguage(@RequestHeader("Accept-Language") String acceptLanguage){
        return acceptLanguage;
    }

    @ModelAttribute("jsessionId")
    public String jsessionId(@CookieValue("JSESSIONID") String jsessionId){
        return jsessionId;
    }

    @ModelAttribute("message")
    public String message(){
        return "Hello,World";
    }

    @ExceptionHandler(Throwable.class)
    public ResponseEntity<String> onException(Throwable throwable) {
        return ResponseEntity.ok(throwable.getMessage());
    }

}
@Controller
public class HelloWorldController {
    
    @RequestMapping("")
    public String index(@RequestParam int value, Model model) {
//        model.addAttribute("acceptLanguage",acceptLanguage);
//        model.addAttribute("jsessionId",jsessionId);
//        model.addAttribute("message","Hello,World");
        return "index";
    }
}
<jsp:root xmlns:jsp="http://java.sun.com/JSP/Page" version="2.0">
    <body>
        <message>${message}</message>
        <language>${acceptLanguage}</language>
        <jsessionId>${jsessionId}</jsessionId>
    </body>
</jsp:root>

spring boot 自动装配

Spring Boot JSP 依赖

        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>
        </dependency>

 application.properties

spring.mvc.view.prefix = /WEB-INF/jsp/
spring.mvc.view.suffix = .jsp
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new HandlerInterceptor() {
            @Override
            public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
                System.out.println("拦截中...");
                return true;
            }
        });
    }
}

 启动类

@SpringBootApplication(scanBasePackages = "com.imooc.web")
public class SpringBootWebMvcBootstrap {

    public static void main(String[] args) {
        SpringApplication.run(SpringBootWebMvcBootstrap.class, args);
    }

}
@Controller
public class HelloWorldController {

    @RequestMapping("")
    public String index(@RequestParam int value, Model model) {
        return "index";
    }

}

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值