SpringBoot详解(四) 从入门到入土 (web开发)

五、web开发

1.使用SpringBoot:

  • 创建SpringBoot应用,选中我们需要的模块

  • SpringBoot已经将这些场景配置好了,只需要在配置文件中指定少量的配置就可以运行

  • 自己编写业务代码

    自动配置原理:

回顾:
@Controller
public class HelloWorld {
    @ResponseBody
    @RequestMapping("/hello")
    public String helloWorld(){
        return "hello world";
    }
}

2.SpringBoot对静态资源的映射规则

@ConfigurationProperties(prefix = "spring.resources", ignoreUnknownFields = false)
public class ResourceProperties {
    //可以设置和静态资源有关的参数
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));
        }

    }
}

//配置欢迎面映射
@Bean
		public WelcomePageHandlerMapping welcomePageHandlerMapping(
            ApplicationContext applicationContext,FormattingConversionService mvcConversionService, ResourceUrlProvider mvcResourceUrlProvider) {
			WelcomePageHandlerMapping welcomePageHandlerMapping = new WelcomePageHandlerMapping(
					new TemplateAvailabilityProviders(applicationContext), applicationContext, getWelcomePage(),
					this.mvcProperties.getStaticPathPattern());
			welcomePageHandlerMapping.setInterceptors(getInterceptors(mvcConversionService, mvcResourceUrlProvider));
			return welcomePageHandlerMapping;
		}
  • 所有 /webjars/,都去 classpath:/META-INF/resources/webjars/ 找资源

    webjars:以jar包的形式引入静态资源

https://www.webjars.org/

在这里插入图片描述

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

<dependency>
    <groupId>org.webjars</groupId>
    <artifactId>jquery</artifactId>
    <version>3.4.1</version>
</dependency>
  • staticPathPattern = "/"** 访问当前项目的任何资源(静态资源目录)
"classpath:/META-INF/resources/",
"classpath:/resources/", 
"classpath:/static/", 
"classpath:/public/" 
"/":当前目录下的根路径

localhost:8080/abc === 去静态资源文件夹里面找abc

  • 欢迎面,静态资源文件夹下的所有index.html页面;被"/"映射**

localhost:8080/ 找index页面

  • 所有的/favicon.ico 都是在静态资源文件下找 只需要将favicon.ico放置于任意静态资源目录
  • 如何自定义静态资源目录(properties文件中 spring.resource.static-locations=classpath:/xxx,classpath:/xxxx) 自定义静态资源目录后

3.模板引擎

springBoot推荐使用Thymeleaf

语法简单功能强大

1.引入Thymeleaf

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

2.Thymeleaf使用&语法

@ConfigurationProperties(prefix = "spring.thymeleaf")
public class ThymeleafProperties {

	private static final Charset DEFAULT_ENCODING = Charset.forName("UTF-8");
	
	private static final MimeType DEFAULT_CONTENT_TYPE = MimeType.valueOf("text/html");
	
	public static final String DEFAULT_PREFIX = "classpath:/templates/";
	
	public static final String DEFAULT_SUFFIX = ".html";

  	//只要我们把HTML页面放入classpath:/templates/ Thymeleaf就能帮我们自动渲染

使用:

1、导入thymeleaf的名称空间

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

2、使用thymeleaf语法;

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    welcome
    <div th:text="${hello}"></div>
</body>
</html>

3.语法规则

在这里插入图片描述

4.lombok

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

六、CRUD

1.默认访问首页

@Configuration
public class MyMvcConfig implements WebMvcConfigurer {
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("login");
        registry.addViewController("/index.html").setViewName("login");
    }
}

2.国际化

步骤

  • 编写 国际化配置文件,抽取页面所需要显示的国际化信息
    在这里插入图片描述

SpringBoot自动配置好了管理国际化资源文件的组件

@ConfigurationProperties(prefix = "spring.messages")
public class MessageSourceAutoConfiguration {
/**
Comma-separated list of basenames (essentially a fully-qualified classpath

location), each following the ResourceBundle convention with relaxed support for

slash based locations. If it doesn't contain a package qualifier (such as

"org.mypackage"), it will be resolved from the classpath root.
*/
private String basename = "messages";  
//我们的配置文件可以直接放在类路径下叫messages.properties;

@Bean
public MessageSource messageSource() {
	ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
	if (StringUtils.hasText(this.basename)) {
        //设置国际化资源文件的基础名(去掉语言国家代码的)
		messageSource.setBasenames(StringUtils.commaDelimitedListToStringArray(
				StringUtils.trimAllWhitespace(this.basename)));
	}
	if (this.encoding != null) {
		messageSource.setDefaultEncoding(this.encoding.name());
	}
	messageSource.setFallbackToSystemLocale(this.fallbackToSystemLocale);
	messageSource.setCacheSeconds(this.cacheSeconds);
	messageSource.setAlwaysUseMessageFormat(this.alwaysUseMessageFormat-  );
	return messageSource;
}
<h1 class="h3 mb-3 font-weight-normal" th:text="#{login.tip}">Please sign in</h1>

label class="sr-only" th:text="#{login.username}">Username</label>
			<input type="text" class="form-control" placeholder="Username" th:placeholder="#{login.username}" required="" autofocus="">
  • 去页面获取国际化的值

原理:

​ 国际化Locale(区域信息对象);LocaleResolver(获取区域信息对象);

@Bean
	@ConditionalOnMissingBean
	@ConditionalOnProperty(prefix = "spring.mvc", name = "locale")
	public LocaleResolver localeResolver() {
		if (this.mvcProperties
				.getLocaleResolver() == WebMvcProperties.LocaleResolver.FIXED) {
			return new FixedLocaleResolver(this.mvcProperties.getLocale());
		}
		AcceptHeaderLocaleResolver localeResolver = new AcceptHeaderLocaleResolver();
		localeResolver.setDefaultLocale(this.mvcProperties.getLocale());
		return localeResolver;
	}

默认的就是根据请求头带来的区域信息获取Locale进行国际化

  • 点击链接切换国际化

    /**
     * 可以在连接上携带区域信息
     */
    public class MyLocaleResolver implements LocaleResolver {
        
        @Override
        public Locale resolveLocale(HttpServletRequest request) {
            String l = request.getParameter("l");
            Locale locale = Locale.getDefault();
            if(!StringUtils.isEmpty(l)){
                String[] split = l.split("_");
                locale = new Locale(split[0],split[1]);
            }
            return locale;
        }
    
        @Override
        public void setLocale(HttpServletRequest request, HttpServletResponse response, Locale locale) {
    
        }
    }
    
    
     @Bean
        public LocaleResolver localeResolver(){
            return new MyLocaleResolver();
        }
    }
    

下一篇学习
SpringBoot详解(五) 从入门到入土 (整合Mybatis)

猜你喜欢

转载自blog.csdn.net/weixin_45262118/article/details/108483840
今日推荐