In a Spring MVC application, I'm trying to pass a list to a JSP page and show it on a table, but my index.jsp isn't rendered well and just shows source code on browser.
Here is my controller:
package com.orantaj.controllers;
import com.orantaj.service.EventService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@RestController
public class IndexController {
@Autowired
EventService eventService;
@RequestMapping(value = "/")
public void setEvents(HttpServletRequest request, HttpServletResponse response) {
try {
request.setAttribute("basketballEvents", eventService.getBasketballEvents());
request.getRequestDispatcher("index.jsp").forward(request, response);
} catch (Exception e) {
e.printStackTrace();
}
}
}
And here is JSP:
<%@ page import="com.orantaj.model.BasketballEvent" %>
<%@ page import="java.util.List" %>
<html>
<head>
<title></title>
</head>
<body>
<table>
<tr>
<th>Maç Kodu</th>
<th>Lig</th>
<th>Maç Saati</th>
<th>Takımlar</th>
</tr>
<%List<BasketballEvent> basketballEvents = (List<BasketballEvent>) request.getAttribute("basketballEvents");%>
<%if (basketballEvents != null && basketballEvents.size() > 0) {%>
<%for (BasketballEvent event : basketballEvents) {%>
<tr>
<td><%=event.getMatchCode()%></td>
<td><%=event.getLeague()%></td>
<td><%=event.getMatchDate()%></td>
<td><%=event.getHomeTeam() + " " + event.getAwayTeam()%></td>
</tr>
<%
}
}
%>
</table>
</body>
</html>
What could be wrong?
You have two options to avoid this problem :
See an example here : http://www.breathejava.com/spring-restful-web-service-tutorial-with-json-format-java-configuration/
You may need to annotate your controller class with
@Controller
instead of using the@RestController
annotation which implies that all request handling method assumes the@ResponseBody
semantics, which (from Javadoc):You can check the annotation inernals:
@RestController
@ResponseBody
I have always used the view resolver in spring bean instead of passing jsp name with extension in controller. You need the pass the jsp name without extension in this case just index and the view resolver will resolve it. It works fine. I believe this is the issue.
Also you should use just
@Controller
annotation instead of@RestController
if you dont have specfic requirement