StringBoot 易上手的java框架

StringBoot是一个几乎不需要配置的Java框架,能够帮助开发者专注于业务逻辑,而不需要关心框架的复杂配置.

1.新建一个SpringBoot项目.

  • 打开IDEA,new->project->Spring Intializr(每一步确认JDK版本是否一致)->Web->Spring Web Starter
  • 项目创建完成,是一个maven项目,在src/main/java(...)/有一个SpringbootApplication,直接运行该程序,就开启了项目内置的tomcat了.
  • 在SpringbootApplication所在目录下新建一个web目录,在其中新建一个控制类.
package com.how2java.springboot.web;
 
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
 
@RestController
public class HelloController {
 
    @RequestMapping("/hello")
    public String hello() {
        return "Hello Spring Boot!";
    }
 
}

重写运行,访问/hello就会看到输出的文字了.

2.热部署

  • CTRL + SHIFT + A --> 查找make project automatically --> 选中
  • CTRL + SHIFT + A --> 查找Registry --> 找到并勾选compiler.automake.allow.when.app.running
  • pom.xml下添加依赖
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-devtools</artifactId>
    <optional>true</optional> <!-- 这个需要为 true 热部署才有效 -->
</dependency>
  • application.propertiles下增加
spring.thymeleaf.cache=true
spring.devtools.restart.enabled=true
spring.devtools.restart.additional-paths=src/main/java

之后修改控制类中内容后并ctrl+s保存后,程序会自动重启(需要等待一定时间,约5-6s)

3.配置切换.

在核心配置文件application.propertiles所在目录下新建两个配置文件
application-dev.properties
application-pro.properties
分别代表开发配置和生产配置.通过修改application.propertiles下spring.profiles.active属性=pro或者dev来切换配置.
核心配置文件中的配置在两套配置中都是通用的.
对最终生成的jar文件也可以通过java -jar target/springboot-0.0.1-SNAPSHOT.jar --spring.profiles.active=pro命令使用对应配置

4.JPA

Sun制定了java持久化规范,Hibernate执行了该规范.Springboot内部集成了Hibernate,让用户简单的调用.

  • application.properties中增加声明:
spring.mvc.view.prefix=/WEB-INF/jsp/
spring.mvc.view.suffix=.jsp
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/how2java?characterEncoding=UTF-8
spring.datasource.username=root
spring.datasource.password=admin
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.properties.hibernate.hbm2ddl.auto=update
  • pom.xml添加依赖
 <!-- mysql-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.21</version>
        </dependency>
 
        <!-- jpa-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency> 
  • pojo目录下添加实体类
package com.example.springboot.pojo;

import javax.persistence.*;

@Entity
@Table(name = "category_")
public class Category {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private int id;

    @Column(name = "name")
    private String name;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }

}
  • dao目录下添加接口
package com.example.springboot.dao;

import com.example.springboot.pojo.Category;
import org.springframework.data.jpa.repository.JpaRepository;


public interface CategoryDAO extends JpaRepository<Category,Integer> {
}

  • web目录下添加控制器
package com.example.springboot.web;

import com.example.springboot.dao.CategoryDAO;
import com.example.springboot.pojo.Category;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;


@Controller
public class CategoryController {
    @Autowired
    CategoryDAO categoryDAO;

    @RequestMapping("/listCategory")
    public String listCategory(Model m) throws Exception {
        List<Category> cs=categoryDAO.findAll();

        m.addAttribute("cs", cs);

        return "listCategory";
    }

}
  • 添加jsp显示
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
 
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
   
<table align='center' border='1' cellspacing='0'>
    <tr>
        <td>id</td>
        <td>name</td>
    </tr>
    <c:forEach items="${cs}" var="c" varStatus="st">
        <tr>
            <td>${c.id}</td>
            <td>${c.name}</td>
                
        </tr>
    </c:forEach>
</table>

5. JPA分页,增删改用法

  • 为控制器添加映射,redirect表示客户端跳转,RequestMapping表示访问url
@RequestMapping("/addCategory")
public String addCategory(Category c) throws Exception {
	categoryDAO.save(c);
	return "redirect:listCategory";
}
@RequestMapping("/deleteCategory")
public String deleteCategory(Category c) throws Exception {
	categoryDAO.delete(c);
	return "redirect:listCategory";
}
@RequestMapping("/updateCategory")
public String updateCategory(Category c) throws Exception {
	categoryDAO.save(c);
	return "redirect:listCategory";
}
@RequestMapping("/editCategory")
public String editCategory(int id,Model m) throws Exception {
	Category c= categoryDAO.getOne(id);
	m.addAttribute("c", c);
	return "editCategory";
}

  @RequestMapping("/listCategory")
    public String listCategory(Model m, @RequestParam(value="start",defaultValue = "0")int start,@RequestParam(value="size",defaultValue="5")int size) throws Exception {
        start=start<0?0:start;
        Sort sort = new Sort(Sort.Direction.DESC,"id");
        //2.0版本提示过时
        //Pageable pageable = new PageRequest(start,size,sort);
        Pageable pageable = PageRequest.of(start,size,sort);
        Page<Category> page = categoryDAO.findAll(pageable);
        m.addAttribute("page", page);
        return "listCategory";
    }

    @RequestMapping("/editCategory")
    public String editCategory(int id,Model m) throws Exception{
        Category c = categoryDAO.getOne(id);
        m.addAttribute("c",c);
        return "editCategory";
    }

  • jsp页面
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
 
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
   
<div align="center">
 
</div>
 
<div style="width:500px;margin:20px auto;text-align: center">
    <table align='center' border='1' cellspacing='0'>
        <tr>
            <td>id</td>
            <td>name</td>
            <td>编辑</td>
            <td>删除</td>
        </tr>
        <c:forEach items="${page.content}" var="c" varStatus="st">
            <tr>
                <td>${c.id}</td>
                <td>${c.name}</td>
                <td><a href="editCategory?id=${c.id}">编辑</a></td>
                <td><a href="deleteCategory?id=${c.id}">删除</a></td>
            </tr>
        </c:forEach>
         
    </table>
    <br>
    <div>
                <a href="?start=0">[首  页]</a>
            <a href="?start=${page.number-1}">[上一页]</a>
            <a href="?start=${page.number+1}">[下一页]</a>
            <a href="?start=${page.totalPages-1}">[末  页]</a>
    </div>
    <br>
    <form action="addCategory" method="post">
     
    name: <input name="name"> <br>
    <button type="submit">提交</button>
     
    </form>
</div>





<%@ page language="java" contentType="text/html; charset=UTF-8"
 pageEncoding="UTF-8" isELIgnored="false"%>
 
<div style="margin:0px auto; width:500px">
 
<form action="updateCategory" method="post">
 
name: <input name="name" value="${c.name}"> <br>
 
<input name="id" type="hidden" value="${c.id}">
<button type="submit">提交</button>
 
</form>
</div>

6.测试

SpringBoot的测试相当便捷.

  • 首先在pom.xml中添加对Springboot测试和junit的依赖
 <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
  <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
        </dependency>
  • 之后新建一个测试类运行即可
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
public class TestJPA {
 
    @Autowired CategoryDAO dao;
     
    @Test
    public void test() {
        List<Category> cs=  dao.findAll();
        for (Category c : cs) {
            System.out.println("c.getName():"+ c.getName());
        }
         
    }
}

7.JPA条件查询

无需写一条sql语句.JPA规范帮你实现查询,NB!
在DAO接口中添加接口方法.JPA根据方法名通过反射创造相应的SQL语句.

例代码:

public interface CategoryDAO extends JpaRepository<Category,Integer>{
 
    public List<Category> findByName(String name);
     
    public List<Category> findByNameLikeAndIdGreaterThanOrderByNameAsc(String name, int id);
}

调用

 List<Category> cs = dao.findByNameLikeAndIdGreaterThanOrderByNameAsc("%是%",16);
        for(Category c : cs){
            System.out.println(c);
        }

8.Restful风格

Restful风格利用不同的method值来区分CRUD.简化url.

@GetMapping("/categories")
    public String listCategory(@NotNull Model m, @RequestParam(value = "start", defaultValue = "0") int start, @RequestParam(value = "size", defaultValue = "5") int size) throws Exception {
        start = start<0?0:start;
        Sort sort = new Sort(Sort.Direction.DESC, "id");
        Pageable pageable = new PageRequest(start, size, sort);
        Page<Category> page =categoryDAO.findAll(pageable);
        m.addAttribute("page", page);
        return "listCategory";
    }

    @PostMapping("/categories")
    public String addCategory(Category c) throws Exception {
        categoryDAO.save(c);
        return "redirect:/categories";
    }
    @DeleteMapping("/categories/{id}")
    public String deleteCategory(Category c) throws Exception {
        categoryDAO.delete(c);
        return "redirect:/categories";
    }
    @PutMapping("/categories/{id}")
    public String updateCategory(Category c) throws Exception {
        categoryDAO.save(c);
        return "redirect:/categories";
    }
    @GetMapping("/categories/{id}")
    public String getCategory(@PathVariable("id") int id, @NotNull Model m) throws Exception {
        Category c= categoryDAO.getOne(id);
        m.addAttribute("c", c);
        return "editCategory";
    }

9.JSON格式

控制器传递JSON格式数据,需要用直接文本输出注解@RestController.或者@Controller和@ResponseBody,这样就可以直接返回文本传递给前端了.

@GetMapping("category")
    public List<Category> listCategory(@RequestParam(value = "start",defaultValue = "0")int start,@RequestParam(value = "size",defaultValue = "5")int size)throws Exception{
        start=start<0?0:start;
        Sort sort = new Sort(Sort.Direction.DESC,"id");
        Pageable pageable = new PageRequest(start,size,sort);
        Page<Category> page = categoryDAO.findAll(pageable);
        System.out.println(page);
        return page.getContent();
    }

    @GetMapping("/category/{id}")
    public Category getCategory(@PathVariable("id")int id)throws Exception{
        Category c = categoryDAO.getOne(id);
        System.out.println(c);
        return c;
    }

    @PutMapping("/category")
    public void addCategoryJson(@RequestBody Category category)throws Exception{
        System.out.println("Spring Boot接受浏览器以JSON格式提交的数据: "+category);
    }

参考资料:
how2j

posted on 2019-08-15 22:06  Best_Efforts  阅读(712)  评论(0编辑  收藏  举报

导航