spring boot 入门-使用spring boot构建简单应用

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/PacosonSWJTU/article/details/54313776

目的:建立一个简单的联系人列表; 使用 spring boot + maven 进行构建


【0】文件结构如下:


【1】pom.xml 如下:

<?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.habuma</groupId>
	<artifactId>contacts</artifactId>
	<version>0.1.0</version>
	<packaging>jar</packaging>
	<!-- spring boot 的 web starter 能够将 spring mvc 需要的所有内容全部添加到构建中-->
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>1.1.4.RELEASE</version>
	</parent>
	
	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<dependency>
			<groupId>org.thymeleaf</groupId>
			<artifactId>thymeleaf-spring4</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-jdbc</artifactId>
		</dependency>
		<dependency>
			<groupId>com.h2database</groupId>
			<artifactId>h2</artifactId>
		</dependency>
		<dependency>
			<groupId> org.springframework.boot</groupId>
			<artifactId>spring-boot-actuator</artifactId>
		</dependency>
	</dependencies>
	
	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>
</project>


【2】请求控制器 ContactController.java

package contacts;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
@RequestMapping("/")
public class ContactController {
    private ContactRepository contactRepo;
   
    @Autowired
    public ContactController(ContactRepository contactRepo) {
        this.contactRepo = contactRepo;
    }
    @RequestMapping(method=RequestMethod.GET)
    public String home(Map<String,Object> model) {
        List<Contact> contacts = contactRepo.findAll();
        model.put("contacts", contacts);
        return "home";
    }
    @RequestMapping(method=RequestMethod.POST)
    public String submit(Contact contact) {
        contactRepo.save(contact);
        return "redirect:/";
    }
}

【3】java bean, Contact.java

public class Contact {
    private Long id;
    private String firstName;
    private String lastName;
    private String phoneNumber;
    private String emailAddress;
    // setter + getter 方法
}


【4】创建视图

【4.1】 在maven中建立以来 thymeleaf 模板

<dependency>
			<groupId>org.thymeleaf</groupId>
			<artifactId>thymeleaf-spring4</artifactId>
		</dependency>
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Spring Boot Contacts</title>
<link rel="stylesheet" th:href="@{/style.css}" />
</head>
<body>
	<h2>Spring Boot Contacts</h2>
	<form method="POST">
		<label for="firstName"> First Name:</label> <input type="text" name="firstName"></input><br /> 
		<label for="lastName"> Last Name:</label> <input type="text" name="lastName"></input><br /> 
		<label for="phoneNumber"> Phone #:</label> <input type="text" name="phoneNumber"></input><br /> 
		<label for="emailAddress"> Email:</label><input type="text" name="emailAddress"></input><br /> 
		<input type="submit"></input>
	</form>
	
	<ul th:each="contact : ${contacts}">
		<li>
			<span th:text="${contact.firstName}">First
			</span><span th:text="${contact.lastName}">Last</span> : 
			<span th:text="${contact.phoneNumber}">phoneNumber</span>,
			<span th:text="${contact.emailAddress}">emailAddress</span>
		</li>
	</ul>
</body>
</html>


style.css

body {
	background-color: #eeeeee;
	font-family: sans-serif;
}
label {
	display: inline-block;
	width: 120px;
	text-align: right;
}


【5】持久化数据

【5,.1】 建立maven依赖 jdbc 和 h2 内嵌数据库

<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-jdbc</artifactId>
		</dependency>
		<dependency>
			<groupId>com.h2database</groupId>
			<artifactId>h2</artifactId>
		</dependency>
【5.2】 基于spring 建立 dao

package contacts;
import java.util.List;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

@Repository
public class ContactRepository {
    private JdbcTemplate jdbc;
    
    @Autowired
    public ContactRepository(JdbcTemplate jdbc) {
        this.jdbc = jdbc;
    }
    public List<Contact> findAll() {
        return jdbc.query(
            "select id, firstName, lastName, phoneNumber, emailAddress " +
            "from contacts order by lastName",
            new RowMapper<Contact>() {
                public Contact mapRow(ResultSet rs, int rowNum)
                throws SQLException {
                    Contact contact = new Contact();
                    contact.setId(rs.getLong(1));
                    contact.setFirstName(rs.getString(2));
                    contact.setLastName(rs.getString(3));
                    contact.setPhoneNumber(rs.getString(4));
                    contact.setEmailAddress(rs.getString(5));
                    return contact;
                }
            });
    }
    public void save(Contact contact) {
        jdbc.update(
            "insert into contacts " +
            "(firstName, lastName, phoneNumber, emailAddress) " +
            "values (?, ?, ?, ?)",
            contact.getFirstName(), contact.getLastName(),
            contact.getPhoneNumber(), contact.getEmailAddress());
    }
}


【6】建立启动类

package contacts;

import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.SpringApplication;
import org.springframework.context.annotation.ComponentScan;

@ComponentScan
@EnableAutoConfiguration
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

【7】构建项目 mvn pacakge


补充: schema.sql SQL文件:

create table contacts (
	id identity,
	firstName varchar(30) not null,
	lastName varchar(50) not null,
	phoneNumber varchar(13),
	emailAddress varchar(30)
);













展开阅读全文

没有更多推荐了,返回首页