我已经开始使用 Spring MVC 和 Spring Boot 创建 hello World Web 应用程序的教程。我无法让应用程序启动 hello.jsp。
这是我的项目配置:
应用类:
@Configuration
@ComponentScan
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
HelloController 类:
@RestController
public class HelloController {
@RequestMapping(value="/greeting",method= RequestMethod.GET)
public String sayHello (Model model){
model.addAttribute("greeting","Hello World!");
return "HELLO!";
}
}
servlet-config.xml 文件:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<mvc:annotation-driven/>
<context:component-scan base-package="trex.controller"/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
<!-- ... -->
</beans>
web.xml 文件:
<?xml version="1.0" encoding="ISO-8859-1"?>
<!--
Add Copyright notice here.
-->
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
version="2.4">
<display-name>SpringWebMVCApp</display-name>
<servlet>
<servlet-name>fitTrackerServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/config/servlet-config.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>fitTrackerServlet</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
</web-app>
hello.jps 文件:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Insert title here</title>
</head>
<body>
<h1>${greeting}</h1>
</body>
</html>
网络结果:
正在获取 sayHello 方法的返回值,而不是 model.addAttribute("greeting","Hello World!")。即使我删除 hello.jsp 文件,我仍然得到相同的结果。
有什么想法为什么不读这个文件吗?是不是不正确?
非常感谢!!!
最佳答案
您正在使用 RestController
,其响应返回类型即“Hello!”...因此您可以使用 @Controller
而不是 @RestController
。
关于java - 使用 Spring Boot 的 Spring MVC WebApp 无法启动 "*.jsp"文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37817173/