SpringBoot Web开发体验

栏目: Java · 发布时间: 6年前

内容简介:SpringBoot Web开发体验

1 前言

本文记录SpringBoot搭建Web平台的开发经验,以备后续更近一步实践。

先来看看搭建的页面效果,如下图:

SpringBoot Web开发体验

打开safari的开发者 工具 框,如下图,可以再控制台中看到浏览器执行日志-点击获取名字时就会打出日志。

SpringBoot Web开发体验

附图为MVC框图,对于开发者理解构架有益。

SpringBoot Web开发体验

2 步骤

接下来,介绍搭建步骤,总共分为3步:

  • 创建maven工程
  • 配置springboot项目
  • spring web配置

2.1 创建maven工程

通过Idea中的“Create New Project”功能创建工程。

SpringBoot Web开发体验

选择maven项目。

SpringBoot Web开发体验

填写Groupid、Artifactid、Version内容。至此,Maven工程新建完毕。

SpringBoot Web开发体验

2.2 配置springboot项目

pom.xml文件配置,使用到了spring-boot-starter-parent、spring-boot-starter-web两依赖。

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.amap.openapi</groupId>
    <artifactId>openapi-web</artifactId>
    <version>1.0-SNAPSHOT</version>

    <!-- Inherit defaults from Spring Boot -->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.3.RELEASE</version>
    </parent>

    <!-- Add typical dependencies for a web application -->
    <dependencies>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    </dependencies>
</project>

创建application.properties文件:

################################################################################
# embedded servlet container
server.port=7000
# sessionTimeout in seconds
server.sessionTimeout=30000
# tomcat compression
server.tomcat.compression=on

创建applicationContext.xml文件:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="properties" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations">
            <list>
                <value>classpath:spring/config/application.properties</value>
            </list>
        </property>
        <property name="ignoreUnresolvablePlaceholders" value="true" />
    </bean>
</beans>

文件初始化配置:

@SpringBootApplication
@EnableAutoConfiguration
public class App {

    @Value("${server.port}")
    private int port;
    @Value("${server.sessionTimeout}")
    private int sessionTimeout;

    public static void main(String[] args) throws Exception {
        SpringApplication.run(App.class, args);
    }

    @Bean
    public EmbeddedServletContainerFactory servletContainer() {
        TomcatEmbeddedServletContainerFactory factory = new TomcatEmbeddedServletContainerFactory();
        factory.setPort(port);
        factory.setSessionTimeout(sessionTimeout, TimeUnit.SECONDS);
        return factory;
    }

    @Bean
    public MultipartConfigElement multipartConfigElement() {
        // 配置最大上传文件大小为100M
        MultipartConfigFactory factory = new MultipartConfigFactory();
        factory.setMaxFileSize("102400KB");
        factory.setMaxRequestSize("102400KB");
        return factory.createMultipartConfig();
    }
}

@Configuration
@ImportResource("/spring/*.xml")
class XmlImportingConfiguration {
}

2.3 spring web配置

本例中使用thymeleaf作为web模版引擎,因此首先需要在pom中加入依赖及插件,更新后的依赖如下:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.amap.openapi</groupId>
    <artifactId>openapi-web</artifactId>
    <version>1.0-SNAPSHOT</version>

    <!-- Inherit defaults from Spring Boot -->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.3.RELEASE</version>
    </parent>

    <!-- Add typical dependencies for a web application -->
    <dependencies>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

在application.properties文件添加thymeleaf的相关配置(模版默认路径、后缀、模式、编码、缓存),更新后的配置文件如下:

################################################################################
# embedded servlet container
server.port=7000
# sessionTimeout in seconds
server.sessionTimeout=30000
# tomcat compression
server.tomcat.compression=on

################################################################################
# THYMELEAF (ThymeleafAutoConfiguration)
spring.thymeleaf.check-template-location=true
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
spring.thymeleaf.mode=HTML5
spring.thymeleaf.encoding=UTF-8
# charset=<encoding> is added
spring.thymeleaf.content-type=text/html
# set to false for hot refresh
spring.thymeleaf.cache=true

创建Controller控制器,对应的视图模型为index。其中@RequestMapping(value = “/user”)属性值”/user”表示访问路径,如 http://localhost:7000/user ,函数index返回类型为String,其返回值为”index”,这里需要区分的是不是返回”index”字符串。工程默认模版路径为”resources/templates”。

@Controller
public class SampleController {

    @RequestMapping(value = "/user")
    public String index(ModelMap model){

        User user = new User("loongshawn","12345678");
        List<User> list = new ArrayList<User>();
        User user1 = new User("user1","12345678");
        User user2 = new User("user2","12345678");
        User user3 = new User("user3","12345678");
        list.add(user1);
        list.add(user2);
        list.add(user3);

        model.addAttribute("user",user);
        model.addAttribute("list",list);
        System.out.println("index");

        return "index";
    }
}

既然视图模型为index,创建index.html,将其存放在templates路径下。

SpringBoot Web开发体验

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8" />
    <title>首页</title>
    <link th:href="@{bootstrap/css/bootstrap.min.css}" rel="stylesheet" />
    <link th:href="@{bootstrap/css/bootstrap-theme.min.css}" rel="stylesheet" />
</head>
<body>
<div class="panel panel-primary">
    <div class="panel-heading">
        <h3 class="panel-title">访问Model</h3>
    </div>
    <div class="panel-body">
        <span th:text="${user.name}"></span>
    </div>
</div>
<div th:if="${not #lists.isEmpty(list)}">
    <div class="panel panel-primary">
        <div class="panel-heading">
            <h3 class="panel-title">列表</h3>
        </div>
        <div class="panel-body">
            <ul class="list-group">
                <li class="list-group-item" th:each="person:${list}">
                    <span th:text="${person.name}"></span>
                    <span th:text="${person.password}"></span>
                    <button class="btn" th:onclick="'getName(\''+${person.name}+'\');'">获得名字</button>
                </li>
            </ul>
        </div>
    </div>
</div>
<script th:src="@{jquery-3.2.1.js}" type="text/javascript"></script>
<script th:src="@{bootstrap/js/bootstrap.min.js}" type="text/javascript"></script>
<script th:inline="javascript">
    var single = [[${user}]];
    console.log(single.name+"/"+single.password);
    function getName(name) {
        console.log(name);
    }
</script>
</body>
</html>

出于显示效果考虑,用到了bootstrap及jquery两个库,在resources路径下创建static文件夹,将bootstrap、jquery库存放在此,官方均提供最新版本库下载地址。至此,所用配置工作完成。

SpringBoot Web开发体验

3 总结

本文仅仅记录了利用SpringBoot如何搭建一个Web平台,配置比较简易。但没有涉及数据库操作,因此你也可以在此基础上自行配置MyBatis,可以参考之前的文章 《SpringBoot、MyBatis配置多数据源》 。上述配置过程如有问题,请吐槽。

4 附件

工程源码地址


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

JavaScript语言精粹

JavaScript语言精粹

Douglas Crockford / 赵泽欣、鄢学鹍 / 电子工业出版社 / 2009-4 / 35.00元

本书通过对JavaScript语言的分析,甄别出好的和坏的特性,从而提取出相对这门语言的整体而言具有更好的可靠性、可读性和可维护性的JavaScript的子集,以便你能用它创建真正可扩展的和高效的代码。 雅虎资深JavaScript架构师Douglas Crockford倾力之作。 向读者介绍如何运用JavaScript创建真正可扩展的和高效的代码。一起来看看 《JavaScript语言精粹》 这本书的介绍吧!

JS 压缩/解压工具
JS 压缩/解压工具

在线压缩/解压 JS 代码

JSON 在线解析
JSON 在线解析

在线 JSON 格式化工具

MD5 加密
MD5 加密

MD5 加密工具