一、SpringBoot基础

一、yaml对象赋值

  1. User实体类

    package com.jx.pojo;
    
    import lombok.AllArgsConstructor;
    import lombok.Data;
    import lombok.NoArgsConstructor;
    import org.springframework.boot.context.properties.ConfigurationProperties;
    import org.springframework.stereotype.Component;
    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    @Component//注册bean
    @ConfigurationProperties(prefix = "user")//与yaml中的类进行绑定
    public class User {
        private Integer id;
        private String username;
        private String password;
        private String name;
    }
    
    
  2. application.yaml

    user:
      name: jx
      username: root
      password: 123456
    
  3. 测试

    package com.jx;
    import com.jx.pojo.User;
    import org.junit.jupiter.api.Test;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.test.context.SpringBootTest;
    @SpringBootTest
    class SpringbootApplicationTests {
    @Autowired
    private User user;
        @Test
        void contextLoads() {
            System.out.println(user);
        }
    
    }
    

二、thymeleaf模板引擎

  1. 依赖

    		<!--thymeleaf-->
            <dependency>
                <groupId>org.thymeleaf</groupId>
                <artifactId>thymeleaf-spring5</artifactId>
            </dependency>
    
  2. 在templates文件夹下创建html文件

  3. 引入头文件

    <html lang="en"  xmlns:th="http://www.thymeleaf.org">
    
  4. 常用语法:

    <!--链接-->
    <a th:href="@{www.baidu.com}">[[#{国际化文本}]]</a>
    <!--资源引入-->
    <script th:src="@{/js/jquery-2.2.1.min.js}"></script>
    <!--对象属性-->
    <span th:text="${user.name}">
    <!--遍历集合-->    
    <ul th:each="item : ${items}">
       <li th:text="${item.property}"></li>
    </ul>     
    
  5. 示例 index.html

    <!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 th:href="@{/css/bootstrap.min.css}" rel="stylesheet">
    		<!-- Custom styles for this template -->
    		<link th:href="@{/css/signin.css}" rel="stylesheet">
    	</head>
    	<body class="text-center">
    		<form class="form-signin" th:action="@{/login}">
    			<img class="mb-4" th:src="@{/img/bootstrap-solid.svg}" alt="" width="72" height="72">
    			<h1 class="h3 mb-3 font-weight-normal" th:text="#{login.tip}"></h1>
    			<p style="color: red" th:text="${msg}" th:if="${not #strings.isEmpty(msg)}"></p>
    			<label class="sr-only"th:text="#{login.username}"></label>
    			<input type="text" class="form-control" th:placeholder="#{login.username}" required="" autofocus="" name="username">
    			<label class="sr-only" th:text="#{login.password}"></label>
    			<input type="password" class="form-control" th:placeholder="#{login.password}" required="" name="password">
    			<div class="checkbox mb-3">
    				<label>
              <input type="checkbox" value="remember-me" th:text="#{login.remember}">
            </label>
    			</div>
    			<button class="btn btn-lg btn-primary btn-block" type="submit">[[ #{login.login}]]</button>
    			<p class="mt-5 mb-3 text-muted">© 2017-2018</p>
    			<a class="btn btn-sm" th:href="@{/index.html(lang='zh_CN')}">中文</a>
    			<a class="btn btn-sm" th:href="@{/index.html(lang='en_US')}">English</a>
    		</form>
    	</body>
    </html>
    

三、自定义视图解析器

  1. 创建MyWebMvcConfig类继承WebMvcConfigurer类

    package com.jx.config;
    
    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 MyWebMvcConfig implements WebMvcConfigurer {
        //自定义视图解析
        @Override
        public void addViewControllers(ViewControllerRegistry registry) {
            registry.addViewController("/").setViewName("index");//视图映射
            registry.addViewController("/index.html").setViewName("index");
            registry.addViewController("/main.html").setViewName("dashboard");
        }
    }
    

四、国际化组件

  1. 创建i18n文件夹

  2. 创建三个配置文件

在这里插入图片描述

  1. 配置路径

    #国际化配置文件路径
    spring.messages.basename=i18n.login
    
  2. 创建地区解析类

    package com.jx.config;
    
    import org.springframework.util.StringUtils;
    import org.springframework.web.servlet.LocaleResolver;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.util.Locale;
    
    public class MyLocalResolver implements LocaleResolver {
    
        @Override
        public Locale resolveLocale(HttpServletRequest httpServletRequest) {
          String language = httpServletRequest.getParameter("lang");
            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) {
    
        }
    }
    
    
  3. 注册bean

     //国际化组件
        @Bean
        public LocaleResolver localeResolver(){
            return new MyLocalResolver();
        }
    

五、登录的实现

package com.jx.controller;

import com.jx.pojo.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import javax.servlet.http.HttpSession;

//@RestController返回字符串
@Controller
public class HelloController {
    @RequestMapping("/hello")
    public String hello(){
        return "hello,world";
    }
    @RequestMapping("/login")
    public String login(@RequestParam("username") String username,
                        @RequestParam("password") String password,
                        Model model,
                        HttpSession session){
        User user = new  User();
        user.setUsername(username);
        user.setPassword(password);
        if (username.equals("root")&&password.equals("123456")){
            System.out.println(user);
            session.setAttribute("loginUser",user);
            return "redirect:/main.html";
        }
        System.out.println(user);
        model.addAttribute("msg","用户名或密码错误");
        return "index";
    }

}

六、登录拦截器

  1. 定义登录拦截处理器类

    package com.jx.config;
    import org.springframework.web.servlet.HandlerInterceptor;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    public class LoginHandleInterceptor implements HandlerInterceptor {
        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
            Object loginUser = request.getSession().getAttribute("loginUser");
            if (loginUser==null){//没有登录
                request.setAttribute("msg","没有权限请先登录!");
                request.getRequestDispatcher("/index.html").forward(request,response);
                return false;
            }
            return true;
        }
    }
    
    
  2. 在MyWebMvcConfig中配置拦截器

    //登录拦截器
        @Override
        public void addInterceptors(InterceptorRegistry registry) {
            registry.addInterceptor(new LoginHandleInterceptor())
                    .addPathPatterns("/**")//拦截的url请求,拦截所有的请求
                    .excludePathPatterns("/index.html","/","/login","/css/**","/js/**","/img/**");//放行的请求
        }
    
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值