美文网首页
Intellij Idea下启动内嵌tomcat的spring

Intellij Idea下启动内嵌tomcat的spring

作者: henry技术探索记录员 | 来源:发表于2019-03-12 11:15 被阅读0次

Spring Boot大大提高了web项目的开发。Intellij Idea支持打jar包、war包,然后部署到tomcat或jetty服务器上运行。但在开发环境下,我们希望项目的热部署,即改变代码后,立即在Intellij Idea上更新、运行最新的代码。这样大大提高开发速度。
点击Intellij Idea界面的Run->Edit Configuration, 点击红色的+号,选择Maven:


Maven运行配置1

Name: 自己任意起一个名字
Working directory: 项目的根目录
Command line: spring-boot:run
Profiles: 配置文件可以分开发阶段(develop)和发布阶段(released)
右上角勾选Share或者Single instance only

Maven运行配置2

注意: 一定要用debug启动,但如果项目中有target目录里面打的包,启动可能失败,数据库链接失败,一定要删除target包(或者你自定义的打包的目录及package包)。

启动成功后控制台的信息:

启动成功

发起请求,直接在浏览器上输入:http://localhost:8080可能会是如下的界面,因为服务器没有对应的url请求:

无法映射的请求url

在后端代码的Controller中加一个请求处理,浏览器中输入http:localhost:8080/hello或者http://127.0.0.1:8080/hello,请求成功,并返回正确的数据。

 @RequestMapping(value = "/hello", method = RequestMethod.GET)
    public JSONObject hello(@RequestParam("var")String var) {
        // hello
    }

如果请求有跨域问题,需要加Spring boot的跨域的配置,加一个配置类:

package com.polyzg.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;


@Configuration
public class CorsConfig {
    private CorsConfiguration buildConfig() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.addAllowedOrigin("*"); // 1
        corsConfiguration.addAllowedHeader("*"); // 2
        corsConfiguration.addAllowedMethod("*"); // 3
        return corsConfiguration;
    }

    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", buildConfig()); // 4
        return new CorsFilter(source);
    }
}

至此,可以在本地快速开发和测试后端项目了。

相关文章

网友评论

      本文标题:Intellij Idea下启动内嵌tomcat的spring

      本文链接:https://www.haomeiwen.com/subject/qvpvpqtx.html