用Jersey构建RESTful服务8--Jersey+SQLServer+Hibernate4.3+Spring3.2+jquery

本文涉及的产品
云数据库 RDS SQL Server,独享型 2核4GB
简介:

一、总体说明

本例运行演示了用 Jersey 构建 RESTful 服务中,如何集成 jQuery,用html作为客户端访问 RESTful 服务。

二、环境

  • 1.上文的项目RestDemo
  • 2.jQuery 库 ,本例为1.7.1版本

    三、配置

    配置

  • 创建 jQuery 客户端的项目结构,在WebContent创建js,css两个目录,并把jQuery 库 放入js目录下,并在该目录下创建main,js空文件

  • WebContent创建index.html:

    <!DOCTYPE HTML>
    <html>
    <head>
    <title>jquery Demo (人员管理系统)</title>
    <meta charset="utf-8"/>
    <link rel="stylesheet" href="css/styles.css" />

    <script src="js/jquery-1.7.1.min.js"></script>
    <script src="js/main.js"></script>
    </head>

    <body>
        <div class="header">

            <button id="btnClear">Clear</button>
            <button id="btnRefreash">Refreash</button>
            更多实例访问:<a href="http://www.waylau.com" >www.waylau.com</a>
        </div>


        <div class="leftArea">
            <ul id="userList"></ul>
        </div>

        <form id="wineForm">

            <div class="mainArea">

                <label>Id:</label> <input id="userId" name="userId" type="text"  required/>

                <label>Name:</label> <input type="text" id="userName" name="userName" required> 
                <label>Age:</label> <input  type="text" id="age" name="age" required/>

                <button id="btnAdd">Add</button>
                <button id="btnSave">Save</button>
                <button id="btnDelete">Delete</button>
            </div>

        </form>

    </body>
    </html>
  1. 修改main.js
    // The root URL for the RESTful services
    var rootURL = 'http://localhost:8089/RestDemo/rest/users';

    var currentUser;

    // Retrieve wine list when application starts 
    findAll();

    // Nothing to delete in initial application state
    $('#btnDelete').hide();

    $('#btnAdd').click(function() {
        addUser();
        return false;
    });

    $('#btnSave').click(function() {

        updateUser();
        return false;
    });

    $('#btnClear').click(function() {
        newUser();
        return false;
    });


    $('#btnDelete').click(function() {
        deleteUser();
        return false;
    });

    $('#userList a').live('click', function() {
        findById($(this).data('identity'));
    });

    $('#btnRefreash').click(function() {
        findAll();
        return false;
    });


    function newUser() {
        $('#btnDelete').hide();
        currentUser = {};
        renderDetails(currentUser); // Display empty form
    }

    function findAll() {
        console.log('findAll');
        $.ajax({
            type: 'GET',
            url: rootURL,
            dataType: "json", // data type of response
            success: renderList
        });
    }


    function findById(id) {
        console.log('findById: ' + id);
        $.ajax({
            type: 'GET',
            url: rootURL + '/' + id,
            dataType: "json",
            success: function(data){
                $('#btnDelete').show();

                console.log('findById success: ' + data.userName);
                currentUser = data;
                renderDetails(currentUser);
            }

        });
    }

    function addUser() {
        console.log('addUser');
        $.ajax({
            type: 'POST',
            contentType: 'application/json',
            url: rootURL,
            dataType: "json",
            data: formToJSON(),
            success: function(data, textStatus, jqXHR){
                alert('User created successfully');
                $('#btnDelete').show();
                $('#userId').val(data.userId);
            },
            error: function(jqXHR, textStatus, errorThrown){
                alert('addUser error: ' + textStatus);
            }
        });
    }

    function updateUser() {
        console.log('updateUser');
        $.ajax({
            type: 'PUT',

            contentType: 'application/json',
            url: rootURL,
            dataType: "json",
            data: formToJSON(),

            success: function(data, textStatus, jqXHR){
                alert('User updated successfully');
            },
            error: function(jqXHR, textStatus, errorThrown){
                alert('updateUser error: ' + textStatus);
            }
        });
    }

    function deleteUser() {
        console.log('deleteUser');
        $.ajax({
            type: 'DELETE',
            url: rootURL + '/' + $('#userId').val(),
            success: function(data, textStatus, jqXHR){
                alert('user deleted successfully');
            },
            error: function(jqXHR, textStatus, errorThrown){
                alert('delete user error');
            }
        });
    }

    function renderList(data) {
        // JAX-RS serializes an empty list as null, and a 'collection of one' as an object (not an 'array of one')
        var list = data == null ? [] : (data instanceof Array ? data : [data]);

        $('#userList li').remove();
        $.each(list, function(index, data) {
            $('#userList').append('<li><a href="#" data-identity="' + data.userId + '">'+data.userName+'</a></li>');
        });
    }

    function renderDetails(data) {
        $('#userId').val(data.userId);
        $('#userName').val(data.userName);
        $('#age').val(data.age);

    }

    // Helper function to serialize all the form fields into a JSON string
    function formToJSON() {
        var userId = $('#userId').val();
        return JSON.stringify({
            "userId": userId == "" ? null : userId, 
            "userName": $('#userName').val(), 
            "age": $('#age').val() 
            });
    }
  1. css目录下创建styles.css文件
    * {
      font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
      font-size: 18px;
    }

    .header {
        padding-top: 5px;

    }

    .leftArea {
        position: absolute;
        left: 10px;
        top: 70px;
        bottom: 20px;
        width: 260px;
        border:solid 1px #CCCCCC;
        overflow-y: scroll;
    }

    .mainArea {
        position: absolute;
        top: 70px;
        bottom: 20px;
        left:300px;
        overflow-y: scroll;
        width:300px;
    }

    .rightArea {
        position: absolute;
        top: 70px;
        bottom: 20px;
        left:650px;
        overflow-y: scroll;
        width:270px;
    }

    ul {
        list-style-type: none;
        padding-left: 0px;
        margin-top: 0px;
    }

    li a { 
        text-decoration:none;
        display: block;
        color: #000000;
        border-bottom:solid 1px #CCCCCC;
        padding: 8px;
    }

    li a:hover {
        background-color: #4B0A1E;
        color: #BA8A92;
    }

    input, textarea {
      border:1px solid #ccc;
      min-height:30px;
      outline: none;
    }

    .mainArea input {
      margin-bottom:15px;
      margin-top:5px;
      width:280px;
    }

    textarea {
        margin-bottom:15px;
        margin-top:5px;
        height: 200px;
        width:250px;
    }

    label {
        display:block;
    }

    button {
        padding:6px;
    }


    #searchKey {
        width:160px;
    }

四、运行

1.先运行项目

2.可以进行CURD操作 CURD

PS:本案例力求简单把jquery访问 RESTful 服务展示出来,代码只在Chrome上做过测试。

本章源码https://github.com/waylau/RestDemo/tree/master/jersey-demo8-sqlserver-hibernate-spring3-jquery


相关实践学习
使用SQL语句管理索引
本次实验主要介绍如何在RDS-SQLServer数据库中,使用SQL语句管理索引。
SQL Server on Linux入门教程
SQL Server数据库一直只提供Windows下的版本。2016年微软宣布推出可运行在Linux系统下的SQL Server数据库,该版本目前还是早期预览版本。本课程主要介绍SQLServer On Linux的基本知识。 相关的阿里云产品:云数据库RDS&nbsp;SQL Server版 RDS SQL Server不仅拥有高可用架构和任意时间点的数据恢复功能,强力支撑各种企业应用,同时也包含了微软的License费用,减少额外支出。 了解产品详情:&nbsp;https://www.aliyun.com/product/rds/sqlserver
目录
相关文章
|
6天前
|
Java API 微服务
【Spring Boot系列】通过OpenAPI规范构建微服务服务接口
【4月更文挑战第5天】通过OpenAPI接口构建Spring Boot服务RestAPI接口
|
1月前
|
SpringCloudAlibaba Java 网络架构
【Springcloud Alibaba微服务分布式架构 | Spring Cloud】之学习笔记(七)Spring Cloud Gateway服务网关
【Springcloud Alibaba微服务分布式架构 | Spring Cloud】之学习笔记(七)Spring Cloud Gateway服务网关
99 0
|
20小时前
|
Java 数据安全/隐私保护 Sentinel
微服务学习 | Spring Cloud 中使用 Sentinel 实现服务限流
微服务学习 | Spring Cloud 中使用 Sentinel 实现服务限流
|
23天前
|
前端开发 Java API
构建RESTful API:Java中的RESTful服务开发
【4月更文挑战第3天】本文介绍了在Java环境中构建RESTful API的重要性及方法。遵循REST原则,利用HTTP方法处理资源,实现CRUD操作。在Java中,常用框架如Spring MVC简化了RESTful服务开发,包括定义资源、设计表示层、实现CRUD、考虑安全性、文档和测试。通过Spring MVC示例展示了创建RESTful服务的步骤,强调了其在现代Web服务开发中的关键角色,有助于提升互操作性和用户体验。
构建RESTful API:Java中的RESTful服务开发
|
29天前
|
安全 API 开发者
构建高效可扩展的RESTful API服务
在数字化转型的浪潮中,构建一个高效、可扩展且易于维护的后端API服务是企业竞争力的关键。本文将深入探讨如何利用现代后端技术栈实现RESTful API服务的优化,包括代码结构设计、性能调优、安全性强化以及微服务架构的应用。我们将通过实践案例分析,揭示后端开发的最佳实践,帮助开发者提升系统的响应速度和处理能力,同时确保服务的高可用性和安全。
29 3
|
1月前
|
缓存 前端开发 API
构建高效可扩展的RESTful API:后端开发的最佳实践
【2月更文挑战第30天】 在现代Web应用和服务端架构中,RESTful API已成为连接前端与后端、实现服务间通信的重要接口。本文将探讨构建一个高效且可扩展的RESTful API的关键步骤和最佳实践,包括设计原则、性能优化、安全性考虑以及错误处理机制。通过这些实践,开发者可以确保API的健壮性、易用性和未来的可维护性。
|
1月前
|
消息中间件 SpringCloudAlibaba Java
【Springcloud Alibaba微服务分布式架构 | Spring Cloud】之学习笔记(八)Config服务配置+bus消息总线+stream消息驱动+Sleuth链路追踪
【Springcloud Alibaba微服务分布式架构 | Spring Cloud】之学习笔记(八)Config服务配置+bus消息总线+stream消息驱动+Sleuth链路追踪
784 0
|
1月前
|
SpringCloudAlibaba 负载均衡 Java
【Springcloud Alibaba微服务分布式架构 | Spring Cloud】之学习笔记(三)Eureka服务注册中心
【Springcloud Alibaba微服务分布式架构 | Spring Cloud】之学习笔记(三)Eureka服务注册中心
44 1
|
安全 Java 应用服务中间件
Java 近期新闻:Hibernate 6.0、JobRunr 5.0、JHipster 7.8.0、Spring CVEs、JReleaser 1.0-RC2
本期 Java 近期新闻综述内容涉及 JDK 19、Spring Boot、Spring CVEs、Apache Tomcat 点版本、Quarkus Tools for Visual Studio Code、Micronaut 3.4.1、JetBrains 加入 Micronaut 基金会、Open Liberty Paketo Liberty Buildpack、Hibernate 6.0、JobRunr 5.0、WildFly 26.1 Beta S2I 镜像、JReleaser 1.0-RC2、MicroStream 7.0-M2、JHipster 7.8.0、JMH 1.35。
782 0
|
17天前
|
SQL Java 数据库连接
jpa、hibernate、spring-data-jpa、jdbcTemplate
jpa、hibernate、spring-data-jpa、jdbcTemplate