四.Spring Boot与web开发

一.简介

使用SpringBoot;

1)、创建SpringBoot应用,选中我们需要的模块;

2)、SpringBoot已经默认将这些场景配置好了,只需要在配置文件中指定少量配置就可以运行起来

3)、自己编写业务代码;

二.静态资源的映射规则

1.方式一:以jar包的方式引入静态资源

所有 /webjars/** 的请求,都去 classpath:/META-INF/resources/webjars/ 找资源

例如,引入jquery
只需在pom.xml中添加

<!-- 引入jquery -->
<dependency>
    <groupId>org.webjars</groupId>
    <artifactId>jquery</artifactId>
    <version>3.3.1</version>
</dependency>

静态资源坐标查询网站:http://www.webjars.org/

引入后,查看maven依赖
在这里插入图片描述
访问方式:

localhost:8080/webjars/jquery/3.3.1/jquery.js

2.方式二:按照springBoot的规范在指定位置下放置静态资源

"classpath:/META-INF/resources/", 
"classpath:/resources/",
"classpath:/static/", 
"classpath:/public/" 
"/":当前项目的根路径

在这里插入图片描述
在这里插入图片描述
访问方式:

http://localhost:8080/asserts/img/bootstrap-solid.svg

3.欢迎页

访问项目根目录时:localhost:8080/ 回去静态资源文件夹下找 index.html

在这里插入图片描述

4.网页图标

所有的**/favicon.ico 都在静态资源文件下找

在这里插入图片描述

5.更改springBoot的默认静态文件夹

在application.properties文件中

spring.resources.static-locations=classpath:/hello/,classpath:/miracle

三.模板引擎

SpringBoot推荐的Thymeleaf;
语法更简单,功能更强大;
下面是整合Thymeleaf模板引擎

1.导入依赖

在pom.xml添加

<properties>
    <thymeleaf.version>3.0.2.RELEASE</thymeleaf.version>
    <!-- 布局功能的支持程序 thymeleaf-->
    <thymeleaf-layout-dialect.version>2.1.1</thymeleaf-layout-dialect.version>
</properties>
<!-- 引入模板引擎 thymeleaf-->
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

2.Thymeleaf的拦截规则

只需将*.html放入 classpath下的templates

3.禁用Thymeleaf模板引擎缓存

spring.thymeleaf.cache=false

四.如何修改SpringBoot的配置

模式1

SpringBoot在自动配置很多组件的时候,先看容器中有没有用户自己配置的(@bean,@Component)如果有就用用户的配置,如果没有,才自动配置,有些组件可以有多个将用户配置和自己默认的组合起来

模式2

五.首页映射

1.创建config包

com.miracle.config

2.创建配置类

MyMvcConfig.java
扩展springMVC配置,配置类需要继承WebMvcConfigurerAdapter类

package com.miracle.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

// @Configuration注解声明这个类是配置类
// 需要继承类WebMvcConfigurerAdapter
@Configuration
public class MyMvcConfig extends WebMvcConfigurerAdapter {
    // 添加视图映射
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        // 添加视图映射(就相当于编写一个controller) addViewController参数为拦截路径  setViewName设置返回视图
        registry.addViewController("/").setViewName("index");
        registry.addViewController("/index.html").setViewName("index");
    }
}

六.页面登录

1.表单重复提交问题解决

如果前端登录页面采用POST表单数据的方式进行登录
后台编写对应的controller校验,如果登录成功,那么跳转到主页,这这时如果用户刷新页面,会造成表单重复提交
解决方案:登录controller,如果用户登录成功,应该采用重定向的方式,将页面重定向到新的url

在这里插入图片描述
在这里插入图片描述

2.利用拦截器进行登录检查
  • 1.当用户登录成功后,将用户登录信息添加到session中
    在这里插入图片描述

  • 2.编写拦截器,对页面访问进行校验

编写拦截器

/**
 *  登录检查拦截器
 *  自定义拦截器要实现 HandlerInterceptor
 */
public class LoginHandlerInterceptor implements HandlerInterceptor {
    // 目标方法执行之前
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String loginUser = (String)request.getSession().getAttribute("loginUser");
        if (loginUser == null){
            // 设置错误消息
            request.setAttribute("msg","没有权限请先登录");
            // 未登录,返回登录页
            request.getRequestDispatcher("/index.html").forward(request, response);
            return false;
        }else {
            // 已登录,放行请求
            return true;
        }
    }

向配置文件中注册拦截器

package com.atguigu.springboot.config;

import com.atguigu.springboot.component.LoginHandlerInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
public class MvcConfig extends WebMvcConfigurerAdapter {
    // 添加controller
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("login");
        registry.addViewController("/index.html").setViewName("login");
        registry.addViewController("/main.html").setViewName("dashboard");
    }

    // 添加自定义拦截器
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        /**
         * 注册自定义的拦截器
         * addPathPatterns("/**") 表示拦截哪些路径
         * excludePathPatterns("/index.html", "/", "/user/login") 表示不能拦截哪些路径(登录页面和登录请求)
         * springBoot默认做好排除静态资源,因此拦截器 不会拦截静态资源
         */
        registry.addInterceptor(new LoginHandlerInterceptor()).addPathPatterns("/**")
        .excludePathPatterns("/index.html", "/", "/user/login");
    }
}

七.页面提交数据格式化

1.对页面提交的日期进行格式化

查看WebMvcAutoConfiguration类

在这里插入图片描述
想修改默认的日期格式,可以在springBoot的配置文件中修改:spring.mvc.date.format属性

spring.mvc.date-format=yyyy-MM-dd HH:mm:ss

在这里插入图片描述
查看this.mvcProperties.getDateFormat()可知默认日期格式为 dd/MM/yyyy

八.定制错误响应

1.定制错误页面

(1)有模板引擎的情况下
  • 将错误页面命名为 错误状态码.html 放到模板引擎文件夹下的error文件夹中,发生此状态码的错误就会来到对应的页面
templates/error/错误状态码.html
  • 为每一个错误码都编写错误页面也很麻烦,因此如果是4xx的错误,可以编写4xx.html(5xx.html)页面,如果发生404错误时,404.html和4xx.html同时存在,那么优先匹配404.html
(2)没有模板引擎的情况下
  • 去静态资源文件夹下找,同上

2.定制错误数据

当其他类型客户端访问时,发生错误,由于springBoot自适应,会返回json数据,下面介绍如何定制错误json
相同访问,产生不同返回的原因:
这个请求头accept : text/html 所以返回html页面
在这里插入图片描述
这个请求头accept : / 所以返回json
在这里插入图片描述

自定义错误步骤:

package com.atguigu.springboot.controller;

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;

@ControllerAdvice
public class MyExceptionHandler {

    /**
     * 这里 @ExceptionHandler(UserNotExistException.class) 表示处理具体哪个类的异常
     * 如果要处理 所有异常 ExceptionHandler(ExistException.class)
     */
    @ExceptionHandler(Exception.class)
    public String handleException(Exception e, HttpServletRequest request){
        HashMap<String, Object> map = new HashMap<>();
        // 这里设置服务器响应的状态码
        request.setAttribute("javax.servlet.error.status_code", 520);

        // 这里添加错误信息
        map.put("code", "用户不存在");
        map.put("message", e.getMessage());

        // 设置完错误信息,要将map存入 request域中,传递给自定义的 ErrorAttributes
        request.setAttribute("ext", map);

        // 转发到 /error
        return "forward:/error";
    }
}
package com.atguigu.springboot.component;

import org.springframework.boot.autoconfigure.web.DefaultErrorAttributes;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import java.util.Map;

// 想容器中注册自定义的 ErrorAttributes
@Component                     // 要继承 DefaultErrorAttributes
public class MyErrorAttributes extends DefaultErrorAttributes {
    @Override
    public Map<String, Object> getErrorAttributes(RequestAttributes requestAttributes, boolean includeStackTrace) {
        Map<String, Object> map = super.getErrorAttributes(requestAttributes, includeStackTrace);

        /**
         * requestAttributes 是一个包装的 HttpServletRequest
         * 可以当作 HttpServletRequest 来使用,这里获取 request 域 存的数据
         *
         * getAttribute 第二个参数 0 代表 request域
         *                       1 代表 session域
         */
        Map<String, Object> extMap = (Map<String, Object>) requestAttributes.getAttribute("ext", 0);

        // 将 request 域中的 map数据 合并,并返回
        for (Map.Entry<String, Object> entry : extMap.entrySet()) {
            map.put(entry.getKey(), entry.getValue());
        }
        // 这里也可以添加返回的错误信息
        map.put("company", "neusoft");
        // 返回的 map 是 页面 和 json 能获取的所有字段
        return map;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值