我有一个Spring Boot项目,使用Jersey作为我的REST服务,并使用AngularJS进行前端开发。当我在不使用任何控制器的情况下运行它并转到index.html(位于 resource / static / index.html中 )时,它工作正常。当我添加一个控制器时,它呈现为字符串“ index.html”作为输出。Spring Boot配置:
import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.ComponentScan; @SpringBootApplication @ComponentScan(basePackages = {"com.cst.interfaces","com.cst.configuration","com.cst.application","com.cst.application.implmentation"}) @EnableAutoConfiguration public class ApplicationConfiguration { public static void main(String args[]) throws Exception{ SpringApplication.run(ApplicationConfiguration.class, args); } public ServletRegistrationBean jerseyServlet(){ ServletRegistrationBean register = new ServletRegistrationBean(new ServletContainer(),"/*"); register.addInitParameter(ServletProperties.JAXRS_APPLICATION_CLASS, JerseyInitalize.class.getName()); return register; } }
JerseyConfiguration:
import org.glassfish.jersey.server.ResourceConfig; import org.springframework.stereotype.Component; @Component public class JerseyInitalize extends ResourceConfig{ public JerseyInitalize(){ super(); this.packages("com.cst.interfaces"); } }
控制器类别:
import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import org.springframework.web.bind.annotation.RestController; @RestController @Path("/home") public class HomeResource { @GET @Produces("application/json") public String getString(){ return "index.html"; } }
这是因为你标注了你的控制器@RestController,这是一个简写为@Controller用@ResponseBody。后一个注释指示控制器将输出原样直接呈现到响应中。
@RestController
@Controller
@ResponseBody
使用@Controller的控制器,是 不是 REST风格代替。