美文网首页
Java高级技术day84:JsonP和HttpClient

Java高级技术day84:JsonP和HttpClient

作者: 开源oo柒 | 来源:发表于2019-11-17 18:09 被阅读0次

    一、Jsonp的简介

    1.什么是 JsonP?

    Jsonp(JSON with Padding) 是 json 的一种"使用模式",可以让网页从别的域名(网站)那获取资料,即跨域读取数据。
    为什么我们从不同的域(网站)访问数据需要一个特殊的技术(JSONP )呢?这是因为同源策略。

    2.什么是跨域?

    跨域是指一个域(网站)下的文档或脚本试图去请求另一个域(网站)下的资源。

    示例

    3. 什么是同源策略?

    同源策略/SOP(Same origin policy)是一种约定,由 Netscape 公司 1995 年引入浏览器,它是浏览器最核心也最基本的安全功能,现在所有支持 JavaScript 的浏览器都会使用这个策略。如果缺少了同源策略,浏览器很容易受到 XSS、CSFR 等攻击。所谓同源是指"协议+域名+端口"三者相同,即便两个不同的域名指向同一个 ip 地址,也非同源。

    • 非同源策略限制以下几种行为:

    (1)Cookie、LocalStorage 和 IndexDB 无法读取;
    (2) DOM 和 Js 对象无法获得;
    (3)AJAX 请求不能发送;

    • 常见跨域场景:


      示例
    • 跨域解决方案:
      (1) 通过 jsonp 跨域
      (2)document.domain + iframe 跨域
      (3) location.hash + iframe
      (4)window.name + iframe 跨域
      (5) postMessage 跨域
      (6)跨域资源共享(CORS)
      (7)nginx 代理跨域
      (8) nodejs 中间件代理跨域
      (9) WebSocket 协议跨域

    4.JsonP 优缺点:

    优点:它不像 XMLHttpRequest 对象实现的 Ajax 请求那样受到同源策略的限制;它的兼容性更好,在更加古老的浏览器中都 可以运行,不需要 XMLHttpRequest 或ActiveX 的支持;并且在请求完毕后可以通过调用 callback 的方式回传结果。
    缺点:它只支持 GET 请求而不支持 POST 等其它类型的 HTTP 请求;它
    只支持跨域 HTTP 请求这种情况,不能解决不同域的两个页面之间如何进行 JavaScript 调用的问题。

    二、JsonP 的使用

    1.搭建跨域场景:

    (1)创建两个 web 工程,名称为 jsonDemo1(8080)、jsonDemo2(9090)
    (2)jsonDemo1 中提供一个 index.jsp。
    (3)在 jsonDemo1 的 index.jsp 中通过 Jquery 的 Ajax 跨域请求 jsonDemo2
    (4)jsonDemo2 中使用 springMVC 处理请求,返回一个 json 对象
    (5)在 jsonDemo1 中将返回的结果插入到 index.jsp 中

    • Ajax 跨域请求时会出现异常:


      异常

    2.改变ajax请求方式:

    <head>
    <meta charset="UTF-8">
    <title>Insert title here</title>
    <script type="text/javascript" src="/js/jquery-1.7.2.js"></script>
    <script type="text/javascript">
        $(function() {
            $("#but").click(
                    function() {
                        $.get("/user/show", function(data) {
                            var str = "";
                            for (i = 0; i < data.length; i++) {
                                str += data[i].userid + " " + data[i].username
                                        + " " + data[i].userage + " | ";
                            }
                            $("#sp").html(str);
                        });
                    })
    
        })
    </script>
    </head>
    <body>
        <span style="font-size: 20px" id="sp"></span>
        <br />
        <p>
            <input type="button" value="查看" id="but" />
        </p>
    </body>
    
    • 修改POM文件:
        <dependencies>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-webmvc</artifactId>
            </dependency>
            <!-- JSP相关 -->
            <dependency>
                <groupId>jstl</groupId>
                <artifactId>jstl</artifactId>
            </dependency>
            <dependency>
                <groupId>javax.servlet</groupId>
                <artifactId>servlet-api</artifactId>
                <scope>provided</scope>
            </dependency>
            <dependency>
                <groupId>javax.servlet</groupId>
                <artifactId>jsp-api</artifactId>
                <scope>provided</scope>
            </dependency>
            <!-- Jackson Json处理工具包 -->
            <dependency>
                <groupId>com.fasterxml.jackson.core</groupId>
                <artifactId>jackson-databind</artifactId>
            </dependency>
        </dependencies>
        <build>
            <plugins>
                <!-- 配置Tomcat插件 -->
                <plugin>
                    <groupId>org.apache.tomcat.maven</groupId>
                    <artifactId>tomcat7-maven-plugin</artifactId>
                    <configuration>
                        <path>/</path>
                        <port>9090</port>
                    </configuration>
                </plugin>
            </plugins>
        </build>
    

    3.改变请求的Controller:

    @Controller
    @RequestMapping("/user")
    public class UserController {
        
        @RequestMapping("/show")
        @ResponseBody
        public Object userShow(String callback) {
            Users users = new Users(01,"张三",20);
            Users users2 = new Users(02, "李四", 18);
            Users users3 = new Users(03, "admin", 22);
            
            List<Users> list = new ArrayList<>();
            list.add(users);
            list.add(users2);
            list.add(users3);
    //      String json = JsonUtils.objectToJson(list);
    //      return callback+"("+json+")";
            //json转换
            MappingJacksonValue mjv = new MappingJacksonValue(list);
            mjv.setJsonpFunction(callback);
            return mjv;
        }
    
    • 效果:


      8080
      9090

    三、HttpClient 简介

    HttpClient 是 Apache Jakarta Common 下的子项目,可以用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建议。
    HTTP 协议可能是现在 Internet 上使用得最多、最重要的协议了,越来越多的 Java应用程序需要直接通过 HTTP 协议来访问网络资源。虽然在 JDK 的 java net 包中已经提供了访问 HTTP 协议的基本功能,但是对于大部分应用程序来说,JDK 库本身提供的功能还不够丰富和灵活。

    四、HttpClient 应用

    1. 发送 GET 请求:

    1.1不带参数的:

    • 修改POM文件:
            <!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
            <dependency>
                <groupId>org.apache.httpcomponents</groupId>
                <artifactId>httpclient</artifactId>
                <version>4.5.2</version>
            </dependency>
    
    • 编写测试代码:
        private static void doGet() throws Exception {
    
            // 创建HttpClient对象
            CloseableHttpClient client = HttpClients.createDefault();
            // 创建get请求对象,请求中输入url
            HttpGet httpGet = new HttpGet("http://www.jd.com");
            // 发送请求,返回响应
            CloseableHttpResponse execute = client.execute(httpGet);
            // 处理响应
            // 获取响应的状态码
            int code = execute.getStatusLine().getStatusCode();
            // 获取响应内容
            HttpEntity entity = execute.getEntity();
            String str = EntityUtils.toString(entity, "utf-8");
            System.out.println(code);
            System.out.println(str);
            // 关闭连接
            client.close();
        }
    
    1.2带参数:
        /**
         * 带参数
         * 
         * @throws URISyntaxException
         * @throws IOException 
         * @throws ClientProtocolException 
         */
        private static void doGet02() throws Exception {
            CloseableHttpClient client = HttpClients.createDefault();
            // 创建一个封装URI对象。在该对象中可以带请求参数
            URIBuilder uri = new URIBuilder("https://www.sogou.com");
            uri.addParameter("query", "java");
            // 创建一个get请求对象
            HttpGet httpGet = new HttpGet(uri.build());
            // 发送请求,返回响应
            CloseableHttpResponse execute = client.execute(httpGet);
            // 处理响应
            // 获取响应的状态码
            int code = execute.getStatusLine().getStatusCode();
            // 获取响应内容
            HttpEntity entity = execute.getEntity();
            String str = EntityUtils.toString(entity, "utf-8");
            System.out.println(code);
            System.out.println(str);
            //关闭连接
            client.close();
        }
    
    • 测试:
        public static void main(String[] args) throws Exception {
    //      TestHttpClient.doGet();
            TestHttpClient.doGet02();
        }
    
    

    2.发送post请求:

    2.1不带参数:
        /**
         * 不带参的post请求
         * 
         * @throws Exception
         */
        private static void doPost() throws Exception {
            CloseableHttpClient client = HttpClients.createDefault();
            HttpPost httpPost = new HttpPost("http://localhost:8080/test/post");
            CloseableHttpResponse execute = client.execute(httpPost);
    
            // 处理响应
            // 获取响应的状态码
            int code = execute.getStatusLine().getStatusCode();
            System.out.println(code);
            // 获取响应的内容
            HttpEntity entity = execute.getEntity();
            String str = EntityUtils.toString(entity, "utf-8");
            System.out.println(str);
            // 关闭连接
            client.close();
        }
    
    2.2带参数:
        /**
         * 带参的post请求
         * 
         * @throws Exception
         */
        private static void doPost02() throws Exception {
            CloseableHttpClient client = HttpClients.createDefault();
            HttpPost httpPost = new HttpPost("http://localhost:8080/test/post/param");
            // 给定参数
            ArrayList<BasicNameValuePair> list = new ArrayList<>();
            list.add(new BasicNameValuePair("name", "张三"));
            list.add(new BasicNameValuePair("pwd", "zhangsan"));
            // 将参数做字符串的转换
            StringEntity entiry = new UrlEncodedFormEntity(list, "utf-8");
            // 向请求中绑定参数
            httpPost.setEntity(entiry);
            // 处理响应
            CloseableHttpResponse execute = client.execute(httpPost);
            // 获取响应的状态码
            int code = execute.getStatusLine().getStatusCode();
            System.out.println(code);
            // 获取响应的内容
            HttpEntity entity = execute.getEntity();
            String str = EntityUtils.toString(entity, "utf-8");
            System.out.println(str);
            // 关闭连接
            client.close();
        }
    
    2.3带参json:
        /**
         * 带参json的post请求
         * @throws Exception
         */
        private static void doPost03() throws Exception {
            CloseableHttpClient client = HttpClients.createDefault();
            HttpPost httpPost = new HttpPost("http://localhost:8080/test/post/josn");
            String json = "{\"username\":\"张三\",\"userpwd\":\"zhangsan\"}";
            StringEntity entity = new StringEntity(json,ContentType.APPLICATION_JSON);
            // 向请求中绑定参数
            httpPost.setEntity(entity);
            // 处理响应
            CloseableHttpResponse execute = client.execute(httpPost);
            // 获取响应的状态码
            int code = execute.getStatusLine().getStatusCode();
            System.out.println(code);
            // 获取响应的内容
            HttpEntity en = execute.getEntity();
            String str = EntityUtils.toString(en, "utf-8");
            System.out.println(str);
            // 关闭连接
            client.close();
        }
    
    2.4使用HttpClient 自定义工具类:
    public class HttpClientUtil {
        public static String doGet(String url, Map<String, String> param) {
    
            // 创建Httpclient对象
            CloseableHttpClient httpclient = HttpClients.createDefault();
    
            String resultString = "";
            CloseableHttpResponse response = null;
            try {
                // 创建uri
                URIBuilder builder = new URIBuilder(url);
                if (param != null) {
                    for (String key : param.keySet()) {
                        builder.addParameter(key, param.get(key));
                    }
                }
                URI uri = builder.build();
    
                // 创建http GET请求
                HttpGet httpGet = new HttpGet(uri);
    
                // 执行请求
                response = httpclient.execute(httpGet);
                // 判断返回状态是否为200
                if (response.getStatusLine().getStatusCode() == 200) {
                    resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    if (response != null) {
                        response.close();
                    }
                    httpclient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return resultString;
        }
    
        public static String doGet(String url) {
            return doGet(url, null);
        }
    
        public static String doPost(String url, Map<String, String> param) {
            // 创建Httpclient对象
            CloseableHttpClient httpClient = HttpClients.createDefault();
            CloseableHttpResponse response = null;
            String resultString = "";
            try {
                // 创建Http Post请求
                HttpPost httpPost = new HttpPost(url);
                // 创建参数列表
                if (param != null) {
                    List<NameValuePair> paramList = new ArrayList<>();
                    for (String key : param.keySet()) {
                        paramList.add(new BasicNameValuePair(key, param.get(key)));
                    }
                    // 模拟表单
                    UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList, "utf-8");
                    httpPost.setEntity(entity);
                }
                // 执行http请求
                response = httpClient.execute(httpPost);
                resultString = EntityUtils.toString(response.getEntity(), "utf-8");
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    response.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            return resultString;
        }
    
        public static String doPost(String url) {
            return doPost(url, null);
        }
    
        public static String doPostJson(String url, String json) {
            // 创建Httpclient对象
            CloseableHttpClient httpClient = HttpClients.createDefault();
            CloseableHttpResponse response = null;
            String resultString = "";
            try {
                // 创建Http Post请求
                HttpPost httpPost = new HttpPost(url);
                // 创建请求内容
                StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
                httpPost.setEntity(entity);
                // 执行http请求
                response = httpClient.execute(httpPost);
                resultString = EntityUtils.toString(response.getEntity(), "utf-8");
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    response.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            return resultString;
        }
    }
    
    • 测试工具类:
        /**
         * 测试工具类
         */
        private static void httpClientUtilTest() {
            String url = "http://localhost:8080/test/post/param";
            HashMap<String, String> map = new HashMap<>();
            map.put("name", "李四");
            map.put("pwd", "lisi");
            String result = HttpClientUtil.doPost(url, map);
            System.out.println(result);
        }
    

    3.实战案例:

    3.1需求:

    (1)采用 SOA 架构项目
    (2) 使用 HttpClient 调用服务
    (3) 完成用户的添加与查询

    • 项目架构:


      示例
    • 数据库:
    CREATE TABLE `tb_item` (
      `id` bigint(20) NOT NULL COMMENT '商品id,同时也是商品编号',
      `title` varchar(100) NOT NULL COMMENT '商品标题',
      `sell_point` varchar(500) DEFAULT NULL COMMENT '商品卖点',
      `price` bigint(20) NOT NULL COMMENT '商品价格,单位为:分',
      `num` int(10) NOT NULL COMMENT '库存数量',
      `barcode` varchar(30) DEFAULT NULL COMMENT '商品条形码',
      `image` varchar(500) DEFAULT NULL COMMENT '商品图片',
      `cid` bigint(10) NOT NULL COMMENT '所属类目,叶子类目',
      `status` tinyint(4) NOT NULL DEFAULT '1' COMMENT '商品状态,1-正常,2-下架,3-删除',
      `created` datetime NOT NULL COMMENT '创建时间',
      `updated` datetime NOT NULL COMMENT '更新时间',
      PRIMARY KEY (`id`),
      KEY `cid` (`cid`),
      KEY `status` (`status`),
      KEY `updated` (`updated`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='商品表';
    

    3.2创建commons项目:

    示例
    • 修改POM文件:
        <dependencies>
            <!-- Jackson Json处理工具包 -->
            <dependency>
                <groupId>com.fasterxml.jackson.core</groupId>
                <artifactId>jackson-databind</artifactId>
            </dependency>
            <!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
            <dependency>
                <groupId>org.apache.httpcomponents</groupId>
                <artifactId>httpclient</artifactId>
                <version>4.5.2</version>
            </dependency>
        </dependencies>
    
    3.3创建 service 项目:
    示例
    • 修改POM文件:
        <dependencies>
            <dependency>
                <groupId>com.zlw</groupId>
                <artifactId>13-httpCommens</artifactId>
                <version>0.0.1-SNAPSHOT</version>
            </dependency>
            <dependency>
                <groupId>org.apache.solr</groupId>
                <artifactId>solr-solrj</artifactId>
            </dependency>
            <dependency>
                <groupId>redis.clients</groupId>
                <artifactId>jedis</artifactId>
            </dependency>
            <!-- 单元测试 -->
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
            </dependency>
            <!-- 日志处理 -->
            <dependency>
                <groupId>org.slf4j</groupId>
                <artifactId>slf4j-log4j12</artifactId>
            </dependency>
            <!-- Mybatis -->
            <dependency>
                <groupId>org.mybatis</groupId>
                <artifactId>mybatis</artifactId>
            </dependency>
            <dependency>
                <groupId>org.mybatis</groupId>
                <artifactId>mybatis-spring</artifactId>
            </dependency>
            <!-- MySql -->
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
            </dependency>
            <!-- 连接池 -->
            <dependency>
                <groupId>com.alibaba</groupId>
                <artifactId>druid</artifactId>
            </dependency>
            <!-- Spring -->
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-context</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-beans</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-webmvc</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-jdbc</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-aspects</artifactId>
            </dependency>
            <!-- JSP相关 -->
            <dependency>
                <groupId>jstl</groupId>
                <artifactId>jstl</artifactId>
            </dependency>
            <dependency>
                <groupId>javax.servlet</groupId>
                <artifactId>servlet-api</artifactId>
                <scope>provided</scope>
            </dependency>
            <dependency>
                <groupId>javax.servlet</groupId>
                <artifactId>jsp-api</artifactId>
                <scope>provided</scope>
            </dependency>
            <!-- Jackson Json处理工具包 -->
            <dependency>
                <groupId>com.fasterxml.jackson.core</groupId>
                <artifactId>jackson-databind</artifactId>
            </dependency>
        </dependencies>
    
        <build>
            <resources>
                <resource>
                    <directory>src/main/java</directory>
                    <includes>
                        <include>**/*.xml</include>
                    </includes>
                </resource>
                <resource>
                    <directory>src/main/resources</directory>
                    <includes>
                        <include>**/*.xml</include>
                        <include>**/*.properties</include>
                    </includes>
                </resource>
            </resources>
            <!-- tomcat插件,由于子项目不一定每个都是web项目,所以该插件只是声明,并未开启 -->
            <pluginManagement>
                <plugins>
                    <!-- 配置Tomcat插件 -->
                    <plugin>
                        <groupId>org.apache.tomcat.maven</groupId>
                        <artifactId>tomcat7-maven-plugin</artifactId>
                        <configuration>
                            <path>/</path>
                            <port>8080</port>
                        </configuration>
                    </plugin>
                </plugins>
            </pluginManagement>
        </build>
    
    3.4创建client项目:
    示例
    • 修改POM文件:
        <dependencies>
            <dependency>
                <groupId>com.zlw</groupId>
                <artifactId>13-httpCommens</artifactId>
                <version>0.0.1-SNAPSHOT</version>
            </dependency>
            <dependency>
                <groupId>redis.clients</groupId>
                <artifactId>jedis</artifactId>
            </dependency>
            <!-- 单元测试 -->
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
            </dependency>
            <!-- 日志处理 -->
            <dependency>
                <groupId>org.slf4j</groupId>
                <artifactId>slf4j-log4j12</artifactId>
            </dependency>
            <!-- Spring -->
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-context</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-beans</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-webmvc</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-aspects</artifactId>
            </dependency>
            <!-- JSP相关 -->
            <dependency>
                <groupId>jstl</groupId>
                <artifactId>jstl</artifactId>
            </dependency>
            <dependency>
                <groupId>javax.servlet</groupId>
                <artifactId>servlet-api</artifactId>
                <scope>provided</scope>
            </dependency>
            <dependency>
                <groupId>javax.servlet</groupId>
                <artifactId>jsp-api</artifactId>
                <scope>provided</scope>
            </dependency>
            <!-- Jackson Json处理工具包 -->
            <dependency>
                <groupId>com.fasterxml.jackson.core</groupId>
                <artifactId>jackson-databind</artifactId>
            </dependency>
        </dependencies>
    
        <build>
            <resources>
                <resource>
                    <directory>src/main/java</directory>
                    <includes>
                        <include>**/*.xml</include>
                    </includes>
                </resource>
                <resource>
                    <directory>src/main/resources</directory>
                    <includes>
                        <include>**/*.xml</include>
                        <include>**/*.properties</include>
                    </includes>
                </resource>
            </resources>
            <!-- tomcat插件,由于子项目不一定每个都是web项目,所以该插件只是声明,并未开启 -->
            <pluginManagement>
                <plugins>
                    <!-- 配置Tomcat插件 -->
                    <plugin>
                        <groupId>org.apache.tomcat.maven</groupId>
                        <artifactId>tomcat7-maven-plugin</artifactId>
                        <configuration>
                            <path>/</path>
                            <port>8081</port>
                        </configuration>
                    </plugin>
                </plugins>
            </pluginManagement>
        </build>
    

    4.请求处理的项目:

    • 修改POM文件:
    
        <dependencies>
            <dependency>
                <groupId>com.zlw</groupId>
                <artifactId>13-httpCommens</artifactId>
                <version>0.0.1-SNAPSHOT</version>
            </dependency>
            <dependency>
                <groupId>org.apache.solr</groupId>
                <artifactId>solr-solrj</artifactId>
            </dependency>
            <dependency>
                <groupId>redis.clients</groupId>
                <artifactId>jedis</artifactId>
            </dependency>
            <!-- 单元测试 -->
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
            </dependency>
            <!-- 日志处理 -->
            <dependency>
                <groupId>org.slf4j</groupId>
                <artifactId>slf4j-log4j12</artifactId>
            </dependency>
            <!-- Mybatis -->
            <dependency>
                <groupId>org.mybatis</groupId>
                <artifactId>mybatis</artifactId>
            </dependency>
            <dependency>
                <groupId>org.mybatis</groupId>
                <artifactId>mybatis-spring</artifactId>
            </dependency>
            <!-- MySql -->
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
            </dependency>
            <!-- 连接池 -->
            <dependency>
                <groupId>com.alibaba</groupId>
                <artifactId>druid</artifactId>
            </dependency>
            <!-- Spring -->
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-context</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-beans</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-webmvc</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-jdbc</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-aspects</artifactId>
            </dependency>
            <!-- JSP相关 -->
            <dependency>
                <groupId>jstl</groupId>
                <artifactId>jstl</artifactId>
            </dependency>
            <dependency>
                <groupId>javax.servlet</groupId>
                <artifactId>servlet-api</artifactId>
                <scope>provided</scope>
            </dependency>
            <dependency>
                <groupId>javax.servlet</groupId>
                <artifactId>jsp-api</artifactId>
                <scope>provided</scope>
            </dependency>
            <!-- Jackson Json处理工具包 -->
            <dependency>
                <groupId>com.fasterxml.jackson.core</groupId>
                <artifactId>jackson-databind</artifactId>
            </dependency>
        </dependencies>
    
        <build>
            <resources>
                <resource>
                    <directory>src/main/java</directory>
                    <includes>
                        <include>**/*.xml</include>
                    </includes>
                </resource>
                <resource>
                    <directory>src/main/resources</directory>
                    <includes>
                        <include>**/*.xml</include>
                        <include>**/*.properties</include>
                    </includes>
                </resource>
            </resources>
            <!-- tomcat插件,由于子项目不一定每个都是web项目,所以该插件只是声明,并未开启 -->
            <pluginManagement>
                <plugins>
                    <!-- 配置Tomcat插件 -->
                    <plugin>
                        <groupId>org.apache.tomcat.maven</groupId>
                        <artifactId>tomcat7-maven-plugin</artifactId>
                        <configuration>
                            <path>/</path>
                            <port>8080</port>
                        </configuration>
                    </plugin>
                </plugins>
            </pluginManagement>
        </build>
    
    • mapper:
    <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
            "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    <mapper namespace="com.zlw.mapper.UserMapper">
        <insert id="insertUser" parameterType="com.zlw.pojo.Users">
            insert into users(username,userage) values(#{username},#{userage})
        </insert>
        
        <select id="findAllUser" resultType="com.zlw.pojo.Users">
            select *from users
        </select>
        <select id="findById" resultType="com.zlw.pojo.Users">
            select *from users where userid=#{0}
        </select>
    </mapper>
    
    • service:
    @Service
    public class UserServiceImpl implements UserService {
    
        @Autowired
        private UserMapper userMapper;
    
        @Override
        public void addUser(Users users) {
            userMapper.insertUser(users);
        }
    
        @Override
        public List<Users> findAll() {
            return userMapper.findAllUser();
        }
    }
    
    • Controller:
    @Controller
    @RequestMapping("/user")
    public class UserController {
    
        @Autowired
        private UserService userService;
    
        @RequestMapping("addUser")
        @ResponseBody
        public Object addUser(@RequestBody Users users) {
            HashMap<String, Integer> map = new HashMap<>();
            try {
                this.userService.addUser(users);
                map.put("code", 200);
            } catch (Exception e) {
                e.printStackTrace();
                map.put("code", 500);
            }
            return map;
        }
        
        @RequestMapping("findAll")
        @ResponseBody
        public Object findAll() {
            return this.userService.findAll();
        }
    }
    

    5.实现业务:

    5.1添加用户:
    • JSP页面:
    <body>
        <form action="/user/addUser" method="post">
            <p>
                用户名:<input type="text" name="username" />
            </p>
            <p>
                年龄:<input type="text" name="userage" />
            </p>
            <p>
                <input type="submit" value="添加" />
            </p>
        </form>
        <p>
            <a href="/user/findUser/">查询</a>
        </p>
    </body>
    
    • Controller:
        @Autowired
        private UserService userService;
    
        @RequestMapping("addUser")
        public String addUser(Users user) {
            this.userService.addUser(user);
            return "ok";
        }
    
    • service:
        @Override
        public void addUser(Users users) {
            String json = JsonUtils.objectToJson(users);
            String doPostJson = HttpClientUtil.doPostJson("http://localhost:8080/user/addUser", json);
            Map<String,Integer> map = JsonUtils.jsonToPojo(doPostJson, Map.class);
            Integer integer = map.get("code");
            if (integer == 500) {
                System.out.println("出错了!");
            }else {
                System.out.println("添加成功!");
            }
        }
    
    5.2查询用户:
    • jsp页面:
    <body>
        <table border="1px" align="center" width="400">
            <tr>
                <td>ID</td>
                <td>姓名</td>
                <td>年龄</td>
            </tr>
            <c:forEach items="${list }" var="user">
                <tr>
                    <td>${user.userid }</td>
                    <td>${user.username }</td>
                    <td>${user.userage}</td>
                </tr>
            </c:forEach>
        </table>
    </body>
    
    • Controller:
        @RequestMapping("findUser")
        private String findAll(Model model) {
            List<Users> list = this.userService.findAll();
            model.addAttribute("list",list);
            return "showUser";
        }
    
    • service:
    @Override
        public List<Users> findAll() {
            String doPost = HttpClientUtil.doPost("http://localhost:8080/user/findAll");
            List<Users> list = JsonUtils.jsonToList(doPost, Users.class);
            return list;
        }
    
    5.3实现效果:
    示例
    示例

    相关文章

      网友评论

          本文标题:Java高级技术day84:JsonP和HttpClient

          本文链接:https://www.haomeiwen.com/subject/gkopictx.html