Spring:无法访问控制器,出现404未找到错误。

huangapple go评论73阅读模式
英文:

Spring: can't access controller 404 not found error

问题

我正尝试访问 http://localhost:8088/test_war_exploded/home/hello,但是出现了 404 错误。我无法弄清楚为什么会出现这个错误。

目录结构:

root
  src
    main
      java
         test
           config
              DbConfig.java
              MyAppInitializer.java
              WebConfig.java
          HomeController.java

WebConfig.java:

@Configuration
@ComponentScan("test")
@EnableWebMvc
@EnableTransactionManagement
@EnableGlobalMethodSecurity(prePostEnabled = true)
@EnableJpaRepositories(basePackages = "test",
        entityManagerFactoryRef = "entityManagerFactory",
        transactionManagerRef = "transactionManager")
 public class WebConfig extends WebMvcConfigurerAdapter {
    @Override
    public void configureDefaultServletHandling(
                DefaultServletHandlerConfigurer configurer) {
        configurer.enable();
    }

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("index");
    }

    @Bean
    public ViewResolver viewResolver() {
        InternalResourceViewResolver bean = new InternalResourceViewResolver();

        bean.setViewClass(JstlView.class);
        bean.setPrefix("/WEB-INF/view/");
        bean.setSuffix(".html");

        return bean;
    }
}

MyAppInitializer.java:

public class MyAppInitializer extends
                AbstractAnnotationConfigDispatcherServletInitializer {
    @Override
    public void onStartup(final ServletContext sc) throws ServletException {
        System.out.println("onStartup!");

        AnnotationConfigWebApplicationContext root =
                new AnnotationConfigWebApplicationContext();

        root.register(WebConfig.class);
        root.setServletContext(sc);

        root.scan("test");
        //sc.addListener(new ContextLoaderListener(root));

        ServletRegistration.Dynamic appServlet =
                sc.addServlet("dispatcher", new DispatcherServlet(new GenericWebApplicationContext()));
        appServlet.setLoadOnStartup(1);
        appServlet.addMapping("/");
    }

    @Override
    protected Class<?>[] getRootConfigClasses() {
        return new Class[] {SecurityConfig.class};
    }

    @Override
    protected Class<?>[] getServletConfigClasses() {
        return new Class[]{WebConfig.class};
    }

    @Override
    protected String[] getServletMappings() {
        return new String[]{"/"};
    }
}

HomeController.java:

@RestController
@RequestMapping("/home")
public class HomeController {

    @GetMapping(value = "/hello")
    public String hello() {
        return "Hello";
    }
}

该应用在服务器/IDE日志中没有错误进行部署。在部署过程中,在控制台中会打印出 onStartup,这意味着 MyAppInitializer 中的代码被执行。

英文:

I'm trying to access a http://localhost:8088/test_war_exploded/home/hello but get 404 error. I can't figure out why.

Directory structure:

root
  src
    main
      java
         test
           config
              DbConfig.java
              MyAppInitializer.java
              WebConfig.java
          HomeController.java

WebConfig.java:


@Configuration
@ComponentScan(&quot;test&quot;)
@EnableWebMvc
@EnableTransactionManagement
@EnableGlobalMethodSecurity(prePostEnabled = true)
@EnableJpaRepositories(basePackages = &quot;test&quot;,
        entityManagerFactoryRef = &quot;entityManagerFactory&quot;,
        transactionManagerRef = &quot;transactionManager&quot;)
 public class WebConfig extends WebMvcConfigurerAdapter {
    @Override
    public void configureDefaultServletHandling(
                DefaultServletHandlerConfigurer configurer) {
        configurer.enable();
    }

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController(&quot;/&quot;).setViewName(&quot;index&quot;);
    }

    @Bean
    public ViewResolver viewResolver() {
        InternalResourceViewResolver bean = new InternalResourceViewResolver();

        bean.setViewClass(JstlView.class);
        bean.setPrefix(&quot;/WEB-INF/view/&quot;);
bean.setSuffix(&quot;.html&quot;);


        return bean;
    }
}

MyAppInitializer.java:

public class MyAppInitializer extends
                AbstractAnnotationConfigDispatcherServletInitializer {
    @Override
    public void onStartup(final ServletContext sc) throws ServletException {
        System.out.println(&quot;onStartup!&quot;);

        AnnotationConfigWebApplicationContext root =
                new AnnotationConfigWebApplicationContext();

        root.register(WebConfig.class);
        root.setServletContext(sc);

        root.scan(&quot;test&quot;);
        //sc.addListener(new ContextLoaderListener(root));

        ServletRegistration.Dynamic appServlet =
                sc.addServlet(&quot;dispatcher&quot;, new DispatcherServlet(new GenericWebApplicationContext()));
        appServlet.setLoadOnStartup(1);
        appServlet.addMapping(&quot;/&quot;);
    }

        @Override
    protected Class&lt;?&gt;[] getRootConfigClasses() {
        return new Class[] {SecurityConfig.class};
    }

    @Override
    protected Class&lt;?&gt;[] getServletConfigClasses() {
        return new Class[]{WebConfig.class};
    }

    @Override
    protected String[] getServletMappings() {
        return new String[]{&quot;/&quot;};
    }
}

HomeController.java:

@RestController
@RequestMapping(&quot;/home&quot;)
public class HomeController {

    @GetMapping(value = &quot;/hello&quot;)
    public String hello() {
        return &quot;Hello&quot;;
    }
}

The app gets deployed with no errors in server / IDE log. During deployment onStartup gets printed in console, meaning the code in MyAppInitializer gets executed.

答案1

得分: 1

HomeController为/home提供了映射。
要访问上述端点,您可以将第一部分添加到RequestMapping注释中,如下所示:@RequestMapping("test_war_exploded/home")

并且您尝试通过端口8088进行访问。默认端口为8080,除非在application.properties中进行了设置。

英文:

The HomeController provides a mapping for /home.
For accessing the mentioned endpoint you could add the first part to the RequestMapping Annotation as such: @RequestMapping("test_war_exploded/home")

And you try to access via port 8088. The default port is 8080, if not set in the application.properties otherwise.

答案2

得分: -1

HomeController bean未定义且未初始化。

@Component
@RestController
@RequestMapping("/home")
public class HomeController {

    @GetMapping(value = "/hello")
    public String hello() {
        return "你好";
    }
}
英文:

HomeController bean is not defined and not initialized.

@Component
@RestController
@RequestMapping(&quot;/home&quot;)
public class HomeController {

    @GetMapping(value = &quot;/hello&quot;)
    public String hello() {
        return &quot;Hello&quot;;
    }
}

答案3

得分: -1

我解决了。问题是我没有初始化类。我添加了两个类:SecurityConfigSecurityWebApplicationInitializer

SecurityConfig.java

@Configuration
@EnableGlobalMethodSecurity(prePostEnabled=true)
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter  {
    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        httpSecurity.authorizeRequests().antMatchers("/").permitAll();
    }

    @Bean
    BCryptPasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}

SecurityWebApplicationInitializer.java

public class SecurityWebApplicationInitializer extends AbstractSecurityWebApplicationInitializer {
    public SecurityWebApplicationInitializer() {
        super(SecurityConfig.class, WebConfig.class);
    }
}

现在我的项目看起来是这样的:

Spring:无法访问控制器,出现404未找到错误。
Main.java 仅用于 maven-shade-plugin,不用在意它,它只包含一个空的 main 方法:

Main.java

public class Main {
    public static void main(String[] args) {

    }
}

我的其他类(已更新)。出于简化考虑,我移除了数据库配置类。如果你不需要数据库,只需从这个回答中复制粘贴类,应该可以正常工作:

MyAppInitializer.java

public class MyAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
    @Override
    public void onStartup(final ServletContext sc) throws ServletException {
        System.out.println("onStartup!");

        AnnotationConfigWebApplicationContext root = new AnnotationConfigWebApplicationContext();

        root.register(WebConfig.class);
        root.setServletContext(sc);

        root.scan("test");
        //sc.addListener(new ContextLoaderListener(root));

        ServletRegistration.Dynamic appServlet =
                sc.addServlet("dispatcher", new DispatcherServlet(new GenericWebApplicationContext()));
        appServlet.setLoadOnStartup(1);
        appServlet.addMapping("/");
    }

    @Override
    protected Class<?>[] getRootConfigClasses() {
        return new Class[] {SecurityConfig.class};
    }

    @Override
    protected Class<?>[] getServletConfigClasses() {
        return new Class[]{WebConfig.class};
    }

    @Override
    protected String[] getServletMappings() {
        return new String[]{"/"};
    }
}

WebConfig.java

@Configuration
@ComponentScan("test")
@EnableWebMvc
@EnableTransactionManagement
@EnableGlobalMethodSecurity(prePostEnabled = true)
@EnableJpaRepositories(basePackages = "test",
        entityManagerFactoryRef = "entityManagerFactory", transactionManagerRef = "transactionManager")
public class WebConfig extends WebMvcConfigurerAdapter {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**");
    }

    @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
        configurer.enable();
    }
}

HomeController.java

@RestController
public class HomeController {
    @GetMapping("/")
    public String getHome()  {
        return "home";
    }
}

TestController.java

@RestController
public class TestController {
    @RequestMapping("/test")
    public String test()  {
        return "test";
    }
}

我从配置类中移除了视图解析器,因为我只打算使用 rest controller 作为 API 提供者。感谢收听我的 TED 演讲。

PS 这是我的 pom.xml 如何配置的(因为使用不同的 poms,Intellij 不会自动生成 war-exploded 构件):

(你的 pom.xml 部分被截断,我无法提供完整的翻译。)

英文:

I figured it out. The problem was that I didn't have an initializer class. I added two classes: SecurityConfig and SecurityWebApplicationInitializer:

SecurityConfig.java:

@Configuration
@EnableGlobalMethodSecurity(prePostEnabled=true)
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter  {
    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        httpSecurity.authorizeRequests().antMatchers(&quot;/&quot;).permitAll();
    }

    @Bean
    BCryptPasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}

SecurityWebApplicationInitializer.java:

public class SecurityWebApplicationInitializer extends
                    AbstractSecurityWebApplicationInitializer {
    public SecurityWebApplicationInitializer() {
        super(SecurityConfig.class, WebConfig.class);
    }
}

This is how my project looks now:

Spring:无法访问控制器,出现404未找到错误。
Main.java is just for the maven-shade-plugin, never mind it, it only contains the empty main method:

Main.java:

public class Main {
    public static void main(String[] args) {

    }
}

My other classes (updated). I removed database config class for simplicity. If you don't need a database, you can just copypaste classes from this answer and it should work fine:

MyAppInitializer.java:

public class MyAppInitializer extends
                AbstractAnnotationConfigDispatcherServletInitializer {
    @Override
    public void onStartup(final ServletContext sc) throws ServletException {
        System.out.println(&quot;onStartup!&quot;);

        AnnotationConfigWebApplicationContext root =
                new AnnotationConfigWebApplicationContext();

        root.register(WebConfig.class);
        root.setServletContext(sc);

        root.scan(&quot;test&quot;);
        //sc.addListener(new ContextLoaderListener(root));

        ServletRegistration.Dynamic appServlet =
                sc.addServlet(&quot;dispatcher&quot;, new DispatcherServlet(new GenericWebApplicationContext()));
        appServlet.setLoadOnStartup(1);
        appServlet.addMapping(&quot;/&quot;);
    }

        @Override
    protected Class&lt;?&gt;[] getRootConfigClasses() {
        return new Class[] {SecurityConfig.class};
    }

    @Override
    protected Class&lt;?&gt;[] getServletConfigClasses() {
        return new Class[]{WebConfig.class};
    }

    @Override
    protected String[] getServletMappings() {
        return new String[]{&quot;/&quot;};
    }
}

WebConfig.java:

@Configuration
@ComponentScan(&quot;test&quot;)
@EnableWebMvc
@EnableTransactionManagement
@EnableGlobalMethodSecurity(prePostEnabled = true)
@EnableJpaRepositories(basePackages = &quot;test&quot;,
        entityManagerFactoryRef = &quot;entityManagerFactory&quot;, transactionManagerRef = &quot;transactionManager&quot;)
 public class WebConfig extends WebMvcConfigurerAdapter {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping(&quot;/**&quot;);
    }


    @Override
    public void configureDefaultServletHandling(
                DefaultServletHandlerConfigurer configurer) {
        configurer.enable();
    }
}

HomeController.java:

@RestController
public class HomeController {
    @GetMapping(&quot;/&quot;)
    public String getHome()  {
        return &quot;home&quot;;
    }
}

TestController.java:

@RestController
public class TestController {
    @RequestMapping(&quot;/test&quot;)
    public String test()  {
        return &quot;test&quot;;
    }
}

I removed view resolvers from config classes, because I intend to only use rest controllers as an API provider. Thanks for coming to my TED talk.

PS Here's how the pom.xml looks (it seems to be important because with different poms Intellij doesn't auto generate war-exploded artifact):

&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;project xmlns=&quot;http://maven.apache.org/POM/4.0.0&quot;
xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
xsi:schemaLocation=&quot;http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd&quot;&gt;
&lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt;
&lt;groupId&gt;org.example&lt;/groupId&gt;
&lt;artifactId&gt;bigpuzzle&lt;/artifactId&gt;
&lt;version&gt;1.0-SNAPSHOT&lt;/version&gt;
&lt;packaging&gt;war&lt;/packaging&gt;
&lt;pluginRepositories&gt;
&lt;pluginRepository&gt;
&lt;id&gt;pcentral&lt;/id&gt;
&lt;name&gt;pcentral&lt;/name&gt;
&lt;url&gt;https://repo1.maven.org/maven2&lt;/url&gt;
&lt;/pluginRepository&gt;
&lt;pluginRepository&gt;
&lt;id&gt;central&lt;/id&gt;
&lt;name&gt;Central Repository&lt;/name&gt;
&lt;url&gt;https://repo.maven.apache.org/maven2&lt;/url&gt;
&lt;layout&gt;default&lt;/layout&gt;
&lt;snapshots&gt;
&lt;enabled&gt;false&lt;/enabled&gt;
&lt;/snapshots&gt;
&lt;/pluginRepository&gt;
&lt;/pluginRepositories&gt;
&lt;repositories&gt;
&lt;repository&gt;
&lt;id&gt;jcenter&lt;/id&gt;
&lt;name&gt;jcenter-bintray&lt;/name&gt;
&lt;url&gt;https://jcenter.bintray.com&lt;/url&gt;
&lt;/repository&gt;
&lt;/repositories&gt;
&lt;dependencies&gt;
&lt;!-- Jackson to convert Java object to Json --&gt;
&lt;dependency&gt;
&lt;groupId&gt;com.fasterxml.jackson.core&lt;/groupId&gt;
&lt;artifactId&gt;jackson-databind&lt;/artifactId&gt;
&lt;version&gt;2.9.4&lt;/version&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
&lt;groupId&gt;com.fasterxml.jackson.core&lt;/groupId&gt;
&lt;artifactId&gt;jackson-annotations&lt;/artifactId&gt;
&lt;version&gt;2.9.4&lt;/version&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
&lt;groupId&gt;net.sourceforge&lt;/groupId&gt;
&lt;artifactId&gt;jwbf&lt;/artifactId&gt;
&lt;version&gt;3.1.1&lt;/version&gt;
&lt;/dependency&gt;
&lt;!-- https://mvnrepository.com/artifact/com.google.code.gson/gson --&gt;
&lt;dependency&gt;
&lt;groupId&gt;com.google.code.gson&lt;/groupId&gt;
&lt;artifactId&gt;gson&lt;/artifactId&gt;
&lt;version&gt;2.8.6&lt;/version&gt;
&lt;/dependency&gt;
&lt;!-- https://mvnrepository.com/artifact/org.springframework.security/spring-security-core --&gt;
&lt;dependency&gt;
&lt;groupId&gt;org.springframework.security&lt;/groupId&gt;
&lt;artifactId&gt;spring-security-core&lt;/artifactId&gt;
&lt;version&gt;5.3.1.RELEASE&lt;/version&gt;
&lt;/dependency&gt;
&lt;!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc --&gt;
&lt;dependency&gt;
&lt;groupId&gt;org.springframework&lt;/groupId&gt;
&lt;artifactId&gt;spring-webmvc&lt;/artifactId&gt;
&lt;version&gt;5.2.5.RELEASE&lt;/version&gt;
&lt;/dependency&gt;
&lt;!-- https://mvnrepository.com/artifact/org.springframework/spring-web --&gt;
&lt;dependency&gt;
&lt;groupId&gt;org.springframework&lt;/groupId&gt;
&lt;artifactId&gt;spring-web&lt;/artifactId&gt;
&lt;version&gt;5.2.5.RELEASE&lt;/version&gt;
&lt;/dependency&gt;
&lt;!-- https://mvnrepository.com/artifact/org.springframework.security/spring-security-core --&gt;
&lt;dependency&gt;
&lt;groupId&gt;org.springframework.security&lt;/groupId&gt;
&lt;artifactId&gt;spring-security-core&lt;/artifactId&gt;
&lt;version&gt;5.3.1.RELEASE&lt;/version&gt;
&lt;/dependency&gt;
&lt;!-- https://mvnrepository.com/artifact/org.springframework.security/spring-security-config --&gt;
&lt;dependency&gt;
&lt;groupId&gt;org.springframework.security&lt;/groupId&gt;
&lt;artifactId&gt;spring-security-config&lt;/artifactId&gt;
&lt;version&gt;5.3.1.RELEASE&lt;/version&gt;
&lt;/dependency&gt;
&lt;!-- https://mvnrepository.com/artifact/org.springframework.security/spring-security-web --&gt;
&lt;dependency&gt;
&lt;groupId&gt;org.springframework.security&lt;/groupId&gt;
&lt;artifactId&gt;spring-security-web&lt;/artifactId&gt;
&lt;version&gt;5.3.1.RELEASE&lt;/version&gt;
&lt;/dependency&gt;
&lt;!-- https://mvnrepository.com/artifact/org.springframework.data/spring-data-jpa --&gt;
&lt;dependency&gt;
&lt;groupId&gt;org.springframework.data&lt;/groupId&gt;
&lt;artifactId&gt;spring-data-jpa&lt;/artifactId&gt;
&lt;version&gt;2.2.6.RELEASE&lt;/version&gt;
&lt;/dependency&gt;
&lt;!-- https://mvnrepository.com/artifact/org.springframework/spring-core --&gt;
&lt;dependency&gt;
&lt;groupId&gt;org.springframework&lt;/groupId&gt;
&lt;artifactId&gt;spring-core&lt;/artifactId&gt;
&lt;version&gt;5.2.5.RELEASE&lt;/version&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
&lt;groupId&gt;org.thymeleaf&lt;/groupId&gt;
&lt;artifactId&gt;thymeleaf&lt;/artifactId&gt;
&lt;version&gt;3.0.7.RELEASE&lt;/version&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
&lt;groupId&gt;org.thymeleaf&lt;/groupId&gt;
&lt;artifactId&gt;thymeleaf-spring4&lt;/artifactId&gt;
&lt;version&gt;3.0.7.RELEASE&lt;/version&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
&lt;groupId&gt;org.apache.opennlp&lt;/groupId&gt;
&lt;artifactId&gt;opennlp-tools&lt;/artifactId&gt;
&lt;version&gt;1.9.1&lt;/version&gt;
&lt;/dependency&gt;
&lt;!-- https://mvnrepository.com/artifact/net.dv8tion/JDA --&gt;
&lt;dependency&gt;
&lt;groupId&gt;net.dv8tion&lt;/groupId&gt;
&lt;artifactId&gt;JDA&lt;/artifactId&gt;
&lt;version&gt;4.0.0_46&lt;/version&gt;
&lt;/dependency&gt;
&lt;!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core --&gt;
&lt;dependency&gt;
&lt;groupId&gt;org.hibernate&lt;/groupId&gt;
&lt;artifactId&gt;hibernate-core&lt;/artifactId&gt;
&lt;version&gt;5.4.4.Final&lt;/version&gt;
&lt;/dependency&gt;
&lt;!-- https://mvnrepository.com/artifact/com.h2database/h2 --&gt;
&lt;dependency&gt;
&lt;groupId&gt;com.h2database&lt;/groupId&gt;
&lt;artifactId&gt;h2&lt;/artifactId&gt;
&lt;version&gt;1.4.197&lt;/version&gt;
&lt;scope&gt;test&lt;/scope&gt;
&lt;/dependency&gt;
&lt;!-- https://mvnrepository.com/artifact/org.springframework/spring-orm --&gt;
&lt;dependency&gt;
&lt;groupId&gt;org.springframework&lt;/groupId&gt;
&lt;artifactId&gt;spring-orm&lt;/artifactId&gt;
&lt;version&gt;5.2.5.RELEASE&lt;/version&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
&lt;groupId&gt;org.postgresql&lt;/groupId&gt;
&lt;artifactId&gt;postgresql&lt;/artifactId&gt;
&lt;version&gt;9.4-1203-jdbc4&lt;/version&gt;
&lt;/dependency&gt;
&lt;!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api --&gt;
&lt;dependency&gt;
&lt;groupId&gt;javax.servlet&lt;/groupId&gt;
&lt;artifactId&gt;javax.servlet-api&lt;/artifactId&gt;
&lt;version&gt;4.0.1&lt;/version&gt;
&lt;scope&gt;provided&lt;/scope&gt;
&lt;/dependency&gt;
&lt;!-- https://mvnrepository.com/artifact/org.springframework.security.oauth/spring-security-oauth2 --&gt;
&lt;dependency&gt;
&lt;groupId&gt;org.springframework.security.oauth&lt;/groupId&gt;
&lt;artifactId&gt;spring-security-oauth2&lt;/artifactId&gt;
&lt;version&gt;2.4.1.RELEASE&lt;/version&gt;
&lt;/dependency&gt;
&lt;!--is needed for jwt--&gt;
&lt;!-- https://mvnrepository.com/artifact/javax.xml/jaxb-api --&gt;
&lt;dependency&gt;
&lt;groupId&gt;javax.xml&lt;/groupId&gt;
&lt;artifactId&gt;jaxb-api&lt;/artifactId&gt;
&lt;version&gt;2.1&lt;/version&gt;
&lt;/dependency&gt;
&lt;!-- https://mvnrepository.com/artifact/com.sun.xml.bind/jaxb-impl --&gt;
&lt;dependency&gt;
&lt;groupId&gt;com.sun.xml.bind&lt;/groupId&gt;
&lt;artifactId&gt;jaxb-impl&lt;/artifactId&gt;
&lt;version&gt;3.0.0-M4&lt;/version&gt;
&lt;/dependency&gt;
&lt;!-- https://mvnrepository.com/artifact/com.sun.xml.bind/jaxb-core --&gt;
&lt;dependency&gt;
&lt;groupId&gt;com.sun.xml.bind&lt;/groupId&gt;
&lt;artifactId&gt;jaxb-core&lt;/artifactId&gt;
&lt;version&gt;3.0.0-M4&lt;/version&gt;
&lt;/dependency&gt;
&lt;!-- https://mvnrepository.com/artifact/org.springframework.security/spring-security-jwt --&gt;
&lt;dependency&gt;
&lt;groupId&gt;org.springframework.security&lt;/groupId&gt;
&lt;artifactId&gt;spring-security-jwt&lt;/artifactId&gt;
&lt;version&gt;1.1.0.RELEASE&lt;/version&gt;
&lt;/dependency&gt;
&lt;!-- https://mvnrepository.com/artifact/io.jsonwebtoken/jjwt --&gt;
&lt;dependency&gt;
&lt;groupId&gt;io.jsonwebtoken&lt;/groupId&gt;
&lt;artifactId&gt;jjwt&lt;/artifactId&gt;
&lt;version&gt;0.9.1&lt;/version&gt;
&lt;/dependency&gt;
&lt;!-- https://mvnrepository.com/artifact/com.jakewharton.fliptables/fliptables --&gt;
&lt;dependency&gt;
&lt;groupId&gt;com.jakewharton.fliptables&lt;/groupId&gt;
&lt;artifactId&gt;fliptables&lt;/artifactId&gt;
&lt;version&gt;1.0.2&lt;/version&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
&lt;groupId&gt;com.squareup.okhttp3&lt;/groupId&gt;
&lt;artifactId&gt;okhttp&lt;/artifactId&gt;
&lt;version&gt;3.4.2&lt;/version&gt;
&lt;/dependency&gt;
&lt;!-- https://mvnrepository.com/artifact/org.json/json --&gt;
&lt;dependency&gt;
&lt;groupId&gt;org.json&lt;/groupId&gt;
&lt;artifactId&gt;json&lt;/artifactId&gt;
&lt;version&gt;20190722&lt;/version&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
&lt;groupId&gt;javax.servlet&lt;/groupId&gt;
&lt;artifactId&gt;jstl&lt;/artifactId&gt;
&lt;version&gt;1.2&lt;/version&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
&lt;groupId&gt;com.fasterxml.jackson.core&lt;/groupId&gt;
&lt;artifactId&gt;jackson-databind&lt;/artifactId&gt;
&lt;version&gt;2.9.8&lt;/version&gt;
&lt;/dependency&gt;
&lt;!-- https://mvnrepository.com/artifact/commons-codec/commons-codec --&gt;
&lt;dependency&gt;
&lt;groupId&gt;commons-codec&lt;/groupId&gt;
&lt;artifactId&gt;commons-codec&lt;/artifactId&gt;
&lt;version&gt;1.14&lt;/version&gt;
&lt;/dependency&gt;
&lt;!-- https://mvnrepository.com/artifact/javax.xml.bind/jaxb-api --&gt;
&lt;dependency&gt;
&lt;groupId&gt;javax.xml.bind&lt;/groupId&gt;
&lt;artifactId&gt;jaxb-api&lt;/artifactId&gt;
&lt;version&gt;2.3.1&lt;/version&gt;
&lt;/dependency&gt;
&lt;/dependencies&gt;
&lt;build&gt;
&lt;finalName&gt;bigpuzzle&lt;/finalName&gt;
&lt;plugins&gt;
&lt;plugin&gt;
&lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;
&lt;artifactId&gt;maven-shade-plugin&lt;/artifactId&gt;
&lt;version&gt;3.0.0&lt;/version&gt;
&lt;executions&gt;
&lt;execution&gt;
&lt;phase&gt;package&lt;/phase&gt;
&lt;goals&gt;
&lt;goal&gt;shade&lt;/goal&gt;
&lt;/goals&gt;
&lt;configuration&gt;
&lt;shadedArtifactAttached&gt;true&lt;/shadedArtifactAttached&gt;
&lt;transformers&gt;
&lt;transformer
implementation=&quot;org.apache.maven.plugins.shade.resource.ManifestResourceTransformer&quot;&gt;
&lt;mainClass&gt;bigpuzzle.Main&lt;/mainClass&gt;
&lt;manifestEntries&gt;
&lt;Main-Class&gt;bigpuzzle.Main&lt;/Main-Class&gt;
&lt;/manifestEntries&gt;
&lt;/transformer&gt;
&lt;/transformers&gt;
&lt;filters&gt;
&lt;filter&gt;
&lt;artifact&gt;*:*&lt;/artifact&gt;
&lt;excludes&gt;
&lt;exclude&gt;META-INF/*.SF&lt;/exclude&gt;
&lt;exclude&gt;META-INF/*.DSA&lt;/exclude&gt;
&lt;exclude&gt;META-INF/*.RSA&lt;/exclude&gt;
&lt;/excludes&gt;
&lt;/filter&gt;
&lt;/filters&gt;
&lt;/configuration&gt;
&lt;/execution&gt;
&lt;/executions&gt;
&lt;/plugin&gt;
&lt;plugin&gt;
&lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;
&lt;artifactId&gt;maven-compiler-plugin&lt;/artifactId&gt;
&lt;version&gt;3.1&lt;/version&gt;
&lt;configuration&gt;
&lt;source&gt;1.8&lt;/source&gt;
&lt;target&gt;1.8&lt;/target&gt;
&lt;/configuration&gt;
&lt;/plugin&gt;
&lt;plugin&gt;
&lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;
&lt;artifactId&gt;maven-dependency-plugin&lt;/artifactId&gt;
&lt;version&gt;2.3&lt;/version&gt;
&lt;executions&gt;
&lt;execution&gt;
&lt;phase&gt;package&lt;/phase&gt;
&lt;goals&gt;&lt;goal&gt;copy&lt;/goal&gt;&lt;/goals&gt;
&lt;configuration&gt;
&lt;artifactItems&gt;
&lt;artifactItem&gt;
&lt;groupId&gt;com.github.jsimone&lt;/groupId&gt;
&lt;artifactId&gt;webapp-runner&lt;/artifactId&gt;
&lt;version&gt;8.0.30.2&lt;/version&gt;
&lt;destFileName&gt;webapp-runner.jar&lt;/destFileName&gt;
&lt;/artifactItem&gt;
&lt;/artifactItems&gt;
&lt;/configuration&gt;
&lt;/execution&gt;
&lt;/executions&gt;
&lt;/plugin&gt;
&lt;plugin&gt;
&lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;
&lt;artifactId&gt;maven-war-plugin&lt;/artifactId&gt;
&lt;version&gt;3.2.2&lt;/version&gt;
&lt;/plugin&gt;
&lt;/plugins&gt;
&lt;/build&gt;
&lt;/project&gt;

Once you've configured Tomcat Local, you can change this pom.xml.

If you also want database support, add this file to config package:

package bigpuzzle.config;
import org.hibernate.SessionFactory;
import org.hibernate.jpa.HibernatePersistenceProvider;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import javax.sql.DataSource;
import java.io.IOException;
import java.util.Properties;
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(basePackages = &quot;bigpuzzle&quot;, entityManagerFactoryRef = &quot;entityManagerFactory&quot;)
public class DbConfig {
@Primary
@Bean(name = &quot;entityManagerFactory&quot;)
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
entityManagerFactoryBean.setDataSource(getDatasource());
entityManagerFactoryBean.setPersistenceProviderClass(HibernatePersistenceProvider.class);
entityManagerFactoryBean.setJpaProperties(getHibernateProperties());
entityManagerFactoryBean.setPackagesToScan(&quot;bigpuzzle&quot;);
return entityManagerFactoryBean;
}
@Bean
public DataSource getDatasource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(&quot;org.postgresql.Driver&quot;);
dataSource.setUrl(&quot;jdbc:postgresql://127.0.0.1:5432/bigpuzzle&quot;);
dataSource.setUsername(&quot;postgres&quot;);
dataSource.setPassword(&quot;123456&quot;);
return dataSource;
}
@Primary
@Bean
public SessionFactory getSessionFactory() throws IOException {
LocalSessionFactoryBean sessionFactoryBean = new LocalSessionFactoryBean();
sessionFactoryBean.setPackagesToScan(&quot;bigpuzzle&quot;);
//getHibernateProperties method is a private method
sessionFactoryBean.setHibernateProperties(getHibernateProperties());
sessionFactoryBean.setDataSource(getDatasource());
sessionFactoryBean.afterPropertiesSet();
return sessionFactoryBean.getObject();
}
@Bean(name = &quot;transactionManager&quot;)
public PlatformTransactionManager transactionManager() throws IOException {
/*HibernateTransactionManager transactionManager = new HibernateTransactionManager();
transactionManager.setSessionFactory(getSessionFactory());*/
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(entityManagerFactory().getObject());
return transactionManager;
}
@Bean
private static Properties getHibernateProperties() {
Properties hibernateProperties = new Properties();  //PostgreSQLDialect
//hibernateProperties.put(&quot;hibernate.dialect&quot;, &quot;org.hibernate.dialect.HSQLDialect&quot;);
hibernateProperties.put(&quot;hibernate.dialect&quot;, &quot;org.hibernate.dialect.PostgreSQLDialect&quot;);
hibernateProperties.put(&quot;hibernate.connection.driver_class&quot;, &quot;org.postgresql.Driver&quot;);
hibernateProperties.put(&quot;hibernate.show_sql&quot;, true);
hibernateProperties.put(&quot;hibernate.allow_update_outside_transaction&quot;,  false);
//    hibernateProperties.put(&quot;spring.jpa.hibernate.ddl-auto&quot;, &quot;create&quot;);
hibernateProperties.put( &quot;hibernate.hbm2ddl.auto&quot;, &quot;create-drop&quot;);  //create-drop or update
/*hibernateProperties.setProperty(
&quot;hibernate.dialect&quot;, &quot;org.hibernate.dialect.H2Dialect&quot;);
*/
System.out.println();
hibernateProperties.put(&quot;spring.jpa.properties.hibernate.show_sql&quot;, &quot;false&quot;);
hibernateProperties.put(&quot;spring.jpa.properties.hibernate.use_sql_comments&quot;, &quot;true&quot;);
hibernateProperties.put(&quot;spring.jpa.properties.hibernate.format_sql&quot;, &quot;true&quot;);
hibernateProperties.put(&quot;spring.jpa.properties.hibernate.type&quot;, &quot;trace&quot;);
hibernateProperties.put(&quot;spring.jpa.show-sql&quot;, &quot;true&quot;);
hibernateProperties.put(&quot;logging.level.org.hibernate&quot;, &quot;TRACE&quot;);
// other properties
return hibernateProperties;
}
}

PS If you also use Idea Intellij, follow this video to deploy the application on Tomcat.

huangapple
  • 本文由 发表于 2020年8月27日 02:23:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/63603604.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定