本篇博文主要包含:
一、springboot介绍
Spring Boot让我们的Spring应用变的更轻量化。
Spring Boot的主要优点:
1)为所有Spring开发者更快的入门
2)开箱即用,提供各种默认配置来简化项目配置
3)内嵌式容器简化Web项目
4)没有冗余代码生成和XML配置的要求
系统要求
Java1.8及以上
Spring Framework 4.1.5及以上
本文采用Java 1.8.0_73、Spring Boot 1.3.2调试通过。
二、快速入门
1.创建一个springboot项目
1.1 创建maven工程
1.2 引入maven依赖
org.springframework.boot
spring-boot-starter-parent
1.3.3.RELEASE
org.springframework.boot
spring-boot-starter-web
1.3 编写StuController服务
@RestController //表示修饰该Controller所有的方法返回JSON格式,直接可以编写Restful接口,相当于@ResponseBody + @Controller
public class StuController {
@RequestMapping("/index")
public Object index(){
return "success";
}
}
1.4 编写启动类
@EnableAutoConfiguration //作用在于让 Spring Boot根据应用所声明的依赖来对 Spring 框架进行自动配置
@ComponentScan(basePackages = "wmq.fly.controller") //控制器扫包范围
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
}
1.5 访问/index
在浏览器中输入:http://127.0.0.1:8080/index
三、Web开发
静态资源访问
Spring Boot默认提供js、css、图片等静态资源目录位置需置于classpath下,目录名需符合如下规则:
/static
/public
/resources
/META-INF/resources
举例:我们可以在src/main/resources/目录下创建static,在该位置放置一个图片文件。启动程序后,尝试访问http://localhost:8080/stt.png。如能显示图片,配置成功。
全局捕获异常
2.1 异常拦截GlobalExceptionHandler 类的实现
//@ControllerAdvice 是 controller 的一个辅助类,最常用的就是作为全局异常处理的切面类
@ControllerAdvice
public class GlobalExceptionHandler {
//拦截运行时异常,可以指定扫描范围
@ExceptionHandler(RuntimeException.class)
@ResponseBody @ResponseBody //返回json格式数据;不用@ResponseBody的话,返回 String,表示跳到某个 view
public Map exceptionHandler() {
Map map = new HashMap();
map.put("errorCode", "101");
map.put("errorMsg", "系統错误!");
return map;
}
}
2.2 抛出异常的类StuController
@RestController口,相当于@ResponseBody + @Controller
public class StuController {
@RequestMapping("/index")
public Object index(){
int i = 1/0;
return "success";
}
}
2.3 访问/index
在浏览器中输入:http://127.0.0.1:8080/index
3. 使用Freemarker模板引擎渲染web视图
FreeMarker是一款模板引擎,即一种基于模板和要改变的数据,并用来生成输出文本(HTML网页,电子邮件,配置文件,源代码等)的通用工具。它不是面向最终用户的,而是一个Java类库,是一款程序员可以嵌入他们所开发产品的组件。
3.1 pom文件引入
org.springframework.boot
spring-boot-starter-freemarker
3.2 模板index.ftl代码
${name}
<#if sex==1>
男
<#elseif sex==2>
女
<#else>
其他
#if>
<#list userlist as user>
${user}
#list>
3.3 后台代码
@Controller
public class FreemarkController {
@RequestMapping("/freeTest")
public String freemarkTest(Map result){
result.put("name","good");
result.put("sex",1);
List list = new ArrayList<>();
list.add("aly");
list.add("lucy");
result.put("userlist",list);
return "index";
}
}
3.5 访问
在浏览器中输入:http://127.0.0.1:8080/freeTest
3.6 Freemarker配置
application.properties文件中加入一下配置
########################################################
###FREEMARKER (FreeMarkerAutoConfiguration)
########################################################
spring.freemarker.allow-request-override=false
spring.freemarker.cache=true
spring.freemarker.check-template-location=true
spring.freemarker.charset=UTF-8
spring.freemarker.content-type=text/html
spring.freemarker.expose-request-attributes=false
spring.freemarker.expose-session-attributes=false
spring.freemarker.expose-spring-macro-helpers=false
#spring.freemarker.prefix=
#spring.freemarker.request-context-attribute=
#spring.freemarker.settings.*=
spring.freemarker.suffix=.ftl
spring.freemarker.template-loader-path=classpath:/templates/
#comma-separated list
#spring.freemarker.view-names= # whitelist of view names that can be resolved
org.springframework.boot
spring-boot-starter-parent
1.3.3.RELEASE
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-starter-tomcat
org.apache.tomcat.embed
tomcat-embed-jasper
4.3 在application.yml创建以下配置
###配置jsp文件路径
spring:
mvc:
view:
prefix: /WEB-INF/jsp/
suffix: .jsp
server:
port: 9999
4.4 index.jsp页面代码
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
Insert title here
hello world
4.5 后端代码
@Controller
public class IndexController {
@RequestMapping("/index")
public String indexTest() {
return "index";
}
}
org.springframework.boot
spring-boot-starter-parent
1.5.2.RELEASE
org.springframework.boot
spring-boot-starter-jdbc
mysql
mysql-connector-java
5.1.21
org.springframework.boot
spring-boot-starter-test
test
org.springframework.boot
spring-boot-starter-web
1.2 在application.yml文件中添加配置
####数据库链接
spring:
datasource:
url: jdbc:mysql://localhost:3308/school
username: root
password: 123456
driver-class-name: com.mysql.jdbc.Driver
server:
port: 9999
1.3 service层代码
@Service
public class UserServiceImpl {
@Autowired
private JdbcTemplate jdbcTemplate;
public void createUser(String name, Integer age) {
System.out.println("ssss");
jdbcTemplate.update("insert into users values(null,?,?);", name, age);
}
}
1.4 controller层代码
@RestController
public class UserController {
@Autowired
private UserServiceImpl userServiceImpl;
@RequestMapping("/createUser")
public void createUser(String name, Integer age) {
userServiceImpl.createUser(name, age);
}
}
1.5 启动类
@SpringBootApplication //组合了@EnableAutoConfiguration+@Configurable+@ComponentScan,只能在当前同级包下扫包
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
}
org.springframework.boot
spring-boot-starter-parent
1.5.2.RELEASE
org.springframework.boot
spring-boot-starter-jdbc
mysql
mysql-connector-java
5.1.21
org.springframework.boot
spring-boot-starter-test
test
org.springframework.boot
spring-boot-starter-web
org.mybatis.spring.boot
mybatis-spring-boot-starter
1.1.1
2.2 在application.yml文件中添加配置
####数据库链接
spring:
datasource:
url: jdbc:mysql://localhost:3308/school
username: root
password: 123456
driver-class-name: com.mysql.jdbc.Driver
server:
port: 9999
2.3 User类
public class User {
private String name;
private Integer age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
2.4 UserMapper
public interface UserMapper {
@Select("SELECT * FROM USERS WHERE NAME = #{name}")
User findByName(@Param("name") String name);
@Insert("INSERT INTO USERS(NAME, AGE) VALUES(#{name}, #{age})")
int insert(@Param("name") String name, @Param("age") Integer age);
}
2.5 controller层
@RestController
public class MUserController {
@Autowired
private UserMapper userMapper;
@RequestMapping("/getUser")
public User getUser(String name) {
return userMapper.findByName(name);
}
}
2.6 启动类
启动类上添加@MapperScan(basePackages = {“wmq.fly.mybatis”})注解将*Mapper.java注入容器
@MapperScan(basePackages = {"wmq.fly.mybatis"})//将*Mapper.java注入spring容器
@SpringBootApplication //组合了@EnableAutoConfiguration+@Configurable+@ComponentScan,只能在当前同级包下扫包
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
}
org.springframework.boot
spring-boot-starter-parent
1.4.2.RELEASE
org.springframework.boot
spring-boot-starter-data-jpa
mysql
mysql-connector-java
5.1.21
org.springframework.boot
spring-boot-starter-web
3.2 在application.yml文件中添加配置
####数据库链接
spring:
datasource:
url: jdbc:mysql://localhost:3308/school
username: root
password: 123456
driver-class-name: com.mysql.jdbc.Driver
server:
port: 9999
3.3 创建User实体类
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
@Entity(name = "users")
public class User {
@Id
@GeneratedValue
private Integer id;
@Column
private String name;
@Column
private Integer age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
3.4 创建UserDao
import org.springframework.data.jpa.repository.JpaRepository;
public interface UserDao extends JpaRepository {
}
3.5 创建controller层
@RestController
public class IndexController {
@Autowired
private UserDao userDao;
@RequestMapping("/getOneUser")
public String getOneUser(Integer id) {
User findUser = userDao.findOne(id);
System.out.println(findUser.getName());
return findUser.getName();
}
}
3.6 启动类
@EnableJpaRepositories(basePackages = "wmq.fly.jpa") //将Dao层的UserDao注入容器
@EntityScan(basePackages = "wmq.fly.jpa") //将实体类User注入容器
@SpringBootApplication //组合了@EnableAutoConfiguration+@Configurable+@ComponentScan,只能在当前同级包下扫包
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
}