Spring Boot 之整合 EasyUI 打造 Web 应用

SpringBootTutorial :: Web :: UI :: EasyUI

EasyUI 是一个简单的用户界面组件的集合。由于 EasyUI 已经封装好大部分 UI 基本功能,能帮用户减少大量的 js 和 css 代码。所以,EasyUI 非常适合用于开发简单的系统或原型系统。

本文示例使用技术点:

  • Spring Boot:主要使用了 spring-boot-starter-web、spring-boot-starter-data-jpa
  • EasyUI:按需加载,并没有引入所有的 EasyUI 特性
  • 数据库:为了测试方便,使用 H2

简介

什么是 EasyUI?

  • easyui 是基于 jQuery、Angular.、Vue 和 React 的用户界面组件的集合。
  • easyui 提供了构建现代交互式 javascript 应用程序的基本功能。
  • 使用 easyui,您不需要编写许多 javascript 代码,通常通过编写一些 HTML 标记来定义用户界面。
  • 完整的 HTML5 网页框架。
  • 使用 easyui 开发你的产品时可以大量节省你的时间和规模。
  • easyui 使用非常简单但功能非常强大。

Spring Boot 整合 EasyUI

配置

application.properties 修改:

spring.mvc.view.prefix = /views/
spring.mvc.view.suffix = .html

引入 easyui

EasyUI 下载地址:http://www.jeasyui.cn/download.html

src/main/resources/static 目录下引入 easyui。

然后在 html 中引用:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <link
      rel="stylesheet"
      type="text/css"
      href="../lib/easyui/themes/bootstrap/easyui.css"
    />
    <link
      rel="stylesheet"
      type="text/css"
      href="../lib/easyui/themes/icon.css"
    />
    <link
      rel="stylesheet"
      type="text/css"
      href="../lib/easyui/themes/color.css"
    />
    <script type="text/javascript" src="../lib/easyui/jquery.min.js"></script>
    <script
      type="text/javascript"
      src="../lib/easyui/jquery.easyui.min.js"
    ></script>
    <script
      type="text/javascript"
      src="../lib/easyui/locale/easyui-lang-zh_CN.js"
    ></script>
  </head>
  <body>
    <!-- 省略 -->
  </body>
</html>

引入 easyui 后,需要使用哪种组件,可以查看相关文档或 API,十分简单,此处不一一赘述。

实战

引入 maven 依赖

  <dependencies>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-tomcat</artifactId>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-test</artifactId>
      <scope>test</scope>
    </dependency>

    <dependency>
      <groupId>com.h2database</groupId>
      <artifactId>h2</artifactId>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-devtools</artifactId>
    </dependency>
    <dependency>
      <groupId>commons-collections</groupId>
      <artifactId>commons-collections</artifactId>
      <version>3.2.2</version>
    </dependency>
  </dependencies>

使用 JPA

为了使用 JPA 技术访问数据,我们需要定义 Entity 和 Repository

定义一个 Entity:

@Entity
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    private String firstName;
    private String lastName;
    private String phone;
    private String email;

    protected User() {}

    public User(String firstName, String lastName, String phone, String email) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.phone = phone;
        this.email = email;
    }

    // 略 getter/setter
}

定义一个 Repository:

public interface UserRepository extends CrudRepository<User, Long> {

    List<User> findByLastName(String lastName);
}

使用 Web

首页 Controller,将 web 请求定向到指定页面(下面的例子定向到 index.html)

@Controller
public class IndexController {

    @RequestMapping(value = {"", "/", "index"})
    public String index() {
        return "index";
    }

}

此外,需要定义一个 Controller,提供后台的 API 接口

@Controller
public class UserController {

    @Autowired
    private UserRepository customerRepository;

    @RequestMapping(value = "/user", method = RequestMethod.GET)
    public String user() {
        return "user";
    }

    @ResponseBody
    @RequestMapping(value = "/user/list")
    public ResponseDTO<User> list() {
        Iterable<User> all = customerRepository.findAll();
        List<User> list = IteratorUtils.toList(all.iterator());
        return new ResponseDTO<>(true, list.size(), list);
    }

    @ResponseBody
    @RequestMapping(value = "/user/add")
    public ResponseDTO<User> add(User user) {
        User result = customerRepository.save(user);
        List<User> list = new ArrayList<>();
        list.add(result);
        return new ResponseDTO<>(true, 1, list);
    }

    @ResponseBody
    @RequestMapping(value = "/user/save")
    public ResponseDTO<User> save(@RequestParam("id") Long id, User user) {
        user.setId(id);
        customerRepository.save(user);
        List<User> list = new ArrayList<>();
        list.add(user);
        return new ResponseDTO<>(true, 1, list);
    }

    @ResponseBody
    @RequestMapping(value = "/user/delete")
    public ResponseDTO delete(@RequestParam("id") Long id) {
        customerRepository.deleteById(id);
        return new ResponseDTO<>(true, null, null);
    }

}

使用 EasyUI

接下来,我们要使用前面定义的后台接口,仅需要在 EasyUI API 中指定 url 即可。

请留意下面示例中的 url 字段,和实际接口是一一对应的。

<!DOCTYPE html>
<html>
  <head>
    <title>Complex Layout - jQuery EasyUI Demo</title>
    <meta charset="UTF-8" />
    <link
      rel="stylesheet"
      type="text/css"
      href="../lib/easyui/themes/bootstrap/easyui.css"
    />
    <link
      rel="stylesheet"
      type="text/css"
      href="../lib/easyui/themes/icon.css"
    />
    <link
      rel="stylesheet"
      type="text/css"
      href="../lib/easyui/themes/color.css"
    />
    <script type="text/javascript" src="../lib/easyui/jquery.min.js"></script>
    <script
      type="text/javascript"
      src="../lib/easyui/jquery.easyui.min.js"
    ></script>
    <script
      type="text/javascript"
      src="../lib/easyui/locale/easyui-lang-zh_CN.js"
    ></script>
    <style type="text/css">
      body {
        font-family: microsoft yahei;
      }
    </style>
  </head>
  <body>
    <div style="width:100%">
      <h2>基本的 CRUD 应用</h2>
      <p>数据来源于后台系统</p>

      <table
        id="dg"
        title="Custom List"
        class="easyui-datagrid"
        url="/user/list"
        toolbar="#toolbar"
        pagination="true"
        rownumbers="true"
        fitColumns="true"
        singleSelect="true"
      >
        <thead>
          <tr>
            <th field="id" width="50">ID</th>
            <th field="firstName" width="50">First Name</th>
            <th field="lastName" width="50">Last Name</th>
            <th field="phone" width="50">Phone</th>
            <th field="email" width="50">Email</th>
          </tr>
        </thead>
      </table>
      <div id="toolbar">
        <a
          href="javascript:void(0)"
          class="easyui-linkbutton"
          iconCls="icon-add"
          plain="true"
          onclick="newUser()"
          >添加</a
        >
        <a
          href="javascript:void(0)"
          class="easyui-linkbutton"
          iconCls="icon-edit"
          plain="true"
          onclick="editUser()"
          >修改</a
        >
        <a
          href="javascript:void(0)"
          class="easyui-linkbutton"
          iconCls="icon-remove"
          plain="true"
          onclick="destroyUser()"
          >删除</a
        >
      </div>

      <div
        id="dlg"
        class="easyui-dialog"
        style="width:400px"
        data-options="closed:true,modal:true,border:'thin',buttons:'#dlg-buttons'"
      >
        <form
          id="fm"
          method="post"
          novalidate
          style="margin:0;padding:20px 50px"
        >
          <h3>User Information</h3>
          <div style="margin-bottom:10px">
            <input
              name="firstName"
              class="easyui-textbox"
              required="true"
              label="First Name:"
              style="width:100%"
            />
          </div>
          <div style="margin-bottom:10px">
            <input
              name="lastName"
              class="easyui-textbox"
              required="true"
              label="Last Name:"
              style="width:100%"
            />
          </div>
          <div style="margin-bottom:10px">
            <input
              name="phone"
              class="easyui-textbox"
              required="true"
              label="Phone:"
              style="width:100%"
            />
          </div>
          <div style="margin-bottom:10px">
            <input
              name="email"
              class="easyui-textbox"
              required="true"
              validType="email"
              label="Email:"
              style="width:100%"
            />
          </div>
        </form>
      </div>
      <div id="dlg-buttons">
        <a
          href="javascript:void(0)"
          class="easyui-linkbutton c6"
          iconCls="icon-ok"
          onclick="saveUser()"
          style="width:90px"
          >Save</a
        >
        <a
          href="javascript:void(0)"
          class="easyui-linkbutton"
          iconCls="icon-cancel"
          onclick="javascript:$('#dlg').dialog('close')"
          style="width:90px"
          >Cancel</a
        >
      </div>
    </div>

    <script type="text/javascript">
      var url;

      function newUser() {
        $('#dlg')
          .dialog('open')
          .dialog('center')
          .dialog('setTitle', 'New User');
        $('#fm').form('clear');
        url = '/user/add';
      }

      function editUser() {
        var row = $('#dg').datagrid('getSelected');
        if (row) {
          $('#dlg')
            .dialog('open')
            .dialog('center')
            .dialog('setTitle', 'Edit User');
          $('#fm').form('load', row);
          url = '/user/save';
        }
      }

      function saveUser() {
        $('#fm').form('submit', {
          url: url,
          onSubmit: function() {
            return $(this).form('validate');
          },
          success: function(result) {
            var result = eval('(' + result + ')');
            if (result.errorMsg) {
              $.messager.show({
                title: 'Error',
                msg: result.errorMsg
              });
            } else {
              $('#dlg').dialog('close'); // close the dialog
              $('#dg').datagrid('reload'); // reload the user data
            }
          }
        });
      }

      function destroyUser() {
        var row = $('#dg').datagrid('getSelected');
        if (row) {
          $.messager.confirm(
            'Confirm',
            'Are you sure you want to destroy this user?',
            function(r) {
              if (r) {
                $.post(
                  '/user/delete',
                  { id: row.id },
                  function(result) {
                    if (result.success) {
                      $('#dg').datagrid('reload'); // reload the user data
                    } else {
                      $.messager.show({
                        // show error message
                        title: 'Error',
                        msg: result.errorMsg
                      });
                    }
                  },
                  'json'
                );
              }
            }
          );
        }
      }
    </script>
  </body>
</html>

完整示例

请参考 源码

运行方式:

mvn clean package -DskipTests=true
java -jar target/

在浏览器中访问:http://localhost:8080/

引用和引申

posted @ 2019-01-08 16:42  静默虚空  阅读(10425)  评论(3编辑  收藏  举报