欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

springboot第三天

程序员文章站 2024-03-23 23:15:58
...

springboot第三天

SpringBoot Web开发

  1. 创建应用,选择启动器
  2. https://docs.spring.io/spring-boot/docs/2.2.6.RELEASE/reference/html/using-spring-boot.html#using-boot-starter

xxxAUtoConfiguration:向容器中自动配置组件

xxxxProperties:自动配置类,装配配置文件中自定义的一些内容。

要解决的问题:

  • 导入静态资源
  • 首页
  • jsp,模板引擎Thymeleaf
  • 装配扩展SpringMVC
  • 增删改查
  • 拦截器
  • 国际化

静态资源导入

public void addResourceHandlers(ResourceHandlerRegistry registry) {
    if (!this.resourceProperties.isAddMappings()) {
        logger.debug("Default resource handling disabled");
    } else {
        Duration cachePeriod = this.resourceProperties.getCache().getPeriod();
        CacheControl cacheControl = this.resourceProperties.getCache().getCachecontrol().toHttpCacheControl();
        if (!registry.hasMappingForPattern("/webjars/**")) {
            this.customizeResourceHandlerRegistration(registry.addResourceHandler(new String[]{"/webjars/**"}).addResourceLocations(new String[]{"classpath:/META-INF/resources/webjars/"}).setCachePeriod(this.getSeconds(cachePeriod)).setCacheControl(cacheControl));
        }

        String staticPathPattern = this.mvcProperties.getStaticPathPattern();
        if (!registry.hasMappingForPattern(staticPathPattern)) {
            this.customizeResourceHandlerRegistration(registry.addResourceHandler(new String[]{staticPathPattern}).addResourceLocations(WebMvcAutoConfiguration.getResourceLocations(this.resourceProperties.getStaticLocations())).setCachePeriod(this.getSeconds(cachePeriod)).setCacheControl(cacheControl));
        }

    }
}

webjars:在项目中引入的静态资源,自动去/META-INF/resources/webjars/下找

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-jxtp8KZ8-1588345120201)(F:\spring boot\Snipaste_2020-04-27_21-44-19.png)]

https://www.webjars.org/

该网站下可以以jar包引入前端资源,在该网站下载的资源都符合以上方式。

springboot静态资源存放位置可以是如下四个位置,匹配/**的访问请求会默认到这四个文件夹下去寻找资源

“classpath:/META-INF/resources/”, 这个就是在引入的jar包中去找资源

“classpath:/resources/”, 优先级最高

“classpath:/static/”, 优先级其次 默认值

"classpath:/public/"优先级最低

 CLASSPATH_RESOURCE_LOCATIONS = new String[]{"classpath:/META-INF/resources/", "classpath:/resources/", "classpath:/static/", "classpath:/public/"};

设置主页面

@Bean
public WelcomePageHandlerMapping welcomePageHandlerMapping(ApplicationContext applicationContext, FormattingConversionService mvcConversionService, ResourceUrlProvider mvcResourceUrlProvider) {
    WelcomePageHandlerMapping welcomePageHandlerMapping = new WelcomePageHandlerMapping(new TemplateAvailabilityProviders(applicationContext), applicationContext, this.getWelcomePage(), this.mvcProperties.getStaticPathPattern());
    welcomePageHandlerMapping.setInterceptors(this.getInterceptors(mvcConversionService, mvcResourceUrlProvider));
    return welcomePageHandlerMapping;
}

private Optional<Resource> getWelcomePage() {
    String[] locations = WebMvcAutoConfiguration.getResourceLocations(this.resourceProperties.getStaticLocations());
    return Arrays.stream(locations).map(this::getIndexHtml).filter(this::isReadable).findFirst();
}

private Resource getIndexHtml(String location) {
    return this.resourceLoader.getResource(location + "index.html");
}

写一个 为index的页面放在静态资源存放位置中,会自动给跳转到该界面

设置页面图标

@Configuration
@ConditionalOnProperty(
    value = {"spring.mvc.favicon.enabled"},
    matchIfMissing = true
)
public static class FaviconConfiguration implements ResourceLoaderAware {
    private final ResourceProperties resourceProperties;
    private ResourceLoader resourceLoader;

    public FaviconConfiguration(ResourceProperties resourceProperties) {
        this.resourceProperties = resourceProperties;
    }

    public void setResourceLoader(ResourceLoader resourceLoader) {
        this.resourceLoader = resourceLoader;
    }

    @Bean
    public SimpleUrlHandlerMapping faviconHandlerMapping() {
        SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping();
        mapping.setOrder(-2147483647);
        mapping.setUrlMap(Collections.singletonMap("**/favicon.ico", this.faviconRequestHandler()));
        return mapping;
    }

第一步关闭默认图标

在配置文件中设置

sring.mvc.favicon.enabled=false

第二步

把名为favicon的图片放入静态资源夹

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-iOnU7QA7-1588345120205)(Snipaste_2020-04-30_16-07-27.png)]

模板引擎

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-4uEKKGo9-1588345120209)(Snipaste_2020-04-30_16-11-50.png)]

只要需要使用thymeleaf,只需要导入依赖就可以,把heml页面放在templates之中

引入Thymeleaf我们都是基于3.x开发的

<dependency>
   <groupId>org.thymeleaf</groupId>
   <artifactId>thymeleaf-spring5</artifactId>
</dependency>
<dependency>
   <groupId>org.thymeleaf.extras</groupId>
   <artifactId>thymeleaf-extras-java8time</artifactId>
</dependency>
<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

替换warjars

使用方法

导入命名空间

<html lang="en" xmlns:th="http://www.thymeleaf.org">

1)、th:text;改变当前元素里面的文本内容;

​ th:utext:改变当前元素里面的文本内容,不转义

th:each :遍历集合中的每个元素

<h1 th:each="user:${users}" th:text="${user}"></h1>

​ th:任意html属性;来替换原生属性的值

2)、表达式?t

Simple expressions:(表达式语法)
Variable Expressions: ${…}:获取变量值;OGNL;
1)、获取对象的属性、调用方法
2)、使用内置的基本对象:
#ctx : the context object.
#vars: the context variables.
#locale : the context locale.
#request : (only in Web Contexts) the HttpServletRequest object.
#response : (only in Web Contexts) the HttpServletResponse object.
#session : (only in Web Contexts) the HttpSession object.
#servletContext : (only in Web Contexts) the ServletContext object.

            ${session.foo}
        3)、内置的一些工具对象:

#execInfo : information about the template being processed.
#messages : methods for obtaining externalized messages inside variables expressions, in the same way as they would be obtained using #{…} syntax.
#uris : methods for escaping parts of URLs/URIs
#conversions : methods for executing the configured conversion service (if any).
#dates : methods for java.util.Date objects: formatting, component extraction, etc.
#calendars : analogous to #dates , but for java.util.Calendar objects.
#numbers : methods for formatting numeric objects.
#strings : methods for String objects: contains, startsWith, prepending/appending, etc.
#objects : methods for objects in general.
#bools : methods for boolean evaluation.
#arrays : methods for arrays.
#lists : methods for lists.
#sets : methods for sets.
#maps : methods for maps.
#aggregates : methods for creating aggregates on arrays or collections.
#ids : methods for dealing with id attributes that might be repeated (for example, as a result of an iteration).

Selection Variable Expressions: *{...}:选择表达式:和${}在功能上是一样;
	补充:配合 th:object="${session.user}:

Name: Sebastian.

Surname: Pepper.

Nationality: Saturn.

Message Expressions: #{...}:获取国际化内容
Link URL Expressions: @{...}:定义URL;
		@{/order/process(execId=${execId},execType='FAST')}
Fragment Expressions: ~{...}:片段引用表达式
		<div th:insert="~{commons :: main}">...</div>

Literals(字面量)
Text literals: ‘one text’ , ‘Another one!’ ,…
Number literals: 0 , 34 , 3.0 , 12.3 ,…
Boolean literals: true , false
Null literal: null
Literal tokens: one , sometext , main ,…
Text operations:(文本操作)
String concatenation: +
Literal substitutions: |The name is ${name}|
Arithmetic operations:(数学运算)
Binary operators: + , - , * , / , %)
Minus sign (unary operator): -
Boolean operations:(布尔运算)
Binary operators: and , or
Boolean negation (unary operator): ! , not
Comparisons and equality:(比较运算)
Comparators: > , < , >= , <= ( gt , lt , ge , le )
Equality operators: == , != ( eq , ne )
Conditional operators:条件运算(三元运算符)
If-then: (if) ? (then)
If-then-else: (if) ? (then) : (else)
Default: (value) ?: (defaultvalue)
Special tokens:
No-Operation: _

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-qM5bCxrc-1588345120214)(Snipaste_2020-04-30_20-53-30.png)]

扩展装配SPringMVC

扩展只需要定义一个类,一u定要有注释@Config

ration,不能有@EnableWebMvc(这个注解就是导入一个类DelegatingWebMvcConfiguration)并且该类必须是一个WebMvcConfigurer,会自动把该类注入到容器中,该类会放在config包下

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.util.Locale;
@Configuration
public class MyConfig implements WebMvcConfigurer {

    @Bean
    public ViewResolver  myViewResolver(){
        return new MyViewResolver();
    }
    public static class MyViewResolver implements ViewResolver{

        @Override
        public View resolveViewName(String s, Locale locale) throws Exception {
            return null;
        }
    }
}

所有自动配置原理都是一样的,首先看看有没有用户配置的,没有就用自动配置的,如果有些组件可以存在多个,就会把用户配置的和自己自动配置的结合起来

添加一个视图控制器

public class MyConfig implements WebMvcConfigurer {
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/b").setViewName("test");
    }
}

springboot中,有大量的xxxConfigurer帮助我们进行扩展配置,只要看见了,就需要注意扩展了什么功能。

实例

引入依赖lombok

<dependency>
   <groupId>org.projectlombok</groupId>
   <artifactId>lombok</artifactId>
</dependency>

实体类

@Data
@NoArgsConstructor
public class Employee {
    private Integer id;
    private String lastName;
    private String email;
    private Integer gender;
    private Department department;
    private Date birth;

    public Employee(Integer id, String lastName,String email,Integer gender, Department department) {
        this.id = id;
        this.lastName = lastName;
        this.email = email;
        this.gender = gender;
        this.department = department;
        this.birth = new Date();
    }

}
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Department {
    private Integer id;
    private String departmentName;
}

Dao层

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
@Repository
public class EmployeeDao {
    private static Map<Integer,Employee> employees= null;
    @Autowired
    private static DepartmentDao departmentDao;
    static{
        employees=new HashMap<Integer,Employee>();
        employees.put(1002,new Employee(1002,"AA","sadas.com",0,new Department(101,"教育部")));
        employees.put(1001,new Employee(1001,"AS","ASDASD.com",1,new Department(101,"教育部")));
        employees.put(1003,new Employee(1003,"AB","sadas.com",0,new Department(101,"教育部")));
    }
    private Integer initId=1006;
    public void addEmpolyee(Employee employee){
        if(employee.getId()==null){
            employee.setId(initId++);
        }
        employee.setDepartment(departmentDao.getDepartmentById(employee.getId()));
        employees.put(employee.getId(),employee);

    }
    public Collection<Employee> fingAll(){
        return employees.values();
    }
    public Employee getEmployeeById(Integer id){
        return employees.get(id);
    }
    public void deleteEmployee(Integer id){
        employees.remove(id);
    }
}
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
@Repository
public class DepartmentDao {
    private static Map<Integer,Department> departments= null;
    static{
        departments=new HashMap<Integer, Department>() ;
        departments.put(101,new Department(101,"教育部"));
        departments.put(102,new Department(102,"学生部"));
        departments.put(103,new Department(103,"运输部"));
        departments.put(104,new Department(104,"总理部"));
        departments.put(105,new Department(105,"医学部"));
    }
    public Collection<Department> getDepartment(){
        return departments.values();
    }
    public Department getDepartmentById(Integer id){
        return departments.get(id);
    }
}

配置首页所有静态资源都需要使用thymeleaf接管。

页面国际化

国际化的自动配置类: MessageSourceAutoConfiguration

在资源目录下建立一个文件夹名称是i18n

建立properties文件,名称格式为: 名称+国家名字缩写+语言缩写

用下划线相连,idea会自动创建一个文件Resource Bundle ‘名称’

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-umzXeDar-1588345120217)(Snipaste_2020-05-01_20-48-25.png)]

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-nwgX8EKZ-1588345120220)(Snipaste_2020-05-01_20-48-57.png)]

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-TzQ14cbt-1588345120221)(Snipaste_2020-05-01_20-50-20.png)]

在主配置文件中警醒如下设置:

spring.messages.basename=i18n.login

i18n.login是国际化配置文件所在地

在前端页面中使用#{…}来进行国际化

自定义LocaleResolver

public class MyLocalReserver implements LocaleResolver {
    /**
     * 解析请求
     * @param httpServletRequest
     * @return
     */
    @Override
    public Locale resolveLocale(HttpServletRequest httpServletRequest) {
        String language=httpServletRequest.getParameter("l");
        Locale locale=Locale.getDefault();
        //如果请求链接携带了国际化参数
        if(StringUtils.isEmpty(language)){
            String[] split=language.split("_");
            locale=new Locale(split[0],split[1]);
        }
        return locale;
    }

    @Override
    public void setLocale(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Locale locale) {

    }
}
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class MyConfig implements WebMvcConfigurer {


    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("index.html");
        registry.addViewController("/index").setViewName("index.html");
    }
    @Bean
    public LocaleResolver localeResolver(){
        return new MyLocalReserver();
        }
}
port org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class MyConfig implements WebMvcConfigurer {


    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("index.html");
        registry.addViewController("/index").setViewName("index.html");
    }
    @Bean
    public LocaleResolver localeResolver(){
        return new MyLocalReserver();
        }
}
相关标签: spring spring boot