启动 Spring 网络应用程序并且无法将 JSP 内容路由到本地主机

Starting a Spring web app and can't get JSP content routed to localhost

我在尝试开始使用 Spring 时遇到了一个可能令人尴尬的问题,下面显示的是我的代码。

HelloController.java

package hello;

import java.util.Date;
import java.util.Map;

import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.View;

@RestController
public class HelloController {

    @RequestMapping("/zz")
    public String index() {
        return "Greetings from Spring Boot!";
    }
    
    @RequestMapping("/")
    public String welcome(Map<String, Object> model) {
     return "welcome";
    }
}

Application.java

@Configuration
@EnableAutoConfiguration
@ComponentScan
public class Application {

 @Bean
    public InternalResourceViewResolver viewResolver() {
        InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
        viewResolver.setViewClass(JstlView.class);
        viewResolver.setPrefix("/WEB-INF/");
        viewResolver.setSuffix(".jsp");
        return viewResolver;
    }
 
 
 
 
    public static void main(String[] args) {
        ApplicationContext ctx = SpringApplication.run(Application.class, args);
        System.out.println("started");
          
    }
}

welcome.jsp

  <html>
  <head>
    <title>Sample Application JSP Page</title>
  </head>

  <body bgcolor=white>

  <table border="0" cellpadding="10">
    <tr>
      <td align=center>
        <img src="images/springsource.png">
      </td>
      <td>
         <h1>Sample Application JSP Page</h1>
      </td>
    </tr>
  </table>

  <br />
  <p>This is the output of a JSP page that is part of the HelloWorld application.</p>

  <%= new String("Hello!") %>

  </body>
</html> 

当我访问 localhost:8080 时,我只看到一个白色屏幕,上面打印着字符串“welcome”。似乎 Spring 无法使用我的映射找到 jsp。

我的welcome.jsp文件在projectroot->WEB-INF->welcome.jsp下。抱歉,如果这可以通过搜索解决,但似乎大多数其他问题都使用 web.xml 来定义到服务器的路由。我不认为这对我来说是真的..但如果有人能证明我错了,我会很高兴。

-----编辑---- 因为 kamoor 一直建议目录结构已关闭。我更新了结构并放置了 jsp,现在它已被正确路由。谢谢!

@RestController更改为@Controller

spring 启动应用程序中的 JSP 需要做很多事情。

首先修改如下代码

@Controller
public class HelloController {

@RequestMapping("/")
public ModelAndView welcome(Map<String, Object> model) {
    return new ModelAndView("welcome");
}
}

接下来,如果您要创建最终可运行对象 "jar",则 Servlet 容器尝试在嵌入式 jar 中查找资源的方式存在限制。请参阅此 documentation 开始。

一个解决方法是将 JSP 文件保存在资源文件夹(例如 public 文件夹)中,并创建一个可运行的 war 工件而不是 jar 工件。

或者您可以创建 jar 文件,但创建目录结构为 META-INF/resources/jsp/

查看示例 project