Springboot学习~5:Web开发介绍

简介

使用SpringBoot;
1)、建立SpringBoot应用,选中咱们须要的模块;
2)、SpringBoot已经默认将这些场景配置好了,只须要在配置文件中指定少许配置就能够运行起来
3)、本身编写业务代码;css

自动配置原理?
这个场景SpringBoot帮咱们配置了什么?能不能修改?能修改哪些配置?能不能扩展?xxxhtml

xxxxAutoConfiguration:帮咱们给容器中自动配置组件;
xxxxProperties:配置类来封装配置文件的内容;

SpringBoot对静态资源的映射规则

@ConfigurationProperties(prefix = "spring.resources", ignoreUnknownFields = false)
public class ResourceProperties implements ResourceLoaderAware {
  //能够设置和静态资源有关的参数,缓存时间等
WebMvcAuotConfiguration:
        @Override
        public void addResourceHandlers(ResourceHandlerRegistry registry) {
            if (!this.resourceProperties.isAddMappings()) {
                logger.debug("Default resource handling disabled");
                return;
            }
            Integer cachePeriod = this.resourceProperties.getCachePeriod();
            if (!registry.hasMappingForPattern("/webjars/**")) {
                customizeResourceHandlerRegistration(
                        registry.addResourceHandler("/webjars/**")
                                .addResourceLocations(
                                        "classpath:/META-INF/resources/webjars/")
                        .setCachePeriod(cachePeriod));
            }
            String staticPathPattern = this.mvcProperties.getStaticPathPattern();
            //静态资源文件夹映射
            if (!registry.hasMappingForPattern(staticPathPattern)) {
                customizeResourceHandlerRegistration(
                        registry.addResourceHandler(staticPathPattern)
                                .addResourceLocations(
                                        this.resourceProperties.getStaticLocations())
                        .setCachePeriod(cachePeriod));
            }
        }

        //配置欢迎页映射
        @Bean
        public WelcomePageHandlerMapping welcomePageHandlerMapping(
                ResourceProperties resourceProperties) {
            return new WelcomePageHandlerMapping(resourceProperties.getWelcomePage(),
                    this.mvcProperties.getStaticPathPattern());
        }

       //配置喜欢的图标
        @Configuration
        @ConditionalOnProperty(value = "spring.mvc.favicon.enabled", matchIfMissing = true)
        public static class FaviconConfiguration {

            private final ResourceProperties resourceProperties;

            public FaviconConfiguration(ResourceProperties resourceProperties) {
                this.resourceProperties = resourceProperties;
            }

            @Bean
            public SimpleUrlHandlerMapping faviconHandlerMapping() {
                SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping();
                mapping.setOrder(Ordered.HIGHEST_PRECEDENCE + 1);
                //全部  **/favicon.ico 
                mapping.setUrlMap(Collections.singletonMap("**/favicon.ico",
                        faviconRequestHandler()));
                return mapping;
            }

            @Bean
            public ResourceHttpRequestHandler faviconRequestHandler() {
                ResourceHttpRequestHandler requestHandler = new ResourceHttpRequestHandler();
                requestHandler
                        .setLocations(this.resourceProperties.getFaviconLocations());
                return requestHandler;
            }

        }

==1)、全部 /webjars/** ,都去 classpath:/META-INF/resources/webjars/ 找资源;==
webjars:以jar包的方式引入静态资源; http://www.webjars.org/
前端

localhost:8080/webjars/jquery/3.3.1/jquery.js:java

<!--引入jquery-webjar-->在访问的时候只须要写webjars下面资源的名称便可
        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>jquery</artifactId>
            <version>3.3.1</version>
        </dependency>

==2)、"/**" 访问当前项目的任何资源,都去(静态资源的文件夹)找映射==mysql

"classpath:/META-INF/resources/", 
"classpath:/resources/",
"classpath:/static/", 
"classpath:/public/" 
"/":当前项目的根路径

localhost:8080/abc === 去静态资源文件夹里面找abcjquery

==3)、欢迎页; 静态资源文件夹下的全部index.html页面;被"/**"映射;==
​ localhost:8080/ 找index页面web

==4)、全部的 **/favicon.ico 都是在静态资源文件下找;==spring

本身定义静态文件夹的路径:
本身定义了以后,默认的静态资源文件夹就不能使用了sql

JSON接口开发

在之前的项目中,使用JSON接口须要:数据库

  1. 添加 jackjson 等相关 jar 包
  2. 配置 Spring Controller 扫描
  3. 对接的方法添加 @ResponseBody

Spring Boot只须要类添加 @RestController 便可,默认类中的方法都会以 json 的格式返回

@RestController
public class HelloController {
    @RequestMapping("/getUser")
    public User getUser() {
        User user=new User();
        user.setUserName("小明");
        user.setPassWord("xxxx");
        return user;
    }
}

若是须要使用页面开发只要使用@Controller注解便可

自定义Filter

咱们经常在项目中会使用 filters 用于录调用日志、排除有 XSS 威胁的字符、执行权限验证等等。Spring Boot 自动添加了 OrderedCharacterEncodingFilter 和 HiddenHttpMethodFilter,而且咱们能够自定义 Filter。
两个步骤:

  • 实现 Filter 接口,实现 Filter 方法
  • 添加@Configuration 注解,将自定义Filter加入过滤链
@Configuration
public class WebConfiguration {
    @Bean
    public RemoteIpFilter remoteIpFilter() {
        return new RemoteIpFilter();
    }
    
    @Bean
    public FilterRegistrationBean testFilterRegistration() {

        FilterRegistrationBean registration = new FilterRegistrationBean();
        registration.setFilter(new MyFilter());
        registration.addUrlPatterns("/*");
        registration.addInitParameter("paramName", "paramValue");
        registration.setName("MyFilter");
        registration.setOrder(1);
        return registration;
    }
    
    public class MyFilter implements Filter {
        @Override
        public void destroy() {
            // TODO Auto-generated method stub
        }

        @Override
        public void doFilter(ServletRequest srequest, ServletResponse sresponse, FilterChain filterChain)
                throws IOException, ServletException {
            // TODO Auto-generated method stub
            HttpServletRequest request = (HttpServletRequest) srequest;
            System.out.println("this is MyFilter,url :"+request.getRequestURI());
            filterChain.doFilter(srequest, sresponse);
        }

        @Override
        public void init(FilterConfig arg0) throws ServletException {
            // TODO Auto-generated method stub
        }
    }
}

自定义 Property

  1. 配置在 application.properties 中
  2. 自定义配置类
@Component
public class NeoProperties {
    @Value("${com.neo.title}")
    private String title;
    @Value("${com.neo.description}")
    private String description;

    //省略getter settet方法

    }

log配置

logging.path=/user/local/log
logging.level.com.favorites=DEBUG
logging.level.org.springframework.web=INFO
logging.level.org.hibernate=ERROR

path 为本机的 log 地址,logging.level 后面能够根据包路径配置不一样资源的 log 级别

数据库操做

添加 jar 包:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
 <dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>

添加配置文件:

spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

spring.jpa.properties.hibernate.hbm2ddl.auto=update
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
spring.jpa.show-sql= true

添加实体类和 Dao:

@Entity
public class User implements Serializable {

    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue
    private Long id;
    @Column(nullable = false, unique = true)
    private String userName;
    @Column(nullable = false)
    private String passWord;
    @Column(nullable = false, unique = true)
    private String email;
    @Column(nullable = true, unique = true)
    private String nickName;
    @Column(nullable = false)
    private String regTime;

    //省略getter settet方法、构造方法

}

dao 只要继承 JpaRepository 类就能够,几乎能够不用写方法,
能够根据方法名来自动的生成 SQL,好比findByUserName 会自动生成一个以 userName 为参数的查询方法,好比 findAlll 自动会查询表里面的全部数据,好比自动分页等等。

Entity 中不映射成列的字段得加 @Transient 注解,不加注解也会映射成列

public interface UserRepository extends JpaRepository<User, Long> {
    User findByUserName(String userName);
    User findByUserNameOrEmail(String username, String email);
}

测试:

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(Application.class)
public class UserRepositoryTests {

    @Autowired
    private UserRepository userRepository;

    @Test
    public void test() throws Exception {
        Date date = new Date();
        DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG);        
        String formattedDate = dateFormat.format(date);
        
        userRepository.save(new User("aa1", "aa@126.com", "aa", "aa123456",formattedDate));
        userRepository.save(new User("bb2", "bb@126.com", "bb", "bb123456",formattedDate));
        userRepository.save(new User("cc3", "cc@126.com", "cc", "cc123456",formattedDate));

        Assert.assertEquals(9, userRepository.findAll().size());
        Assert.assertEquals("bb", userRepository.findByUserNameOrEmail("bb", "cc@126.com").getNickName());
        userRepository.delete(userRepository.findByUserName("aa1"));
    }

}

Spring Data Jpa 还有不少功能,好比封装好的分页,能够本身定义 SQL,主从分离等等

Thymeleaf 模板

Thymeleaf 是一款用于渲染 XML/XHTML/HTML5 内容的模板引擎。相似 JSP,Velocity,FreeMaker 等,它也能够轻易的与 Spring MVC 等 Web 框架进行集成做为 Web 应用的模板引擎。与其它模板引擎相比,Thymeleaf 最大的特色是可以直接在浏览器中打开并正确显示模板页面,而不须要启动整个 Web 应用。

Thymeleaf 是不同凡响的,由于它使用了天然的模板技术。这意味着 Thymeleaf 的模板语法并不会破坏文档的结构,模板依旧是有效的XML文档。模板还能够用做工做原型,Thymeleaf 会在运行期替换掉静态值。Velocity 与 FreeMarke r则是连续的文本处理器。 下面的代码示例分别使用 Velocity、FreeMarker 与 Thymeleaf 打印出一条消息:

Velocity: <p>$message</p>
FreeMarker: <p>${message}</p>
Thymeleaf: <p th:text="${message}">Hello World!</p>

注意,因为 Thymeleaf 使用了 XML DOM 解析器,所以它并不适合于处理大规模的 XML 文件。

引入webjars:

页面即原型

在 Web 开发过程当中一个绕不开的话题就是前端工程师与后端工程师的协做,在传统 Java Web 开发过程当中,前端工程师和后端工程师同样,也须要安装一套完整的开发环境,而后各种 Java IDE 中修改模板、静态资源文件,启动/重启/从新加载应用服务器,刷新页面查看最终效果。

但实际上前端工程师的职责更多应该关注于页面自己而非后端,使用 JSP,Velocity 等传统的 Java 模板引擎很难作到这一点,由于它们必须在应用服务器中渲染完成后才能在浏览器中看到结果,而 Thymeleaf 从根本上颠覆了这一过程,经过属性进行模板渲染不会引入任何新的浏览器不能识别的标签,例如 JSP 中的 ,不会在 Tag 内部写表达式。整个页面直接做为 HTML 文件用浏览器打开,几乎就能够看到最终的效果,这大大解放了前端工程师的生产力,它们的最终交付物就是纯的 HTML/CSS/JavaScript 文件。

引入Thymeleaf

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
切换thymeleaf版本
<properties>
    <thymeleaf.version>3.0.9.RELEASE</thymeleaf.version>
    <!-- 布局功能的支持程序  thymeleaf3主程序  layout2以上版本 -->
    <!-- thymeleaf2   layout1-->
    <thymeleaf-layout-dialect.version>2.2.2</thymeleaf-layout-dialect.version>
  </properties>

Thymeleaf使用

@ConfigurationProperties(prefix = "spring.thymeleaf")
public class ThymeleafProperties {

    private static final Charset DEFAULT_ENCODING = Charset.forName("UTF-8");

    private static final MimeType DEFAULT_CONTENT_TYPE = MimeType.valueOf("text/html");

    public static final String DEFAULT_PREFIX = "classpath:/templates/";

    public static final String DEFAULT_SUFFIX = ".html";
    //

只要咱们把HTML页面放在classpath:/templates/,thymeleaf就能自动渲染;

  1. 导入thymeleaf的名称空间
<html lang="en" xmlns:th="http://www.thymeleaf.org">
  1. 使用thymeleaf语法;
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>成功!</h1>
    <!--th:text 将div里面的文本内容设置为 -->
    <div th:text="${hello}">这是显示欢迎信息</div>
</body>
</html>
相关文章
相关标签/搜索