SpringBoot整合Angularjs

一、https://code.angularjs.org/  下载  Angularjs

二、添加依赖

 

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.12.0</version>
</dependency>

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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.4.4</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>demo</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>11</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
            <version>2.4.4</version>
        </dependency>
        <dependency>
            <groupId>net.sourceforge.nekohtml</groupId>
            <artifactId>nekohtml</artifactId>
            <version>1.9.22</version>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit-dep</artifactId>
            <version>4.10</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.4</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.23</version>
        </dependency>
        <!-- alibaba数据库连接池 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.2.5</version>
        </dependency>
        <!-- 分页插件 -->
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper-spring-boot-starter</artifactId>
            <version>1.3.0</version>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.12.0</version>
        </dependency>


    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

 

 

三、将下载的js文件导入项目

 

我下载的是1.8.2版本,在resources下创建目录public,将下载的1.8.2的包解压导入public即可。

四、配置文件

application.properties

#是否开启缓存,开发时可设置为false,默认为true
spring.thymeleaf.cache=false
#检查模板是否存在,默认为true
spring.thymeleaf.check-template=true
#检查模板位置是否存在,默认为true
spring.thymeleaf.check-template-location=true
#模板文件编码,UTF-8
spring.thymeleaf.encoding=UTF-8
#模板文件位置
spring.thymeleaf.prefix=classpath:/templates
#Content-Type配置
spring.thymeleaf.servlet.content-type=text/html
#模板文件后缀
spring.thymeleaf.suffix=.html
#启用MVC Thymeleaf视图分辨率
spring.thymeleaf.enabled=true
#模板编码
spring.thymeleaf.mode=LEGACYHTML5
#链中模板解析器的顺序
#spring.thymeleaf.template-resolver-order=o
#应该中解决方案中排除的视图名称的逗号分隔列表
#spring.thymeleaf.excluded-view-names=

#root日志以 WARN 级别输出 (日志只输出 WARN 及以上级别的信息)
#logging.level.root=WARN
#springframework.web 日志只以 DEBUG 级别输出
#logging.level.org.springframework.web=DEBUG
#hibernate 日志以 ERROR 级别输出
#logging.level.org.hibernate=ERROR
logging.file.name=e:\\log\\info.log
logging.pattern.console=%d{yyyy/MM/dd-HH:mm:ss} [%thread] %-5level %logger- %msg%n
logging.pattern.file=%d{yyyy/MM/dd-HH:mm:ss} [%thread] %-5level %logger- %msg%n

#数据源配置
spring.datasource.name=test
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
#加上?useUnicode=true&characterEncoding=UTF-8,否则可能插入数据库中文乱码
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/vhr?useUnicode=true&characterEncoding=UTF-8
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
#spring.datasource.sql-script-encoding=UTF-8
#spring.datasource.druid.filter.encoding.enabled=true
spring.datasource.druid.filters=stat
spring.datasource.druid.max-active=20
spring.datasource.druid.initial-size=1
spring.datasource.druid.max-wait=60000
spring.datasource.druid.min-idle=1
spring.datasource.druid.time-between-eviction-runs-millis=60000
spring.datasource.druid.min-evictable-idle-time-millis=300000
spring.datasource.druid.validation-query=select 'x'
spring.datasource.druid.test-while-idle=true
spring.datasource.druid.test-on-borrow=false
spring.datasource.druid.test-on-return=false
spring.datasource.druid.pool-prepared-statements=true
spring.datasource.druid.max-open-prepared-statements=20

#所有的mapper映射文件
#mybatis.mapper-locations=classpath*:com/springboot/mapper/*.xml
#resource下的mapper映射文件
#mybatis.mapper-locations=classpath*:mapper/**/*.xml
mybatis.mapper-locations=classpath:mapper/BookMapper.xml
mybatis.config-location=classpath:mybatis/mybatis-config.xml

pagehelper.helper-dialect=mysql
pagehelper.reasonable=true
pagehelper.support-methods-arguments=true
pagehelper.params=count=countSql

 

五、后端代码

package com.example.pojo;

import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonIgnore;

import java.io.Serializable;
import java.util.Date;

public class Book implements Serializable {
    private Integer id;
    private String name;
    private String author;
    @JsonIgnore
    private Float price;
    @JsonFormat(pattern = "yyyy-MM-dd")
    private Date publicationDate;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }

    public Float getPrice() {
        return price;
    }

    public void setPrice(Float price) {
        this.price = price;
    }

    public Date getPublicationDate() {
        return publicationDate;
    }

    public void setPublicationDate(Date publicationDate) {
        this.publicationDate = publicationDate;
    }
}
package com.example.mapper;

import com.example.pojo.Book;
import org.apache.ibatis.annotations.Mapper;

import java.util.List;

@Mapper
public interface BookMapper {
    int addBook(Book book);
    int deleteBookById(Integer id);
    int updateBook(Book book);
    Book getBookById(Integer id);
    List<Book> getAllBooks();
}

mapper/BookMapper.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.example.mapper.BookMapper">
    <!--
    <insert id="addBook" parameterType="com.example.pojo.Book">
        INSERT INTO book(name,author) VALUES (#{name},#{author})
    </insert>
    <insert id="addBook" keyProperty="id" useGeneratedKeys="true"
 parameterType="com.example.pojo.Book">
        INSERT INTO book(name,author) VALUES (#{name},#{author})

     </insert>
     -->
    <insert id="addBook" parameterType="com.example.pojo.Book">
        <selectKey keyProperty="id" resultType="int" order="BEFORE">
            <!--
            select idseq.nextVal from dual
            -->
            SELECT
            auto_increment
            FROM
            information_schema.`TABLES`
            WHERE
            table_name = 'book'
            AND TABLE_SCHEMA = 'vhr'
        </selectKey>
        INSERT INTO book(id,name,author) VALUES (#{id},#{name},#{author})
    </insert>
    <delete id="deleteBookById" parameterType="int">
        delete from book where id=#{id}
    </delete>
    <update id="updateBook" parameterType="com.example.pojo.Book">
        update book set name=#{name},author=#{author} where id=#{id}
    </update>
    <select id="getBookById" parameterType="int" resultType="com.example.pojo.Book">
        select * from book where id=#{id}
    </select>
    <select id="getAllBooks" resultType="com.example.pojo.Book">
        select * from book
    </select>
</mapper>
package com.example.service;

import com.example.pojo.Book;

import java.util.List;

public interface BookService {

    int addBook(Book book);

    int updateBook(Book book);

    int deleteBookById(Integer id);

    Book getBookById(Integer id);

    List<Book> getAllBooks();

    List<Book> findBooks(int page, int rows);

}
package com.example.service;

import com.example.mapper.BookMapper;
import com.example.pojo.Book;
import com.github.pagehelper.PageHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class BookServiceImpl implements BookService{

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Resource//@Autowired
    BookMapper bookMapper;

    @Override
    public int addBook(Book book) {
//        return bookMapper.addBook(book);
//        int insertNum = Integer.parseInt(bookMapper.addBook(book) + "");
        int insertNum = bookMapper.addBook(book);
        Integer id = book.getId();
        logger.info(insertNum+"------BookServiceImpl.addBook()-----------"+id);
        return id;
    }

    @Override
    public int updateBook(Book book) {
        return bookMapper.updateBook(book);
    }

    @Override
    public int deleteBookById(Integer id) {
        return bookMapper.deleteBookById(id);
    }

    @Override
    public Book getBookById(Integer id) {
        return bookMapper.getBookById(id);
    }

    @Override
    public List<Book> getAllBooks() {
        return bookMapper.getAllBooks();
    }

    @Override
    public List<Book> findBooks(int page, int rows) {
        PageHelper.startPage(page,rows);
        return bookMapper.getAllBooks();
    }


}
package com.example.controller;

import com.example.pojo.Book;
import com.example.service.BookService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class BookController {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    //@Autowired
    @Resource
    private BookService bookService;

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

    @RequestMapping("/save")
    @ResponseBody
    public Map<String, Object> save(@RequestBody Book book){
        Map<String,Object> result = new HashMap<>();
        if(StringUtils.isEmpty(book.getId())){
            book.setId(bookService.addBook(book));
        }else{
            bookService.updateBook(book);
        }
        result.put("id",book.getId());
        return result;
    }

    @RequestMapping("/get")
    @ResponseBody
    public Book get(Integer id){
        return bookService.getBookById(id);
    }

    @RequestMapping("/findAll")
    @ResponseBody
    public List<Book> findAll(){
        logger.info("-----BookController.findAll()--------------------test-----------");
        List<Book> list = bookService.getAllBooks();
        for(int i=0;i<list.size();i++){
            System.out.println(i+"------"+list.get(i).getName());
        }
        return list;
    }

    @RequestMapping("/delete")
    @ResponseBody
    public Map<String, Object> delete(Integer id){
        Map<String, Object> result = new HashMap<>();
        bookService.deleteBookById(id);
        result.put("id", id);
        return result;
    }

    @RequestMapping("/saveBook")
    @ResponseBody
    public String saveBook(){
        logger.info("-------------------------test-----------");
        Book book = new Book();
        book.setAuthor("罗贯中");
        book.setName("三国演义");
        bookService.addBook(book);
        return  "success";
    }

    @RequestMapping("/findBooks/{page}/{rows}")
    @ResponseBody
    public List<Book> findBooks(@PathVariable int page,@PathVariable int rows){
        return bookService.findBooks(page,rows);
    }

    @GetMapping("/book")
    @ResponseBody
    public Book book(){
        Book book = new Book();
        book.setAuthor("罗贯中");
        book.setName("三国演义");
        book.setPrice(48f);
        book.setPublicationDate(new Date());
        return book;
    }

    @GetMapping("/bookOps")
    @ResponseBody
    public void bookOps(){
        Book b1 = new Book();
        b1.setName("西厢记");
        b1.setAuthor("王实甫");
        int i = bookService.addBook(b1);
        System.out.println("addBook>>"+i);
        Book b2 = new Book();
        b2.setId(2);
        b2.setName("朝花夕拾");
        b2.setAuthor("鲁迅");
        int updateBook = bookService.updateBook(b2);
        System.out.println("updateBook>>"+updateBook);
        Book b3 = bookService.getBookById(1);
        System.out.println("getBookById>>"+b3);
        int delete = bookService.deleteBookById(1);
        System.out.println("deleteBookById>>"+delete);
        List<Book> allBooks=bookService.getAllBooks();
        System.out.println("getAllBooks>>>"+allBooks);
    }



}
package com.example.demo;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication(scanBasePackages = {"com.example.controller","com.example.service"})
@MapperScan("com.example.mapper")
public class DemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

}

六、前端代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <!--
    <script src="//cdn.bootcss.com/angular.js/1.5.8/angular.min.js"></script>
    -->
    <script src="/angular-1.8.2/angular.min.js"></script>
</head>
<body ng-app="myApp" ng-controller="TestBookController">
    <h1>SpringBoot整合Angularjs</h1>
    <input type="button" value="添加" ng-click="add()" />
    <input type="button" value="保存" ng-click="save()" />
    <br />
    <br />

    <h3>书本信息</h3>
    <input id="id" type="hidden" ng-model="data.id" />
    <table cellspacing="1" style="background-color: #a0c6e5">
        <tr>
            <td>书名:</td>
            <td><input id="name" ng-model="data.name"/></td>
            <td>作者:</td>
            <td><input id="author" ng-model="data.author"/></td>
        </tr>
    </table>
    <br />
    <h3>列表信息</h3>
    <table cellspacing="1" style="background-color: #a0c6e5">
        <tr style="text-align: center;color: #0076c8;background-color: #f4faff;">
            <td>操作</td>
            <td>书名</td>
            <td>作者</td>
        </tr>
        <tr ng-repeat="row in rows" bgcolor="#f0ffff">
            <td>
                <input ng-click="edit(row.id)" value="编辑" type="button"/>
                <input ng-click="del(row.id)" value="删除" type="button"/>
            </td>
            <td>{{row.name}}</td>
            <td>{{row.author}}</td>
        </tr>
    </table>

<script type="text/javascript">
    /*<![CDATA[*/
    var app = angular.module('myApp', []);
    // app.controller('customersCtrl', function($scope, $http) {
    //     $http.get("/try/angularjs/data/Customers_JSON.php")
    //         .then(function (result) {
    //             $scope.names = result.data.records;
    //         });
    // });
    app.controller('TestBookController', function($rootScope, $scope, $http) {
        $scope.data = {};
        $scope.rows = [];

        //添加
        $scope.add = function(){
            $scope.data = {
                name : '水浒传',
                author : '施耐庵'
            };
        }

        //编辑
        $scope.edit = function (id) {
            for(var i in $scope.rows){
                var row = $scope.rows[i];
                if(id == row.id){
                    $scope.data = row;
                    return;
                }
            }
        }

        //移除
        $scope.remove = function(id){
            for(var i in $scope.rows){
                var row = $scope.rows[i];
                if(id == row.id){
                    $scope.rows.splice(i,1);
                    return;
                }
            }
        }

        //保存
        $scope.save = function () {
            $http({
                url : '/save',
                method : 'POST',
                data : $scope.data
            }).then(function(result){
                //保存成功后更新数据
                $scope.get(result.data.id);
            });
        }

        //删除
        $scope.del = function(id){
            $http({
                url : '/delete?id='+id,
                method : 'POST'
            }).then(function(result){
                //删除成功后移除数据
                $scope.remove(result.data.id);
            });
        }

        //获取数据
        $scope.get = function(id){
            $http({
                url : '/get?id='+id,
                method : 'POST'
            }).then(function(result){
                for(var i in $scope.rows){
                    var row = $scope.rows[i];
                    if(result.data.id == row.id){
                        row.name = result.data.name;
                        row.author = result.data.author;
                        return;
                    }
                }
                $scope.rows.push(result.data);
            });
        }

        //初始化载入数据
        // $http({
        //     url : 'findAll',
        //     mehtod : 'POST'
        // }).success(function(rows){
        //     for(var i in rows){
        //         var row = rows[i];
        //         $scope.rows.push(row);
        //     }
        // });


        //初始化载入数据
        $http({
            url : 'findAll',
            mehtod : 'POST'
        }).then(function (result) {  //正确请求成功时处理
            console.info("--初始化载入数据----正确请求成功时处理---------"+JSON.stringify(result));
            for(var i in result.data){
                var row = result.data[i];
                $scope.rows.push(row);
            }
        }).catch(function (result) { //捕捉错误处理
            console.info(JSON.stringify(result));
            // alert(result.data.Message);
        });


        // $http.get("/try/angularjs/data/Customers_JSON.php")
        //     .then(function (result) {
        //         $scope.names = result.data.records;
        //     });
    });

    /*]]>*/
</script>
</body>
</html>

七、测试

 

posted @ 2021-04-03 10:42  残星  阅读(1123)  评论(0编辑  收藏  举报