Springboot使用Bootstrap和thymeleaf路径问题,拦截器访问静态资源问题

Springboot使用Bootstrap和thymeleaf路径问题

这是项目结构
在这里插入图片描述
引入bootstrap依赖之后,目录结构
在这里插入图片描述

  1. application.properties重点在这行代码spring.mvc.static-path-pattern=/static/**设置静态资源映射路径
spring.messages.basename=i18n.login
server.port=8888
spring.thymeleaf.cache=false
spring.mvc.static-path-pattern=/static/**
  1. login.html重点在:
    href路径填写自己项目中静态资源的访问路径,和之前在application.properties文件中写的静态资源映射一致,如下
    th:href的路径根据依赖中的目录结构编写

在这里插入图片描述

 <link href="/static/css/bootstrap.min.css" 
 		th:href="@{/webjars/bootstrap/4.0.0/css/bootstrap.min.css}" rel="stylesheet" />
 <link href="/static/css/signin.css" 
 		th:href="@{/static/css/signin.css}" rel="stylesheet" />
/** 
如果没有配置静态资源路径,默认取/**静态资源的文件夹里面查找,
"classpath:/META-INF/resources/", 
"classpath:/resources/",
"classpath:/static/", 
"classpath:/public/" 
"/":当前项目的根路径
**/
<link th:href="@{/css/signin.css}" rel="stylesheet">
//这种也是可以的鼠标点不进去,但是能访问http://localhost:8888/css/signin.css

如果路径编写成功按ctrl键的同时点击路径会有下划线并跳转导该文件,如果没有则是路径写错了

完整html文件

<!DOCTYPE html>
<!-- saved from url=(0051)https://getbootstrap.com/docs/4.1/examples/sign-in/ -->
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<!--<html lang="en">-->
<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="" />
    <link rel="icon" href="https://getbootstrap.com/favicon.ico" />

    <title>登录页面</title>

    <!-- Bootstrap core CSS -->
    
    <link href="/static/css/bootstrap.min.css" th:href="@{/webjars/bootstrap/4.0.0/css/bootstrap.min.css}" rel="stylesheet" />

    <!-- Custom styles for this template -->
  
    <link href="/static/css/signin.css" th:href="@{/static/css/signin.css}" rel="stylesheet" />
  </head>

  <body class="text-center" th:inline="text">
1
    <form class="form-signin" th:action="@{/user/login}" method="post">
      <h1 class="h3 mb-3 font-weight-normal" th:text="#{login.tip}">Please sign in</h1>
        <!--判断-->
        <p style="color: red" th:text="${msg}" th:if="${not #strings.isEmpty(msg)}"></p>
      <label  class="sr-only" th:text="#{login.username}">Username</label>
      <input type="text"  name="username" class="form-control" placeholder="Username" th:placeholder="#{login.username}" required="" autofocus=""/>
      <label for="inputPassword" class="sr-only" th:text="#{login.password}">Password</label>
      <input type="password" name="password" id="inputPassword" 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 href="#" class="btn btn-sm" th:href="@{/index.html(l='zh_CN')}">中文</a>
        <a href="#" class="btn btn-sm" th:href="@{/index.html(l='en_US')}">English</a>
    </form>
  

</body>
</html>

自定义拦截器:

package com.lx.spbtcrud.component;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @ClassName LoginHandlerInteceptor
 * @Description: 拦截器,拦截未登录用户对其他页面的访问
 * @Author LX
 * @Date 2019/11/19
 * @Version V1.0
 **/
public class LoginHandlerInterceptor implements HandlerInterceptor{

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Object user = request.getSession().getAttribute("loginUser");
        if (user != null) {
            return true;
        }else{
            request.setAttribute("msg","请先登录");
            request.getRequestDispatcher("/index.html").forward(request,response);
            return false;
        }
    }

    @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 {

    }
}

注册拦截器:

  1. /项目根目录下
  2. /*拦截一层,例如:拦截addPathPatterns("/a/*"),则路径为/a/b会被拦截,/a/b/c不会拦截
  3. /**拦截两层,即/a/b/c也会被拦截。

注意:

  1. springboot2.0+版本不会自动映射静态资源,需要自己添加排除。
  2. 此前html文件中href用到的静态文件是在static目录下的,th:href所用的的文件是webjars目录下,
  3. 加上excludePathPatterns("/index.html","/","/user/login","/static/**","/webjars/**");解决问题
package com.lx.spbtcrud.config;


import com.lx.spbtcrud.component.LoginHandlerInterceptor;
import com.lx.spbtcrud.component.MyLocaleResolver;
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.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
public class MyMvcConfig extends WebMvcConfigurerAdapter {


    public void addViewController(ViewControllerRegistry registry) {

        registry.addViewController("/").setViewName("success");
    }
    @Bean //註冊到容器去
    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");
            }
            //注册拦截器
            @Override
            public void addInterceptors(InterceptorRegistry registry) {

              registry.addInterceptor(new LoginHandlerInterceptor()).addPathPatterns("/**").
                        excludePathPatterns("/index.html","/","/user/login","/static/**","/webjars/**");
            }
        };
        return adapter;
    }

    @Bean
    public LocaleResolver localeResolver(){
        return new MyLocaleResolver();
    }
}

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
实现前端页面分页,可以按照以下步骤进行: 1. 在前端页面中添加分页组件,例如bootstrap的分页组件,或者自己写一个分页组件。 2. 在后端接口中,通过mybatis查询数据库中的数据,并将查询到的数据返回给前端。 3. 在后端接口中,通过springboot的PageHelper插件对查询结果进行分页处理,得到分页后的数据。 4. 将分页后的数据返回给前端,并在前端页面中显示分页数据。 5. 在前端页面中,监听分页组件的事件,例如翻页、改变每页显示条数等事件,将事件参数传递给后端接口,重新查询并分页处理数据,更新前端页面显示的数据。 下面是一个使用thymeleaf模板引擎的示例代码: Controller代码: ```java @GetMapping("/list") public String list(Model model, @RequestParam(defaultValue = "1") int pageNum, @RequestParam(defaultValue = "10") int pageSize) { PageHelper.startPage(pageNum, pageSize); List<User> userList = userService.getUserList(); PageInfo<User> pageInfo = new PageInfo<User>(userList); model.addAttribute("pageInfo", pageInfo); return "user/list"; } ``` Thymeleaf页面代码: ```html <div class="container"> <table class="table table-striped"> <thead> <tr> <th>ID</th> <th>用户名</th> <th>邮箱</th> </tr> </thead> <tbody> <tr th:each="user : ${pageInfo.list}"> <td th:text="${user.id}"></td> <td th:text="${user.username}"></td> <td th:text="${user.email}"></td> </tr> </tbody> </table> <ul class="pagination"> <li th:class="${pageInfo.isFirstPage() ? 'disabled' : ''}"> <a th:href="@{${#httpServletRequest.requestURI}(pageNum=1,pageSize=${pageInfo.pageSize})}">«</a> </li> <li th:class="${pageInfo.isFirstPage() ? 'disabled' : ''}"> <a th:href="@{${#httpServletRequest.requestURI}(pageNum=${pageInfo.prePage},pageSize=${pageInfo.pageSize})}">‹</a> </li> <li th:each="page : ${pageInfo.navigatepageNums}" th:class="${page == pageInfo.pageNum ? 'active' : ''}"> <a th:href="@{${#httpServletRequest.requestURI}(pageNum=${page},pageSize=${pageInfo.pageSize})}" th:text="${page}"></a> </li> <li th:class="${pageInfo.isLastPage() ? 'disabled' : ''}"> <a th:href="@{${#httpServletRequest.requestURI}(pageNum=${pageInfo.nextPage},pageSize=${pageInfo.pageSize})}">›</a> </li> <li th:class="${pageInfo.isLastPage() ? 'disabled' : ''}"> <a th:href="@{${#httpServletRequest.requestURI}(pageNum=${pageInfo.pages},pageSize=${pageInfo.pageSize})}">»</a> </li> </ul> </div> ``` 在上述代码中,使用了PageHelper插件对查询结果进行分页处理,并将分页信息放入PageInfo对象中,然后将PageInfo对象放入Model中,传递给Thymeleaf模板引擎进行渲染。在Thymeleaf页面中,使用bootstrap的分页组件,根据PageInfo对象中的分页信息动态生成分页按钮,并监听按钮的点击事件,通过URL传递参数给后端接口重新查询并分页处理数据,更新前端页面显示的数据。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值