2017-04-25 3 views
1

json 객체를 jsp 페이지에 배열 형식의 javascript 형식으로 보내는 자바 서블릿이 있습니다. [{ "endDate가": : JSON 내 콘솔에서이 같은 것입니다 system.out.print서블릿에서 jScript 배열을 javascript 변수로 가져 오는 중

List<HistoryLeavesScalar> returnedPastInfo = SaveDAO.getPastInformation(username); 
JSONArray jsonArray = new JSONArray(returnedPastInfo); 
String s = jsonArray.toString(); 
System.out.println("\n\n"+"JSON ARRAY is : "+s); 

HttpSession session = request.getSession(true); 
session.setAttribute("jsonArray",jsonArray); 
this.getServletContext().getRequestDispatcher("/calendar.jsp") 
.forward(request, response); 

: 여기

내 서블릿 (그것의 일부)는 "2017년 4월 22일 ","req ":"2017-04-19 ","nr ": 2,"type ":"CO ","startDate ":"2017-04-20 ","Dep ":"2017-04-19 "}, {"endDate ":"2017-04-22 ","req ":"2017-04-20 ","nr ": 3,"type ":"CM ","startDate ":"2017-04 -20 ","Dep ":"2017-04-19 "}]

이 Json Array이 형식의 javascript 태그에서만 볼 수 있습니다. (this is calendar.jsp - 일부입니다.)

<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %> 
    <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> 
    <%@ page import="javax.servlet.jsp.jstl.core.*"%> 
    <%@ page import="javax.servlet.jsp.el.*" %> 
    <%@ taglib prefix="sql" uri="http://java.sun.com/jsp/jstl/sql"%> 
<script type="text/javascript"> 

    var USER_DAYS = [ 
       <c:forEach items="${jsonArray}" var="jsonArray"> 


         { 
          id: '${jsonArray.nr}', 
          date: '${jsonArray.req}', 
          title: '${jsonArray.type}', 
          startDate: '${jsonArray.startDate', 
          endDate: '${jsonArray.endDate', 
          allDay: true, 
          className: 'done' 
         } 
       </c:forEach> 
    ]; 
</script> 

USER_DAYS 변수 (javascript)의 서블릿에서 오는 json 값을 액세스하는 방법을 모르겠습니다. id, date, title, startDate, endDate에 json의 값을 넣는 방법.

jstl이 javascript 태그에서 작동하는지 여부를 모르겠습니다. 나는 그 값을 인쇄하는 방법을 모른다 (그것들은 무엇이든 - 많은 정보를 담을 수있다.).

자바 스크립트 변수를 다음과 같이 변경하면 언급하고 싶습니다. 제대로 작동합니다. 그러나 이것들은 필자가 필기 한 값이지만, 이제 나는 동적으로 그것들을 원합니다 ... 그리고이 정보는 서블릿에서 calendar.jsp로 와야합니다.

var USER_DAYS = [ 
     { 
      id: 1, 
      date: '2017-04-05', 
      title: 'CO', 
      start: new Date(2017, 3, 5), 
      end: new Date(2017, 3, 7), 
      allDay: true, 
      className: 'done' 
     }, 

나를 도와 줄 사람이 있습니까?

+1

그냥 자바 스크립트에서 이것을 시도를 참조하여 JSON 객체를 수정합니다. JSP 태그가 필요하지 않습니다. 직접 js 변수에 모델 속성을 할당 할 수 있습니다. var USER_DAYS = '$ {jsonArray}'; – Prasath

+0

's'을 세션에 저장하고 인쇄하지 않으시겠습니까? 그것은 이미 JSON 객체의 정확한 문자열 표현입니다. 루프를 만들고 깨진 JSON을 쓸 필요가 없습니다. – BackSlash

+0

var USER_DAYS = JSON.parse ('$ {jsonArray}'); ' –

답변

1

당신은 이미 문자열로 그것을 가지고 : 세션 대신 jsonArray에서

String s = jsonArray.toString(); 

스토어 s;

session.setAttribute("jsonArray", s); 

그리고 서블릿에서 인쇄 :

var USER_DAYS = ${jsonArray}; 

MY TEST

(샘플 데이터)

자바 서블릿 :

enter image description here

bingo.jsp :

enter image description here

HTML 결과 :

enter image description here

렌더링 결과 : 그것은 작동

enter image description here

.

+0

이것이 효과가 있습니까? –

+0

@AtaurRahmanMunna 왜 안되나요? – BackSlash

+0

'USER_DAYS'를 json 객체로 취급하기 전에 먼저 파싱해야한다고 생각합니다. 그렇지 않습니까? –

0

당신은 당신은 당신의 jsonStringJSON 자바 스크립트 객체를 분석 할 수있는이

<script> 
    var DAYS = '${jsonArray}'; 
    if(DAYS.length > 0){ 
    var USER_DAYS = { 
      id: DAYS[0].nr, 
      date: DAYS[0].req, 
      title: DAYS[0].type, 
      startDate: new Date(DAYS[0].startDate), 
      endDate: new Date(DAYS[0].endDate), 
      allDay: true, 
      className: 'done' 
     }; 
    } 
</script> 
0

처럼 쓸 수 있습니다. 그런 다음 json 오브젝트의 오브젝트 키 중 일부를 변경하고 추가 키 [e.g "Dep":"2017-04-19"]을 하나 더 삭제 한 다음 최종 json 오브젝트에 값이있는 두 개의 키를 추가하길 원합니다.

allDay: true, 
className: 'done' 

다음은 솔루션 데이터 세트를 json 문자열로 나타낸 것입니다. 당신의 JSP에서

session.setAttribute("jsonArray",jsonArray.toString()); 

var USER_DAYS = JSON.parse('${jsonArray}'); 

USER_DAYS라는 JSON 개체를 만들 것입니다. 그리고 마침내는

var USER_DAYS = JSON.parse('[{"endDate":"2017-04-22","req":"2017-04-19","nr":2,"type":"CO","startDate":"2017-04-20","Dep":"2017-04-19"},{"endDate":"2017-04-22","req":"2017-04-20","nr":3,"type":"CM","startDate":"2017-04-20","Dep":"2017-04-19"}]'); 
 

 
console.log('Original JSON = ' +JSON.stringify(USER_DAYS)); 
 

 
USER_DAYS.forEach(function(e) { 
 
    e.id = e.nr; 
 
    delete e.nr; 
 
    e.date = e.req; 
 
    delete e.req; 
 
    e.title=e.type; 
 
    delete e.type; 
 
    e.allDay= true; 
 
    e.className='done'; 
 
    delete e.Dep; 
 
    
 
}); 
 

 
console.log('Modified JSON = '+JSON.stringify(USER_DAYS));

JSFIDDLE