Spring-Boot的Web开发(一)

1. 概述

2. 导入静态资源文件

1.首先导入css,js.img文件.把这些文件全部放在static下的asserts目录下

静态资源文件夹

2. 导入html文件,把这些文件放入templates文件夹下面

html文件
  • 但是这些文件如果你直接访问localhost:8080是访问不到的

  • 默认访问的是静态资源文件夹下面的index.html页面,但是应该转到我们的login.html页面

  • 在项目下创建config包,创建MyMvcConfig

    public class MyMvcConfig implements WebMvcConfigurer {
    
    /**
     * 跳转到指定的页面
     * @param registry
     */
    public void addViewControllers(ViewControllerRegistry registry){
        registry.addViewController("/").setViewName("login");
        //遇到"index.html"自动转到"login.html"页面      
        registry.addViewController("/index.html").setViewName("login");
        }
    }
    
  • 这个类方法的作用就是把初始的请求转发到login.html这个响应,之后就可以在localhost:8080直接访问

3. 国际化(可以转变页面语言)

  • 通过浏览器的语言信息,动态调整浏览器的语言

1. Spring MVC步骤

  • 编写国际化配置文件
  • 使用ResourceBundleMessageSource管理国际化资源文件
  • 在页面使用fmt:message取出国际化内容

2. SpringBoot步骤

  • 编写国际化配置文件,抽取页面需要显示的消息

    国际化配置文件

  • SpringBoot自动配置好了管理国际化资源文件的组件,但是他默认是认为这个资源文件是放在classpath/目录下的,我们是把它放在了classpath/目录下的i18n目录下.所以我们需要重新配置一下它的位置

    spring.messages.basename=i18n.login
    
  • 去页面获取国际化的值,根据浏览器语言的信息进行设置的

    <!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" rel="stylesheet">
        <!-- Custom styles for this template -->
        <link href="asserts/css/signin.css" rel="stylesheet">
    </head>
    <body class="text-center">
        <form class="form-signin" action="dashboard.html">
            <img class="mb-4" 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">© 2019-2020</p>
            <a class="btn btn-sm">中文</a>
            <a class="btn btn-sm">English</a>
        </form>
    </body>
    </html>
    
  • 点击中英文按钮转变页面语言信息

    • 原理:国际化Local(区域信息对象):LocalResolver获取区域信息对象
    @Bean
        @ConditionalOnMissingBean
        @ConditionalOnProperty(
            prefix = "spring.mvc",
            name = {"locale"}
        )
        public LocaleResolver localeResolver() {
            if (this.mvcProperties.getLocaleResolver() == org.springframework.boot.autoconfigure.web.servlet.WebMvcProperties.LocaleResolver.FIXED) {
                return new FixedLocaleResolver(this.mvcProperties.getLocale());
            } else {
                AcceptHeaderLocaleResolver localeResolver = new AcceptHeaderLocaleResolver();
                localeResolver.setDefaultLocale(this.mvcProperties.getLocale());
                return localeResolver;
            }
        }
        
    
    • 默认的就是根据请求头带来的区域信息获取语言信息,如果我们想通过点击超链接按钮来获取网页的语言信息,我们就必须自己编写一个类来实现LocaleResolver接口
    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) {
        }
    }
    
    • 把自己编写好的MyLocaleResolver放在spring mvc的扩展功能的类MyMvcConfig里面
    /**
     * @description: 使用WebMvcConfigurer可以扩展spring mvc的功能
    * @Author: Mutong
    * @Date: 2020/2/2 15:49
    */
    @Configuration
    public class MyMvcConfig implements WebMvcConfigurer {
    /**
     * 注册一个自己编写的LocaleResolver,用来点击按钮实现国际化
     * @return
     */
    @Bean
    public LocaleResolver localeResolver(){
        return new MyLocaleResolver();
        }
    }
    
    • 同时改变HTML页面的中英文超链接
    <a class="btn btn-sm" th:href="@{/index.html(l='zh_CN')}">中文</a>
    <a class="btn btn-sm" th:href="@{/index.html(l='en_US')}">English</a>
    
    • 页面显示


      页面显示

      image

4. 登陆拦截

1. 表单提交

  • 完善html代码,根据下面的代码,把页面提交到http://localhost:8080/user/login页面
    <form class="form-signin" action="dashboard.html" th:action="@{/user/login}" method="post">

2. 编写loginController方法

@Controller
public class loginController {
    //@PostMapping(value = "/user/login")
    @RequestMapping(value = "/user/login",method = RequestMethod.POST)
    public String login(@RequestParam("username") String username,
                        @RequestParam("password") String password,
                        Map<String,Object> map){
        if (!StringUtils.isEmpty(username) && "123456".equals(password)){
            return "dashboard";
        }else{
            map.put("msg","用户名密码错误");
            return "login";
        }
    }
}

3. 登陆错误编写提示

  • 如果取到的msg不为空,则显示,否则不显示
    <p style="color: red" th:text="${msg}" th:if="${not #strings.isEmpty(msg)}"></p>

4. 登陆拦截

  • 完善loginController
    • Map<String,Object> map用一个map用来存储报错信息
    • HttpSession session获取登陆的用户名session.setAttribute("loginUser",username);
@Controller
public class loginController {
    //@PostMapping(value = "/user/login")
    @RequestMapping(value = "/user/login",method = RequestMethod.POST)
    public String login(@RequestParam("username") String username,
                        @RequestParam("password") String password,
                        Map<String,Object> map,
                        HttpSession session){
        if (!StringUtils.isEmpty(username) && "123456".equals(password)){
            session.setAttribute("loginUser",username);
            return "redirect:/main.html";
        }else{
            map.put("msg","用户名密码错误");
            return "login";
        }
    }
}
  • 编写loginHandlerInterceptor类来进行登陆检查
    • getAttribute("loginUser");获取到登陆用户
    • 判断user是否为空
/**
 * @description: 登陆检查
 * @Author: Mutong
 * @Date: 2020/2/2 20:57
 */
public class loginHandlerInterceptor implements HandlerInterceptor {
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Object user = request.getSession().getAttribute("loginUser");
        if (user == null){
            request.setAttribute("msg","没有权限,请先登录");
            request.getRequestDispatcher("/index.html").forward(request,response);
        }else{

        }
        return true;
    }
}
  • loginHandlerInterceptor放入到容器中
    • 拦截所有的请求addPathPatterns("/**")
    • 除了excludePathPatterns("/index.html","/","/user/login","/asserts/**");
    /**
     * 注册拦截器
     * @param registry
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new loginHandlerInterceptor()).addPathPatterns("/**").excludePathPatterns("/index.html","/","/user/login","/asserts/**");
    }
  • 页面显示
    image
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 218,640评论 6 507
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,254评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 165,011评论 0 355
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,755评论 1 294
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,774评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,610评论 1 305
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,352评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,257评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,717评论 1 315
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,894评论 3 336
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,021评论 1 350
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,735评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,354评论 3 330
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,936评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,054评论 1 270
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,224评论 3 371
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,974评论 2 355

推荐阅读更多精彩内容