0

我正在编写一个逻辑以在网页中打印检索到的 JSON 数据,为此我有一个控制器类、域类和 hello.jsp 文件。

这是我正在获取并尝试在网页中显示的 JSON 数据

[{"uname":"sam","fileSize":"26 MB","fileName":"Subway_Surfers","downloadSize":1381186649389},
{"uname":"sam","fileSize":"8 MB","fileName":"Grand_Theft_Auto","downloadSize":1381186668752},

但是这个hello.jsp没有被调用,我在这个论坛上发帖。没有得到任何适当的回应。之后我的一位朋友帮助解决了这个问题,因为脚本 url 不正确。

将hello.jsp文件中的脚本 url 修改为<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">它工作正常。

因此,我附上了控制器类、域类和hello.jsp的工作代码,以供在设置简单的 Spring MVC + JSON/REST GET 方法连接时参考。

领域类

    public class OperatorBilling implements Serializable {

    private String uname;

    private String fileSize;

    private String fileName;

    private Timestamp downloadSize;

    public String getUname() {
        return uname;
    }

    public void setUname(String uname) {
        this.uname = uname;
    }

    public String getFileSize() {
        return fileSize;
    }

    public void setFileSize(String fileSize) {
        this.fileSize = fileSize;
    }

    public String getFileName() {
        return fileName;
    }

    public void setFileName(String fileName) {
        this.fileName = fileName;
    }

    public Timestamp getDownloadSize() {
        return downloadSize;
    }

    public void setDownloadSize(Timestamp downloadSize) {
        this.downloadSize = downloadSize;
    }
   }

控制器类

package com.springapp.mvc;

import com.springapp.domain.OperatorBilling;
import org.apache.http.client.ClientProtocolException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

@Controller
public class HelloController {
    @RequestMapping(value="/",method = RequestMethod.GET)

    public String getOperatorBillingDetails(ModelMap model) {
       OperatorBilling operatorBilling  = new OperatorBilling();
       model.addAttribute("operatorBilling",operatorBilling)  ;
       return "hello";
    }

    @RequestMapping(value="/hello",method = RequestMethod.GET, produces="application/json;charset=utf-8")

    public @ResponseBody
    Object getOperatorBillingDetails() {
        List<OperatorBilling> operatorBillingList = new ArrayList<OperatorBilling>();
        try {

            URL url = new URL("http://localhost:8080/operatorBilling");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setRequestProperty("Accept", "application/json");

            if (conn.getResponseCode() != 200) {
                throw new RuntimeException("Failed : HTTP error code : "
                        + conn.getResponseCode());
            }

            BufferedReader br = new BufferedReader(new InputStreamReader(
                    (conn.getInputStream())));

            String output;

            System.out.println("Output from Server .... \n");
            while ((output = br.readLine()) != null) {
                String[] str = output.split("},");
                for(int i =0;i<str.length;i++){
                    String[] str1 = str[i].split(",");

                    OperatorBilling operatorBilling = new OperatorBilling();
                    for(int j =0;j<str1.length;j++){


                        str1[j]= str1[j].replaceAll("\\[\\{","")  ;
                        str1[j]= str1[j].replaceAll("\\}\\]","")  ;
                        str1[j]= str1[j].replaceAll("\"","")  ;
                        str1[j]= str1[j].replaceAll("\\{","")  ;
                        str1[j]= str1[j].replaceAll("\\}","")  ;


                        if(str1[j].contains("uname:")){
                            str1[j] = str1[j].substring(6,str1[j].length());
                            operatorBilling.setUname(str1[j]);

                        }

                        if(str1[j].contains("fileName:")){
                            str1[j] = str1[j].substring(9,str1[j].length());
                            operatorBilling.setFileName(str1[j]);

                        }

                        if(str1[j].contains("fileSize:")){
                            str1[j] = str1[j].substring(9,str1[j].length());
                            operatorBilling.setFileSize(str1[j]);
                        }

                        if(str1[j].contains("downloadTime:")){
                          str1[j] = str1[j].substring(13,str1[j].length());

                          operatorBilling.setDownloadSize(new  Timestamp(Long.valueOf(str1[j])));

                       }

                    }
                    operatorBillingList.add(operatorBilling);
                }

            }
            conn.disconnect();

        } catch (ClientProtocolException e) {

            e.printStackTrace();
        } catch (IOException e) {

            e.printStackTrace();
        }

        return operatorBillingList;

       }

    }

你好.jsp 文件

   <!DOCTYPE html>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page session="false" %>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8" %>

<spring:url scope="page" var="jqueryUrl"
            value="/resources/js/jquery-1.9.1.min.js"/>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>

<html>
<body>
<form:form id="operatorForm" modelAttribute="operatorBilling">
    <h4>test</h4>

    <div id="operatorID"></div>

    <c:url var="findOperatingURL" value="/hello"/>
    <script type="text/javascript">
        $(document).ready(function () {
            $.getJSON('${findOperatingURL}', {
                ajax: 'true'
            }, function (data) {
                alert("inside data!!!!");
                var html = '';
                var len = data.length;
                for (var i = 0; i < len; i++) {
                    html += '<div>' + data[i].uname + '</div><div>' + data[i].fileSize + '</div><div>'+data[i].fileName+'</div>';
                }
                $('#operatorID').html(html);
            });
        });
    </script>

    </div>
</form:form>
</body>
</html>

servlet.xml 文件

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"

             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xmlns:beans="http://www.springframework.org/schema/beans"
             xmlns:context="http://www.springframework.org/schema/context"
             xmlns:tx="http://www.springframework.org/schema/tx" xmlns:mvc="http://www.springframework.org/schema/cache"
             xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd">

    <!-- DispatcherServlet Context: defines this servlet's request-processing
        infrastructure -->

    <!-- Enables the Spring MVC @Controller programming model <mvc:annotation-driven /> -->
    <annotation-driven/>

    <!-- Resolves views selected for rendering by @Controllers to .jsp resources
        in the /WEB-INF/views directory -->
    <beans:bean
            class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <beans:property name="prefix" value="/WEB-INF/pages/"/>
        <beans:property name="suffix" value=".jsp"/>
    </beans:bean>

    <context:component-scan base-package="com.springapp.mvc"/>
</beans:beans>

web.xml 文件

<web-app version="2.4"
    xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 
    http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

    <display-name>Spring MVC Application</display-name>

    <servlet>
        <servlet-name>mvc-dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>mvc-dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>
4

4 回答 4

0

你有没有把杰克逊 JSON 放在你的类路径中使用以下坐标用于 maven 项目

    <!-- Jackson JSON Mapper -->
<dependency>
    <groupId>org.codehaus.jackson</groupId>
    <artifactId>jackson-mapper-asl</artifactId>
    <version>${jackson.version}</version>
</dependency>
于 2013-10-17T14:43:22.567 回答
0

我建议您在 Object getOperatorBillingDetails() 方法中使用 RestTemplate。

添加值属性:

@RequestMapping(method = RequestMethod.GET, produces="application/json;charset=utf-8" value = "/")
于 2013-10-13T20:36:20.103 回答
0

在我提供任何细节之前,请放弃您的解析解决方案并使用适当的 JSON 解析器/生成器。从中选择

还有更多。不要重新发明轮子。请注意,如果换行符出现在其他地方,您的解决方案将失败。


对于真正的交易,您希望看到哪个请求 URL jsp?您的处理程序方法getOperatorBillingDetails映射到 URL 路径/hello并返回一个List<OperatorBilling>. 任何地方都没有引用jsp或视图名称。

看来你混淆了一些概念。

Servlet并且jsp是服务器端组件,javascript而是客户端组件。在您的场景中,您需要两个处理程序方法。用于处理 的 HTTP 请求hello.jsp将生成包含由 that 生成的 HTML 的 HTTP 响应jsp。然后,您需要另一个处理程序方法来处理您在生成的 HTML 中包含的 javascript 脚本中的 AJAX 请求。

于 2013-10-13T21:01:05.310 回答
0

还是行不通 ??不要返回“OperatorBilling”,只需制作其代理对象或 VO 对象然后尝试。

于 2016-03-22T10:06:13.507 回答