控制器寄存器,但在返回数据时得到 404



这是 Spring 的初始值设定项。 我没有使用任何.xml文件。

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
@Configuration
public class WebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
    @Override
    protected Class<?>[] getRootConfigClasses() {
        return new Class<?>[]{
                WebAppConfig.class,
                SecurityConfig.class,
                DatabaseConfig.class,
                DataSourceGenerator.class,
                QuartzConfig.class,
                QueueConfig.class
        };
    }
    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        super.onStartup(servletContext);
        servletContext.addFilter(
                "facilityFilter", new FacilityServletFilter()
        ).addMappingForUrlPatterns(null, false, "/api/*");
        servletContext.addFilter(
                "hmacFilter", new HmacFilter()
        ).addMappingForUrlPatterns(null, false, "/api/*");
    }
    @Override
    protected String[] getServletMappings() {
        return new String[]{"/"};
    }
    @Override
    protected Class<?>[] getServletConfigClasses() {
        return null;
    }
}

这是我的控制器之一。

@Controller
@RequestMapping(value = "/install")
public class HelloController {
    @RequestMapping(value = "/hi", method = RequestMethod.GET,
            consumes = "*/*", produces = "text/html")
    public String sayHello(){
        return "<html> <head> <title>API</title>" +
                "</head>        <body>        <h1>Welcome to the Eric</h1>" +
                "</body>        </html>";
    }
}

我的所有其他控制器似乎都可以正常工作,但是当我尝试命中端点时,这个控制器会返回 404 错误。 当我通过邮递员调用代码时,代码在调试器中命中。

@ResponseBody添加到控制器方法中,否则 spring 将尝试搜索名为 "<html> <head> <title>API</title>..." 的视图

@Controller
@RequestMapping(value = "/install")
public class HelloController {
    @RequestMapping(value = "/hi", method = RequestMethod.GET, consumes = "*/*", produces = "text/html")
    @ResponseBody
    public String sayHello(){
        return "<html> <head> <title>API</title>" +
                "</head>        <body>        <h1>Welcome to the Eric</h1>" +
                "</body>        </html>";
    }
}

正如 Raplh 所建议的那样,您可以这样做,但如果您打算使用更多这些方法,不妨将@Controller替换为@RestController

最新更新