Before proceeding I realise that there's a similar question (Passing a List from Servlet to JSP) from a couple of years ago. I realise that it is possible to set the list I'm trying to pass as a session attribute but out of curiosity I wondered if it's possible to use the PrintWriter object to send the data back to the JSP page.
JSP
<script type="text/javascript">
function getEngineSchemes(engineID) {
$.get('SchemeTypeServlet', {
action: "getSchemes",
engineID: engineID
},
function(data, status){
}).fail(function() {
alert("Error obtaining schemes for engine with engine id: " + engineID);
});
}
</script>
</body>
Servlet
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//Set type of response
response.setContentType("text/html");
response.setCharacterEncoding("UTF-8");
//get parameters that may be passed from client to determine which methods should be called
String action = request.getParameter("action");
if(action.equalsIgnoreCase("getSchemesForEngine")) {
Integer engineID = Integer.parseInt(request.getParameter("engineID"));
List<String> schemeNames = getSchemeNamesForEngine(engineID);
response.getWriter(). //insert code to send object back to JSP
response.getWriter().flush();
}
Options
One solution I think may be reasonable would be to create a JSONObject
and have something along the lines of
response.setContentType("application/json");
JSONObject json = new JSONObject();
for(String name : schemeNames) {
json.put(engineID, name);
}
response.getWriter().write(json.toJSONString());
response.getWriter().flush();
I haven't tested the above code but I just want to know if that seems like the best solution to my problem or if I'm making it overly complicated? Maybe there's a far simpler solution to my question.