1

I have a java servlet that sends a json object to a jsp page in a javascript variabile with array format.

Here is my servlet ( a part of it):

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);

that system.out.print JSON is something like this in my console: [{"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"}]

This Json Array I want to be visible in javascript tag like this in that format only: ( this is calendar.jsp - a part of it)

    <%@ 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>

I don't know how to access the values from that json that comes from the servlet in USER_DAYS variable (javascript). How to put the values from json in id, date, title, startDate, endDate.

I don't know if jstl works in a javascript tag. I don't know how to print that values ( whatever they are - it can contain many information, all in that format).

I want to mention that, if I change the javascript variable into somthing like this: it works just fine. But these are values which I have handwritten, but now I want them dynamically...and this information must come from servlet into 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'
      },

Can someone help me?

4
  • 1
    Just try this in javascript . No need any JSP tags. Directly we can assign model attribute into our js variables. var USER_DAYS = '${jsonArray}'; Commented Apr 25, 2017 at 11:48
  • Why don't you just save s in session and print it? It's already a correct string representation of the JSON object, no need to create loops and write broken JSON Commented Apr 25, 2017 at 11:48
  • Try using var USER_DAYS = JSON.parse('${jsonArray}'); Commented Apr 25, 2017 at 11:50
  • Hey, see my answer and let me know if it works. Commented Apr 26, 2017 at 10:29

3 Answers 3

1

You already have it as string:

String s = jsonArray.toString();

Store s in session instead of jsonArray;

session.setAttribute("jsonArray", s); 

And print it in the servlet:

var USER_DAYS = ${jsonArray};

MY TEST

Java servlet (with sample data):

enter image description here

bingo.jsp:

enter image description here

HTML result:

enter image description here

Rendered result:

enter image description here

It works.

Sign up to request clarification or add additional context in comments.

9 Comments

I think before you gonna treat USER_DAYS as a json object, you should parse it first, isn't it?
@AtaurRahmanMunna No, because it won't be a string once printed. It will not be printed as string. It will be printed as var USER_DAYS = {[.....]}
can you give me a fiddle?
@AtaurRahmanMunna No, AFAIK there is no online fiddle tool for Servlets supporting JSTL too. You can try on your own though.
@AtaurRahmanMunna This doesn't have the java part, which is required to show you that parsing isn't needed.
|
0

you can write like this

<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>

Comments

0

You can parse your jsonString to javascript JSON object. Then you want to change some of the object key's of your json object, delete one more extra key [e.g "Dep":"2017-04-19"] and at last want add two key's with values in your final json object.

allDay: true,
className: 'done'

Here is the solution.set data as a json string.

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

In your jsp

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

This will make a JSON object named USER_DAYS. And at last modify your JSON object,

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));

See the JSFIDDLE

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.