Spring Boot 2.1.5版本(一)

Spring Boot 2.1.5版本(一)

Spring Boot 2.1.5版本(二)

入门

创建jar maven项目

ee8fd035d5b0cb4961a32545855bc38a12f.jpg

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

d9cb1abe1688fd6aac63a4c74580f384143.jpg

查看项目实际的依赖

mvn dependency:tree

c377f33f5bd7a501cc25b96d5c7b7088f41.jpg

静态资源的访问

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

0fa854c7adcd61fbfbb530fb947c27c6808.jpg

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

3cf8c7494148e48ecd9c979e817502a53c3.jpg

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

4f43b6769891446dd84871d39f8e1768d73.jpg

捕获全局异常

创建捕获异常类

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")

控制器出现异常

81c7e17ff9fd84b4cfa058a4a6b1dac57b3.jpg

Web页面

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

  • Thymeleaf
  • FreeMarker
  • Velocity
  • Groovy
  • Mustache

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

Freemarker的使用

在resources下创建templates文件夹

9f183c706236d61c59187ef0c6ab2c914b4.jpg

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

0008f2c7f7909d0da179c9807b630a694ca.jpg

jsp的使用

创建war maven工程

f73354dcfb4e9d1d49aa2465cce50444dc5.jpg

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

0fa854c7adcd61fbfbb530fb947c27c6808.jpg

在 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

057f93c6e3b55d2e306525b8b0e7bcda881.jpg

控制器

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文件

ab3a60796b84cbba7d4a83d68712973817c.jpg

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

0286265daf3e269ba4e1ef62b46042b980a.jpg

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

a2a38d1db3ae5c7dfe607cfe6f5442c8b70.jpg

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

5b00a320f8b8f9478f5e4580dd33ac14d76.jpg

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

9457896c99a4bf2b4f35b834924c5c4ffac.jpg

事务 @Transactional

@Transactional
public class UserServiceImpl implements UserService {

}

 

转载于:https://my.oschina.net/gwlCode/blog/3055412

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值