SpringBoot简单Web项目开发

springBoot基础Web项目开发

要解决的问题:

  • 导入静态资源
  • 首页
  • jsp,模板引擎Thymeleaf
  • 装配扩展SpringMVC
  • crud
  • 拦截器
  • 扩展:国际化

1 静态资源

protected void addResourceHandlers(ResourceHandlerRegistry registry) {
    super.addResourceHandlers(registry);
    if (!this.resourceProperties.isAddMappings()) {
        logger.debug("Default resource handling disabled");
    } else {
        ServletContext servletContext = this.getServletContext();
        this.addResourceHandler(registry, "/webjars/**", "classpath:/META-INF/resources/webjars/");
        this.addResourceHandler(registry, this.mvcProperties.getStaticPathPattern(), (registration) -> {
            registration.addResourceLocations(this.resourceProperties.getStaticLocations());
            if (servletContext != null) {
                registration.addResourceLocations(new Resource[]{
                    new ServletContextResource(servletContext, "/")
                });
            }

        });
    }
}

方式1:locallhoust:8080/webjars/…

需要导入jqery,基本上很少使用这种方法导入静态资源

addResourceHandler方法映射了资源目录,可以将导入的jar包路径缩写,就形成了上面的url。

"classpath:/META-INF/resources/", "classpath:/resources/", "classpath:/static/", "classpath:/public/"

根据源码可以知道在以上这些目录都能放静态资源,优先级依次递减

另外也有一个/** 被定义了,这是默认的资源目录,也就是说标准目录resources下的所有静态资源文件也都能找到

this.mvcProperties.getStaticPathPattern()

另外也可以通过配置文件加入spring.mvc.static-path-pattern=…来自定义配置,但用这种方法的话其他所有静态资源目录都会失效。

2 Thymeleaf的基本使用

首页index.html,放在标准目录下的public下。也可以自己定制首页路径,使用controller或者配置类来配置首页。

thymeleaf:

导入thymeleaf头文件:

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

常用标签

<!--忽视html标签-->
<div th:text="${msg}"></div>
<!--识别字符串中的html标签-->
<div th:utext="${msg}"></div>

遍历:

<!--th:each遍历-->
<h3 th:each="user:${users}" th:text="${user}"></h3>
<!--第二种写法-->
<h3 th:each="user:${users}">[[${user}]]</h3>

注意:url使用@{}来引用

3 装配扩展SpringMVC

如何自定义添加自己的MVC视图解析器

//如果 想diy一些定制化的功能,只要写这个组件,然后把他交给springboot,springboot会帮我们自动装配
//扩展springMVC  DispatcherServlet
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {

    //ViewResolver 实现了视图解析器的类,我们就可以把它看成视图解析器

    @Bean
    public ViewResolver myViewResolver(){
        return new MyViewResolver();
    }


    //自定义了一个视图解析器MyViewResolver
    public static class MyViewResolver implements ViewResolver {
        @Override
        public View resolveViewName(String s, Locale locale) throws Exception {
            return null;
        }
    }
}

image-20210214161701152

//如果要扩展springMVC,官方建议我们这样做
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {
    //视图跳转
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/qtds").setViewName("test");

    }
}

4 拦截器

1、 编写拦截器类

public class LoginHandlerInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //登录成功之后应该有用户的session
        Object loginUser = request.getSession().getAttribute("loginUser");

        if (loginUser == null) {//没有登录
            request.setAttribute("msg","请登录");
            request.getRequestDispatcher("/index.html").forward(request,response);
            return false;
        }
        return true;
    }

}

2、在自定义的mvc配置文件中配置拦截器:

//重写添加拦截器方法addInterceptors
@Override
public void addInterceptors(InterceptorRegistry registry) {
    registry.addInterceptor(new LoginHandlerInterceptor())
        		//表示拦截所有请求
                .addPathPatterns("/**")	
        		//放行的请求
                .excludePathPatterns("/index.html","/","/user/login","/css/*","/js/**","/img/**","/emp/**");
}

5 抽取公共界面

先提取公共部分,标签内加上:th:fragment="Sidebar"

之后在需要使用的地方添加:

<div th:insert="~{dashboard::Sidebar}"></div>

如果要传递参数,thymeleaf可以直接使用()传参,不再需要用?。

6 crud

没什么好写的,都是基础

注意日期格式,spring默认日期格式为:2020/1/1,以/连接,如果需要更改,在配置文件里修改:

spring.mvc.format.date=dd-MM-yyyy

thymeleaf循环遍历,使用th:each

<option th:each="dept:${departments}"
      th:text="${dept.getDepartmentName()}"
      th:value="${dept.getId()}">
</option>
<tr th:each="emp:${emps}">
   <td th:text="${emp.getId()}"></td>
   <td th:text="${emp.getLastName()}"></td>
   <td th:text="${emp.getEmail()}"></td>
   <td th:text="${emp.getGender()==0?'':''}"></td>
   <td th:text="${emp.getDepartment().getDepartmentName()}"></td>
   <td th:text="${#dates.format(emp.getBirth(),'yyyy-MM-dd HH:mm:ss')}"></td>
   <td>
      <button class="btn btn-sm btn-primary">编辑</button>
      <button class="btn btn-sm btn-danger">删除</button>
   </td>
</tr>

thymeleaf restful风格:

<a th:href="@{/emp/{id}(id=${emp.getId()})}">编辑</a>

扩展:国际化

1 配置i18n文件

2 我们如果需要在项目中进行按钮切换,我们需要自定义一个组件,实现LocaleResolver接口

public class MyLocaleResolver implements LocaleResolver {

    //解析请求
    @Override
    public Locale resolveLocale(HttpServletRequest request) {
        //获取请求中的语言参数
        String language = request.getParameter("language");

        Locale locale = Locale.getDefault();    //如果没有就用默认的

        //如果有参数
        if(!StringUtils.isEmpty(language)){
            //zh_CN
            final String[] splict = language.split("_");
            //语言,国家
            locale = new Locale(splict[0], splict[1]);
        }

        return locale;
    }

    @Override
    public void setLocale(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Locale locale) {

    }
}

3 记得将自己写的组件配置到spring容器中@Bean

//自定义的国际化组件
@Bean
public LocaleResolver localeResolver(){
    return new MyLocaleResolver();
}

4 Thymeleaf使用#{}取值

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要搭建一个Spring Boot的Web项目,可以按照以下步骤进行操作: 1. 使用IDE(如IntelliJ IDEA)创建一个新的Spring Boot项目。 2. 在创建项目时,选择Spring Web作为依赖项,以支持Web开发。 3. 在创建项目后,确保pom.xml文件中包含了必要的依赖项,如Thymeleaf模板引擎和MySQL数据库驱动程序。 4. 在项目的主类(通常是DemoApplication.java)上添加@SpringBootApplication注解以标识为Spring Boot的启动类。 5. 在主类中添加main方法,使用SpringApplication.run(DemoApplication.class, args)来启动应用程序。 6. 创建一个新的HTML文件(如index.html),并将其放置在resources/templates目录下。在该HTML文件中,可以使用Thymeleaf来渲染动态内容。 7. 在HTML文件中,使用Thymeleaf的语法来插入动态内容,比如使用th:text属性来设置文本内容。 8. 运行应用程序,并在浏览器中访问http://localhost:8080(默认情况下)来查看你的Spring Boot Web项目。 请注意,在创建项目的过程中,你还可以根据需要选择其他依赖项,如数据库访问框架(如MyBatis)或其他功能模块。可以在pom.xml文件中添加相应的依赖项来支持这些功能。 以上是搭建Spring Boot Web项目的基本步骤,希望对你有所帮助。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *3* [springboot搭建web项目完整步骤(简易,一看就会!)](https://blog.csdn.net/weixin_56281219/article/details/117121783)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *2* [springboot搭建web项目完整步骤](https://blog.csdn.net/qq_39946015/article/details/104527057)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值