Springboot的簡(jiǎn)單RestfulCRUD實(shí)驗(yàn)(上)

代碼鏈接
Springboot的簡(jiǎn)單RestfulCRUD實(shí)驗(yàn)下

一、引入資源

1、先導(dǎo)入對(duì)應(yīng)的pom依賴
我這里就只寫了一點(diǎn)關(guān)鍵的依賴

<!--引入web模塊-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!--引入jquery-webjar-->
        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>jquery</artifactId>
            <version>3.4.1</version>
        </dependency>

        <!--引入bootstrap-->
        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>bootstrap</artifactId>
            <version>4.0.0</version>
        </dependency>
        <!--引入后就可以不用set.get方法了-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.12</version>
        </dependency>

2、引入的資源的放置位置

1

3、項(xiàng)目的架構(gòu)
2

二、登陸界面的國際化

1、展示界面
中文:

3

英文:
4

步驟:

1. 編寫國際化配置文件

5

2。SpringBoot自動(dòng)配置好了管理國際化資源文件的組件;

@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)) {
            //設(shè)置國際化資源文件的基礎(chǔ)名(去掉語言國家代碼的)
            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;
    }

3.去頁面獲取國際化的值

<!DOCTYPE html>
<html lang="en"  xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
        <meta name="description" content="">
        <meta name="author" content="">
        <title>Signin Template for Bootstrap</title>
        <!-- Bootstrap core CSS -->
        <link href="asserts/css/bootstrap.min.css" th:href="@{/webjars/bootstrap/4.0.0/css/bootstrap.css}" rel="stylesheet">
        <!-- Custom styles for this template -->
        <link href="asserts/css/signin.css" th:href="@{/asserts/css/signin.css}" rel="stylesheet">
    </head>

    <body class="text-center">
        <form class="form-signin" action="dashboard.html">
            <img class="mb-4" th:src="@{/asserts/img/bootstrap-solid.svg}" src="asserts/img/bootstrap-solid.svg" alt="" width="72" height="72">
            <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="">
            <label class="sr-only" th:text="#{login.password}">Password</label>
            <input type="password" class="form-control" placeholder="Password" th:placeholder="#{login.password}" required="">
            <div class="checkbox mb-3">
                <label>
                <input type="checkbox" value="remember-me"/> [[#{login.remember}]]
        </label>
            </div>
            <button class="btn btn-lg btn-primary btn-block" type="submit" th:text="#{login.btn}">Sign in</button>
            <p class="mt-5 mb-3 text-muted">? 2017-2018</p>
            <a class="btn btn-sm">中文</a>
            <a class="btn btn-sm">English</a>
        </form>

    </body>

</html>

效果:根據(jù)瀏覽器語言設(shè)置的信息切換了國際化;

原理:

? 國際化Locale(區(qū)域信息對(duì)象);LocaleResolver(獲取區(qū)域信息對(duì)象);

@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;
        }
默認(rèn)的就是根據(jù)請(qǐng)求頭帶來的區(qū)域信息獲取Locale進(jìn)行國際化

4.點(diǎn)擊鏈接切換國際化

/**
 * 可以在連接上攜帶區(qū)域信息
 */
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();
    }
}

5.進(jìn)行登錄
開發(fā)期間模板引擎頁面修改以后,要實(shí)時(shí)生效

1)、禁用模板引擎的緩存

# 禁用緩存
spring.thymeleaf.cache=false 

2)、頁面修改完成以后ctrl+f9:重新編譯;

登陸錯(cuò)誤消息的顯示

<p style="color: red" th:text="${msg}" th:if="${not #strings.isEmpty(msg)}"></p>

6.攔截器進(jìn)行登陸檢查
攔截器

/**
 * 登陸檢查,
 */
public class LoginHandlerInterceptor implements HandlerInterceptor {
    //目標(biāo)方法執(zhí)行之前
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Object user = request.getSession().getAttribute("loginUser");
        if(user == null){
            //未登陸,返回登陸頁面
            request.setAttribute("msg","沒有權(quán)限請(qǐng)先登陸");
            request.getRequestDispatcher("/index.html").forward(request,response);
            return false;
        }else{
            //已登陸,放行請(qǐng)求
            return true;
        }

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}

注冊(cè)攔截器

 //所有的WebMvcConfigurerAdapter組件都會(huì)一起起作用
    @Bean //將組件注冊(cè)在容器
    public WebMvcConfigurerAdapter webMvcConfigurerAdapter(){
        WebMvcConfigurerAdapter adapter = new WebMvcConfigurerAdapter() {
            @Override
            public void addViewControllers(ViewControllerRegistry registry) {
                registry.addViewController("/").setViewName("login");
                registry.addViewController("/index.html").setViewName("login");
                registry.addViewController("/main.html").setViewName("dashboard");
            }

            //注冊(cè)攔截器
            @Override
            public void addInterceptors(InterceptorRegistry registry) {
                //super.addInterceptors(registry);
                //靜態(tài)資源;  *.css , *.js
                //SpringBoot已經(jīng)做好了靜態(tài)資源映射
                registry.addInterceptor(new LoginHandlerInterceptor()).addPathPatterns("/**")
                        .excludePathPatterns("/index.html","/","/user/login");
            }
        };
        return adapter;
    }
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 1、簡(jiǎn)介 使用Spring Boot: (1)、創(chuàng)建Spring Boot應(yīng)用,添加需要的模塊; (2)、Spri...
    木石前盟Caychen閱讀 1,307評(píng)論 0 6
  • 素言小云閱讀 182評(píng)論 0 0
  • 走過一段路,留下一段情 驀然回首,殘影依舊 回憶總是在支離破碎 無奈那歲月的翻滾 情意,今生難以忘記 我會(huì)永遠(yuǎn)記在...
    一樹梨香閱讀 160評(píng)論 0 0
  • 網(wǎng)址:https://icomoon.io/ 1、上傳.svg文件 設(shè)計(jì)人員會(huì)給我們一個(gè).svg的文件(1) 2、...
    大慶無疆閱讀 465評(píng)論 0 1

友情鏈接更多精彩內(nèi)容