1
votes

I am using Spring 4, Servlet 3 API and Tomcat 8 for my project. I have a problem with deployment. I am trying to deploy WAR package in my VPS. I am using Intellij IDEA.

I coppied my WAR to /opt/tomcat/webapps path. I can see WAR from Tomcat's apps page. But when I try to browse URL I get 404 Not Found error.

I am using Spring with annotation and empty web.xml and also I am using Spring Security.

WepAppInitializer.java

public class WepAppInitializer implements WebApplicationInitializer {

@Override
public void onStartup(final ServletContext servletContext) throws ServletException {
    AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
    ctx.register(WebConfig.class);
    ctx.setServletContext(servletContext);
    ServletRegistration.Dynamic dynamic = servletContext.addServlet("dispatcher", new DispatcherServlet(ctx));
    dynamic.addMapping("/acentecilik");
    dynamic.setLoadOnStartup(1);
    }
}

WebConfig.java

@Configuration
@EnableWebMvc
@EnableTransactionManagement
@ComponentScan("com.decimatech.acentecilik")
@PropertySource("classpath:application.properties")
public class WebConfig extends WebMvcConfigurerAdapter{

@Override
public void addInterceptors(InterceptorRegistry registry) {
    registry.addInterceptor(new ThymeleafLayoutInterceptor());
}


@Override
public void addResourceHandlers(ResourceHandlerRegistry registry){
    registry.addResourceHandler("/resources/**").addResourceLocations("/static/");
}

@Bean
@Description("Thymeleaf template resolver serving HTML 5")
public ServletContextTemplateResolver templateResolver() {
    ServletContextTemplateResolver templateResolver = new ServletContextTemplateResolver();
    templateResolver.setPrefix("/WEB-INF/html/");
    templateResolver.setSuffix(".html");
    templateResolver.setTemplateMode("LEGACYHTML5");
    templateResolver.setCharacterEncoding("UTF-8");
    templateResolver.setCacheable(false);

    return templateResolver;
}

@Bean
@Description("Thymeleaf template engine with Spring integration")
public SpringTemplateEngine templateEngine() {
    SpringTemplateEngine templateEngine = new SpringTemplateEngine();
    templateEngine.setTemplateResolver(templateResolver());

    return templateEngine;
}

@Bean
@Description("Thymeleaf view resolver")
public ThymeleafViewResolver viewResolver() {
    ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
    viewResolver.setTemplateEngine(templateEngine());
    viewResolver.setContentType("text/html;charset=UTF-8");
    viewResolver.setCharacterEncoding("utf-8");

    return viewResolver;
}

@Value("${spring.datasource.driver-class-name}")
private String driverClassName;

@Value("${spring.datasource.url}")
private String datasourceUrl;

@Value("${spring.datasource.username}")
private String datasourceUsername;

@Value("${spring.datasource.password}")
private String datasourcePassword;

@Bean(name = "dataSource")
public DataSource getDataSource() {
    DriverManagerDataSource dataSource = new DriverManagerDataSource();
    dataSource.setDriverClassName(driverClassName);
    dataSource.setUrl(datasourceUrl);
    dataSource.setUsername(datasourceUsername);
    dataSource.setPassword(datasourcePassword);

    return dataSource;
}

@Autowired
@Bean(name = "transactionManager")
public HibernateTransactionManager getTransactionManager(SessionFactory sessionFactory) {
    HibernateTransactionManager transactionManager = new HibernateTransactionManager(sessionFactory);

    return transactionManager;
}

@Autowired
@Bean(name = "sessionFactory")
public SessionFactory getSessionFactory(DataSource dataSource) {

    LocalSessionFactoryBuilder sessionBuilder = new LocalSessionFactoryBuilder(dataSource);

    sessionBuilder.scanPackages("com.decimatech.acentecilik.model");
    sessionBuilder.addProperties(getHibernateProperties());

    return sessionBuilder.buildSessionFactory();
}

private Properties getHibernateProperties() {
    Properties properties = new Properties();
    properties.put("hibernate.dialect", "org.hibernate.dialect.PostgreSQLDialect");
    properties.put("hibernate.hbm2ddl.auto", "update");
    properties.put("hibernate.show_sql", "true");
    properties.put("hibernate.format_sql", "true");
    properties.put("hibernate.use_sql_comments", "true");
    properties.put("hibernate.enable_lazy_load_no_trans", "true");
    return properties;
}

@Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
    return new PropertySourcesPlaceholderConfigurer();
}
}

web.xml

<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"
     metadata-complete="true">

<display-name>Acentecilik</display-name>
<description>
    Acentecilik
</description>
</web-app>

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.decimatech</groupId>
<artifactId>acentecilik</artifactId>
<version>1.0-SNAPSHOT</version>

//Some package dependencies

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.3</version>
            <configuration>
                <source>1.8</source>
                <target>1.8</target>
            </configuration>
        </plugin>

        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-resources-plugin</artifactId>
            <version>2.7</version>
            <configuration>
                <encoding>UTF-8</encoding>
            </configuration>
        </plugin>
    </plugins>
</build>

</project>

Here is some screenshot about what settings I used.

IDEA WAR Settings IDEA WAR Settings

Project Structures

Project Structures

Tomcat Manage Apps Page

Tomcat Manage Apps Page

And 404 Error 404 Error

How can I solve this problem?

Here is my catalina log file's output. I changed WAR's ownership from root to tomcat user. But still same problem.

02-Oct-2015 16:03:23.800 SEVERE [localhost-startStop-10] org.apache.catalina.startup.ContextConfig.beforeStart Exception fixing docBase for context [/acentecilik] java.io.IOException: Unable to create the directory [/opt/tomcat/webapps/acentecilik] at org.apache.catalina.startup.ExpandWar.expand(ExpandWar.java:115) at org.apache.catalina.startup.ContextConfig.fixDocBase(ContextConfig.java:618) at org.apache.catalina.startup.ContextConfig.beforeStart(ContextConfig.java:744) at org.apache.catalina.startup.ContextConfig.lifecycleEvent(ContextConfig.java:307) at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:95) at org.apache.catalina.util.LifecycleBase.fireLifecycleEvent(LifecycleBase.java:90) at org.apache.catalina.util.LifecycleBase.setStateInternal(LifecycleBase.java:402) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:147) at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:725) at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:701) at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:717) at org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:945) at org.apache.catalina.startup.HostConfig$DeployWar.run(HostConfig.java:1798) at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471) at java.util.concurrent.FutureTask.run(FutureTask.java:262) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) at java.lang.Thread.run(Thread.java:745)

02-Oct-2015 16:03:58.561 INFO [localhost-startStop-10] org.apache.jasper.servlet.TldScanner.scanJars At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time.

02-Oct-2015 16:03:58.649 INFO [localhost-startStop-10] org.apache.catalina.startup.HostConfig.deployWAR Deployment of web application archive /opt/tomcat/webapps/acentecilik.war has finished in 34,860 ms

Edit I changed /opt/tomcat/webapps ownership to tomcat and now I don't get the 404 error. But now I have this.

INFO [http-nio-8080-exec-17] org.apache.catalina.core.ApplicationContext.log No Spring WebApplicationInitializer types detected on classpath

1
Have you checked Tomcat logs ? I guess there is nothing since you're getting a 404 error but just to be sure..Gaël J
just one thing, offtopic, you are trying to hide the "localhost" word which mentionned on the whole code ?Chaibi Alaa
No. It is my test server's ip. So real world ip. @ChaibiAlaafatiherdem
I'm tempted to vote to close this as "Questions seeking debugging help ("why isn't this code working?") must include the desired behavior, a specific problem or error and the shortest code necessary to reproduce it in the question itself. Questions without a clear problem statement are not useful to other readers." Once you fix one issue, there's probably a plethora of others. @destan already answered the first issue. You should go for minimal example reproducing the problem, the deployment issue, not complex configurations like you have here.eis
I write my all config files because I did't know where the problem is. I tought the problem could be related with config or Tomcat or Maven. That's why I write so much about problem.fatiherdem

1 Answers

3
votes

the exception says

org.apache.catalina.startup.ContextConfig.beforeStart Exception fixing docBase for context [/acentecilik] java.io.IOException: Unable to create the directory

and you've already stated that tomcat is under /opt. so I suppose tomcat has not sufficient permission to create (write permission) on its own directory /opt/tomcat.

If you give write permission to the user who launches the tomcat (most probably your own user) then the problem goes away.

sudo chmod -R 0744 /opt/tomcat