首页 > 解决方案 > 如何在tomcat上启动rest-spring应用程序?

问题描述

我尝试在 spring 上使用 rest-controllers 创建应用程序。项目结构为 在此处输入图像描述

应用上下文.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:util="http://www.springframework.org/schema/util"
       xsi:schemaLocation="
               http://www.springframework.org/schema/beans 
               http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
               http://www.springframework.org/schema/util
               http://www.springframework.org/schema/util/spring-util.xsd
               http://www.springframework.org/schema/context
               http://www.springframework.org/schema/context/spring-context-3.2.xsd
       ">

    <context:annotation-config/>
</beans>

web.xml 是

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
         http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:WEB-INF/applicationContext.xml</param-value>
    </context-param>

    <session-config>
        <session-timeout>30</session-timeout>
    </session-config>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <listener>
        <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
    </listener>
</web-app>

RestController 是

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class TestController {
    @RequestMapping(value="/test", method= RequestMethod.GET)
    public void getTest(){
        int i = 1;
    }
}

所以,我将此应用程序部署在 apache-tomcat-8.5.29 上,但是尝试调用 rest 时出现 404 错误。

我尝试的网址是 localhost:8080/test 和 localhost:8080/appName/test

你有什么想法吗?

标签: javaspring

解决方案


首先您应该使用不需要外部应用程序或Web服务器的springboot,而不是裸spring应用程序,成功运行您的springboot应用程序后,您可以搜索如何将springboot应用程序转换为能够在tomcat上运行。

这里有一些链接:

https://spring.io/guides/gs/rest-service/

https://www.mkyong.com/spring-boot/spring-boot-deploy-war-file-to-tomcat/


推荐阅读