文档章节

Spring Boot 2.1.5版本(一)

gwl_
 gwl_
发布于 05/29 10:50
字数 1325
阅读 821
收藏 0

Spring Boot 2.1.5版本(一)

Spring Boot 2.1.5版本(二)

入门

创建jar maven项目

pom.xml 文件添加

    <!--spring boot 父依赖 -->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.5.RELEASE</version>
    </parent>

    <dependencies>
        <!-- spring boot 配置web的依赖 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    </dependencies>

控制器

package com.gwl.web.controller;

import com.gwl.model.User;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("user")
public class UserController {

    @RequestMapping("{id}")
    //自动返回json格式数据
    @ResponseBody
    public User userInfo(@PathVariable Integer id) {

        User user = new User("zhangsan", "123456");
        user.setId(id);
        return user;
    }
}

创建一个App类,启动springboot

package com.gwl;

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

@EnableAutoConfiguration
//@ComponentScan(basePackages = {"com.gwl.web.controller","com.gwl.web.controller2"})
@ComponentScan(basePackages = "com.gwl.web.controller")
public class App 
{
    public static void main( String[] args )
    {
        // 启动springboot项目
        SpringApplication.run(App.class,args);
    }
}

访问 http://localhost:8080/user/3

查看项目实际的依赖

mvn dependency:tree

静态资源的访问

在main下创建resources文件夹,右键resources,选择Resources Root

在resources下创建static文件夹,static下创建images文件夹,在images文件夹内放入图片 hi.png,创建后的目录如下

访问 http://localhost:8080/images/hi.png 显示图片

捕获全局异常

创建捕获异常类

package com.gwl.web.exception;

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;

//控制器切面
@ControllerAdvice
public class GlobalExceptionHandler {

    //捕获运行时异常
    @ExceptionHandler(RuntimeException.class)
    @ResponseBody
    public Map<String, Object> exceptionHander() {
        Map<String, Object> map = new HashMap<>();
        map.put("msg", "错误");
        map.put("code", "303");
        return map;
    }
}

在 App 启动类中添加扫描

@ComponentScan(basePackages = "com.gwl.web")

控制器出现异常

Web页面

Spring Boot提供了默认配置的模板引擎主要有以下几种:

  • Thymeleaf
  • FreeMarker
  • Velocity
  • Groovy
  • Mustache

Spring Boot建议使用这些模板引擎,避免使用JSP,若一定要使用JSP将无法实现Spring Boot的多种特性,当你使用上述模板引擎中的任何一个,它们默认的模板配置路径为:src/main/resources/templates。也可以修改这个路径。

Freemarker的使用

在resources下创建templates文件夹

pom.xml 添加 freeMarker 的依赖包

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

控制器

package com.gwl.web.controller;

import com.gwl.model.Student;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("student")
public class StudentController {

    @RequestMapping("/list")
    public String list(Model model) {
        model.addAttribute("username", "zhangsan");
        model.addAttribute("age", 18);

        List<Student> list = new ArrayList();
        list.add(new Student(2, "lisi", "123"));
        list.add(new Student(5, "wangwu", "12356"));
        model.addAttribute("studentList", list);
        return "student/list";
    }
}

list.ftl

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8"/>
    <title></title>
</head>
<body>
欢迎
${username}
<#if age <= 17>小哥
<#elseif age <= 30>先生
<#else>大叔
</#if>登录
<table border="1">
    <tr>
        <td>id</td>
        <td>名字</td>
        <td>密码</td>
    </tr>
    <#list studentList?sort_by("id")?reverse as stu>
        <tr>
            <td> ${stu.id}</td>
            <td> ${stu.username}</td>
            <td> ${stu.password}</td>
        </tr>
    </#list>
</table>
</body>
</html>

访问 http://localhost:8080/student/list

jsp的使用

创建war maven工程

pom.xml 添加依赖包

  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.1.5.RELEASE</version>
  </parent>
  <dependencies>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-tomcat</artifactId>
    </dependency>
    <dependency>
      <groupId>org.apache.tomcat.embed</groupId>
      <artifactId>tomcat-embed-jasper</artifactId>
    </dependency>
  </dependencies>

在main下创建resources文件夹,右键resources,选择Resources Root

在 resources 下创建配置文件 application.properties 

spring.mvc.view.prefix=/WEB-INF/view/
spring.mvc.view.suffix=.jsp

server.servlet.context-path=/test
server.port=8888

在main下创建java文件夹,右键java,选择Sources Root

控制器

package com.gwl.web.controller;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.web.bind.annotation.RequestMapping;

@EnableAutoConfiguration
@RequestMapping("user")
public class UserController {

    @RequestMapping("list")
    public String list() {
        return "user/list";
    }

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

在 WEB-INF 下创建 view/user 文件夹,创建list.jsp文件

访问 http://localhost:8888/test/user/list

Spring Boot使用JDBC

pom.xml 添加依赖

        <!-- JDBC -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <!-- 数据库驱动 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
        </dependency>

在 resources 下创建配置文件 application.properties

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

Service

package com.gwl.service.impl;

import com.gwl.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public void add(String username, String password) {
        String sql = "insert into user(username,password) values (?,?)";
        jdbcTemplate.update(sql, username, password);
    }
}

controller

package com.gwl.web.controller;

import com.gwl.service.UserService;
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.ResponseBody;

@Controller
@RequestMapping("user")
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping("add")
    @ResponseBody
    public String add(String username, String password) {
        userService.add(username, password);
        return "success";
    }
}

在 App 启动类中添加扫描 service 包

@ComponentScan(basePackages = {"com.gwl.web","com.gwl.service"})

访问 http://localhost:8080/user/add?username=zhangsan&password=123456

Spring Boot使用Mybatis

pom.xml 添加依赖

        <!-- mybaties -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.0.1</version>
        </dependency>
        <!-- 数据库驱动 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
        </dependency>

在 resources 下创建配置文件 application.properties

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

UserMapper

package com.gwl.mapper;

import com.gwl.model.User;
import org.apache.ibatis.annotations.Param;

public interface UserMapper {

    public int save(@Param("username") String username, @Param("password") String password);

    public User getuser(@Param("username") String username);
}

UserMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.gwl.mapper.UserMapper">

    <insert id="save">
        insert into user (username,password) VALUES(#{username},#{password})
    </insert>

    <select id="getuser" resultType="com.gwl.model.User" parameterType="string">
        select * from user where username = #{username}
    </select>
</mapper>

pom.xml 添加 

    <build>
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
            </resource>
        </resources>
    </build>

注解方式 --- 不需要在 pom.xml 文件中添加配置和添加 UserMapper.xml

package com.gwl.mapper;

import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Param;

public interface UserMapper {

    @Insert("insert user(username,password) values (#{username},#{password})")
    public int save(@Param("username") String username, @Param("password") String password);

//    @Insert("insert user(username,password) values (#{arg0},#{arg1})")
//    public int save(String username, String password);
}

service

package com.gwl.service.impl;

import com.gwl.mapper.UserMapper;
import com.gwl.model.User;
import com.gwl.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public void add(String username, String password) {
        userMapper.save(username, password);
    }

    @Override
    public User get(String username) {
        return userMapper.getuser(username);
    }
}

 controller

package com.gwl.web.controller;

import com.gwl.service.UserService;
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.ResponseBody;

@Controller
@RequestMapping("user")
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping("add")
    @ResponseBody
    public String add(String username, String password) {
        userService.add(username, password);
        return "success";
    }

    @RequestMapping("get")
    @ResponseBody
    public User find(String username) {
        return userService.get(username);
    }
}

在 App 启动类中添加

@MapperScan(basePackages = "com.gwl.mapper")

访问 http://localhost:8080/user/add?username=zhangsan&password=1234567

访问 http://localhost:8080/user/get?username=lisi111

事务 @Transactional

@Transactional
public class UserServiceImpl implements UserService {

}

 

© 著作权归作者所有

gwl_
粉丝 1
博文 245
码字总数 127525
作品 0
其它
私信 提问
Spring Data Lovelace SR5 发布

Spring Data 团队宣布推出 Lovelace SR5 维护版本,此版本基于最新的 Spring Framework 5.1.5。此外,为了方便开发者,Spring Boot 2.1.3 也将提供对其的支持。 该版本的发布主要是修复 bug ...

局长
02/14
0
0
Spring Boot 2.1.5 正式发布,1.5.x 即将结束使命!

Spring Boot 官网在 2019/03/15 这天发布了 Spring Boot 2.1.5 正式版,栈长表示真跟不上了。。 官宣如下 : https://spring.io/blog/2019/05/15/spring-boot-2-1-5-released 仓库也已经跟上...

Java技术栈
05/17
0
0
关于Spring Boot你不得不知道的事

1 Spring Boot官网[2.1.5 CURRENT GA] 1.1 Pivotal Wiki Pivotal Software, Inc. is a software and services company based in San Francisco and Palo Alto, California, with several ot......

Java架构资源分享
06/15
0
0
SpringBoot整合Dubbo案例

使用框架: jdk 1.8 springboot-2.1.3 dubbo-2.6 spring-data-jpa-2.1.5 一、开发dubbo服务接口: 按照Dubbo官方开发建议,创建一个接口项目,该项目只定义接口和model类; 1、创建springboo...

ggod
06/09
0
0
SpringBlade 2.3.1 发布, 升级业务架构

简介: SpringBlade 是由一个商业级项目升级优化而来的 SpringCloud 微服务架构,采用 Java8 API 重构了业务代码,完全遵循阿里巴巴编码规范。采用 Spring Boot 2 、Spring Cloud Greenwich ...

smallchill
05/17
0
0

没有更多内容

加载失败,请刷新页面

加载更多

Hive(五)——Sqoop导入导出数据

一、

ittzg
32分钟前
3
0
抽象同步队列AQS——AbstractQueuedSynchronizer锁详解

AQS——锁的底层支持 谈到并发,不得不谈ReentrantLock;而谈到ReentrantLock,不得不谈AbstractQueuedSynchronizer(AQS)! 类如其名,抽象的队列式的同步器,AQS定义了一套多线程访问共享资...

须臾之余
今天
2
0
springboot配置百度UEditor 富文本详解

富文本简介 UEditor是由百度web前端研发部开发所见即所得富文本web编辑器,具有轻量,可定制,注重用户体验等特点,开源基于MIT协议,允许自由使用和修改代码... 准备工作 ueditor需要单独文...

wotrd
昨天
3
0
mysql 5.7之my.cnf配置大全

[client]port = 3306socket = /tmp/mysql.sock[mysqld]###############################基础设置######################################Mysql服务的唯一编号 每个mysql服务...

Online_Reus
昨天
2
0
MAVEN打包时引入外部链接的包

1.项目引入了ORACLE的jar包,MAVEN配置如下 2.打jar包的时候需要指定下main入口函数mainClass <dependency> <groupId>com.oracle</groupId> <artifactId>ojdbc6</artifactId> ......

Cobbage
昨天
2
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部