index.jsp 不工作,只在浏览器上显示源代码

index.jsp not working, just shows source code on browser

在 Spring MVC 应用程序中,我试图将列表传递到 JSP 页面并在 table 上显示它,但是我的 index.jsp 渲染不佳,仅在浏览器上显示源代码。

这是我的控制器:

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

这里是 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>

有什么问题吗?

我一直在 spring bean 中使用视图解析器,而不是在控制器中传递带有扩展名的 jsp 名称。您需要传递不带扩展名的 jsp 名称,在这种情况下只需索引,视图解析器将解析它。它工作正常。我相信这就是问题所在。

     <bean id="viewResolver"
           class="org.springframework.web.servlet.view.InternalResourceViewResolver" >
           <property name="prefix">
              <value>/WEB-INF/pages/</value>
           </property>
           <property name="suffix">
              <value>.jsp</value>
           </property>
     </bean>

</beans>

此外,如果您没有特定要求,您应该只使用 @Controller 注释而不是 @RestController

你可能需要用 @Controller 注释你的控制器 class 而不是使用 @RestController 注释,这意味着所有请求处理方法都采用 @ResponseBody 语义,这(来自 Javadoc):

indicates a method return value should be bound to the web response body.

您可以查看注释内部:

您有两种选择可以避免此问题:

  • 您必须使用@Controller 而不是@Restcontroller 并添加bean InternalResourceViewResolver 如上所述来定义页面的后缀和前缀。

请在此处查看示例:http://www.breathejava.com/spring-restful-web-service-tutorial-with-json-format-java-configuration/

  • 或者,在客户端开发一个 ajax 请求来使用您的默认网络服务。我更喜欢你使用 AngularJS 框架。