Spring MVC + Twitter Bootstrap 3 + Webjar

agusgambina picture agusgambina · Jan 9, 2014 · Viewed 7.1k times · Source

I have a project with "Spring MVC" and I want to add "Twitter Bootstrap 3"

Here is part of the code

Initializer.java

package com.restaurant.init;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration.Dynamic;

import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;

public class Initializer implements WebApplicationInitializer {

        public void onStartup(ServletContext servletContext)
                        throws ServletException {
                AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
                ctx.register(WebAppConfig.class);
                servletContext.addListener(new ContextLoaderListener(ctx));

                ctx.setServletContext(servletContext);

                Dynamic servlet = servletContext.addServlet("dispatcher", new DispatcherServlet(ctx));
                servlet.addMapping("/");
                servlet.setLoadOnStartup(1);
        }

}

WebAppConfig.java

package com.restaurant.init;

import java.util.Properties;

import javax.annotation.Resource;
import javax.sql.DataSource;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.hibernate4.HibernateTransactionManager;
import org.springframework.orm.hibernate4.LocalSessionFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.JstlView;
import org.springframework.web.servlet.view.UrlBasedViewResolver;

@Configuration
@ComponentScan("com.restaurant")
@EnableWebMvc
@EnableTransactionManagement
@PropertySource("classpath:application.properties")
public class WebAppConfig {

    private static final String PROPERTY_NAME_DATABASE_DRIVER = "db.driver";
    private static final String PROPERTY_NAME_DATABASE_PASSWORD = "db.password";
    private static final String PROPERTY_NAME_DATABASE_URL = "db.url";
    private static final String PROPERTY_NAME_DATABASE_USERNAME = "db.username";

    private static final String PROPERTY_NAME_HIBERNATE_DIALECT = "hibernate.dialect";
    private static final String PROPERTY_NAME_HIBERNATE_SHOW_SQL = "hibernate.show_sql";
    private static final String PROPERTY_NAME_CONNECTION_POOL_SIZE = "hibernate.connection_pool_size";
    private static final String PROPERTY_NAME_HIBERNATE_HBM2DDL_AUTO = "hibernate.hbm2ddl.auto";
    private static final String PROPERTY_NAME_ENTITYMANAGER_PACKAGES_TO_SCAN = "entitymanager.packages.to.scan";

    @Resource
    private Environment env;

    @Bean
    public DataSource dataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();

        dataSource.setDriverClassName(env.getRequiredProperty(PROPERTY_NAME_DATABASE_DRIVER));
        dataSource.setUrl(env.getRequiredProperty(PROPERTY_NAME_DATABASE_URL));
        dataSource.setUsername(env.getRequiredProperty(PROPERTY_NAME_DATABASE_USERNAME));
        dataSource.setPassword(env.getRequiredProperty(PROPERTY_NAME_DATABASE_PASSWORD));

        return dataSource;
    }

    @Bean
    public LocalSessionFactoryBean sessionFactory() {
        LocalSessionFactoryBean sessionFactoryBean = new LocalSessionFactoryBean();
        sessionFactoryBean.setDataSource(dataSource());
        sessionFactoryBean.setPackagesToScan(env.getRequiredProperty(PROPERTY_NAME_ENTITYMANAGER_PACKAGES_TO_SCAN));
        sessionFactoryBean.setHibernateProperties(hibProperties());
        return sessionFactoryBean;
    }

    private Properties hibProperties() {
        Properties properties = new Properties();
        properties.put(PROPERTY_NAME_HIBERNATE_DIALECT, env.getRequiredProperty(PROPERTY_NAME_HIBERNATE_DIALECT));
        properties.put(PROPERTY_NAME_HIBERNATE_SHOW_SQL, env.getRequiredProperty(PROPERTY_NAME_HIBERNATE_SHOW_SQL));
        properties.put(PROPERTY_NAME_CONNECTION_POOL_SIZE, env.getRequiredProperty(PROPERTY_NAME_CONNECTION_POOL_SIZE));
        properties.put(PROPERTY_NAME_HIBERNATE_HBM2DDL_AUTO, env.getRequiredProperty(    PROPERTY_NAME_HIBERNATE_HBM2DDL_AUTO));
        return properties;  
    }

    @Bean
    public HibernateTransactionManager transactionManager() {
        HibernateTransactionManager transactionManager = new HibernateTransactionManager();
        transactionManager.setSessionFactory(sessionFactory().getObject());
        return transactionManager;
    }

    @Bean
    public UrlBasedViewResolver setupViewResolver() {
        UrlBasedViewResolver resolver = new UrlBasedViewResolver();
        resolver.setPrefix("/WEB-INF/pages/");
        resolver.setSuffix(".jsp");
        resolver.setViewClass(JstlView.class);
        return resolver;
    }

}

I tryied using Webjars adding the dependency in the pom and modifying the jsp

pom.xml

<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.restaurant</groupId 
    <artifactId web-crud</artifactId 
    <version 0.0.1-SNAPSHOT</version 
    <packaging war</packaging 


    <build 
        <finalName web-crud</finalName 
        <plugins 
            <plugin 
                <artifactId maven-compiler-plugin</artifactId 
                <version 3.1</version 
                <configuration 
                    <source 1.7</source 
                    <target 1.7</target 
                </configuration 
            </plugin 
        </plugins 
    </build 

    <properties 
        <project.build.sourceEncoding UTF-8</project.build.sourceEncoding 
        <hibernate.version 4.2.0.Final</hibernate.version 
        <mysql.connector.version 5.1.21</mysql.connector.version 
        <spring.version 3.2.2.RELEASE</spring.version 
    </properties 

    <dependencies 
        <!-- DB related dependencies -- 
        <dependency 
            <groupId org.hibernate</groupId 
            <artifactId hibernate-core</artifactId 
            <version ${hibernate.version}</version 
        </dependency 
        <dependency 
            <groupId org.hibernate</groupId 
            <artifactId hibernate-entitymanager</artifactId 
            <version ${hibernate.version}</version 
        </dependency 
        <dependency 
            <groupId mysql</groupId 
            <artifactId mysql-connector-java</artifactId 
            <version ${mysql.connector.version}</version 
        </dependency 
        <dependency 
            <groupId commons-dbcp</groupId 
            <artifactId commons-dbcp</artifactId 
            <version 1.4</version 
        </dependency 
        <dependency 
            <groupId javassist</groupId 
            <artifactId javassist</artifactId 
            <version 3.12.1.GA</version 
        </dependency 
        <!-- SPRING -- 
        <dependency 
            <groupId org.springframework</groupId 
            <artifactId spring-webmvc</artifactId 
            <version ${spring.version}</version 
        </dependency 
        <dependency 
            <groupId org.springframework</groupId 
            <artifactId spring-tx</artifactId 
            <version ${spring.version}</version 
        </dependency 
        <dependency 
            <groupId org.springframework</groupId 
            <artifactId spring-jdbc</artifactId 
            <version ${spring.version}</version 
        </dependency 
        <dependency 
            <groupId org.springframework</groupId 
            <artifactId spring-orm</artifactId 
            <version ${spring.version}</version 
        </dependency 
        <!-- CGLIB is required to process @Configuration classes -- 
        <dependency 
            <groupId cglib</groupId 
            <artifactId cglib</artifactId 
            <version 2.2.2</version 
        </dependency 
        <!-- Servlet API and JSTL -- 
        <dependency 
            <groupId javax.servlet</groupId 
            <artifactId javax.servlet-api</artifactId 
            <version 3.0.1</version 
            <scope provided</scope 
        </dependency 
        <dependency 
            <groupId jstl</groupId 
            <artifactId jstl</artifactId 
            <version 1.2</version 
        </dependency 

        <!-- Test -- 
        <dependency 
            <groupId junit</groupId 
            <artifactId junit</artifactId 
            <version 4.7</version 
            <scope test</scope 
        </dependency 
        <dependency 
            <groupId org.springframework</groupId 
            <artifactId spring-test</artifactId 
            <version ${spring.version}</version 
            <scope test</scope 
        </dependency 

        <dependency 
            <groupId org.webjars</groupId 
            <artifactId jquery</artifactId 
            <version 2.0.3-1</version 
        </dependency 

        <dependency 
            <groupId org.webjars</groupId 
            <artifactId bootstrap</artifactId 
            <version 3.0.3</version 
        </dependency 
    </dependencies 
</project 

index.jsp

<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"% 
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"% 
<%@ page session="false"% 

<!DOCTYPE html 
<html 
<head 
<title Bootstrap test</title 
<!-- Twitter Bootstrap -- 
<spring:url value="/webjars/bootstrap/3.0.3/css/bootstrap.min.css"
    var="bootstrapCSS" / 
<link href="${bootstrapCSS}" rel="stylesheet" / 
<spring:url value="/webjars/bootstrap/3.0.3/css/bootstrap-theme.min.css"
    var="bootstrapCSStheme" / 
<link href="${bootstrapCSStheme}" rel="stylesheet" / 
<!-- jQuery UI -- 
<spring:url value="/webjars/jquery-ui/1.10.3/themes/base/jquery-ui.css"
    var="jQueryUIcss" / 
<link href="${jQueryUIcss}" rel="stylesheet" </link 
</head 
<body 
    <nav class="navbar navbar-default" role="navigation" 
        <!-- Brand and toggle get grouped for better mobile display -- 
        <div class="navbar-header" 
            <button type="button" class="navbar-toggle" data-toggle="collapse"
                data-target="#bs-example-navbar-collapse-1" 
                <span class="sr-only" Toggle navigation</span  <span
                    class="icon-bar" </span  <span class="icon-bar" </span  <span
                    class="icon-bar" </span 
            </button 
            <a class="navbar-brand" href="#" Brand</a 
        </div 

        <!-- Collect the nav links, forms, and other content for toggling -- 
        <div class="collapse navbar-collapse"
            id="bs-example-navbar-collapse-1" 
            <ul class="nav navbar-nav" 
                <li class="active" <a href="#" Link</a </li 
                <li <a href="#" Link</a </li 
                <li class="dropdown" <a href="#" class="dropdown-toggle"
                    data-toggle="dropdown" Dropdown <b class="caret" </b </a 
                    <ul class="dropdown-menu" 
                        <li <a href="#" Action</a </li 
                        <li <a href="#" Another action</a </li 
                        <li <a href="#" Something else here</a </li 
                        <li class="divider" </li 
                        <li <a href="#" Separated link</a </li 
                        <li class="divider" </li 
                        <li <a href="#" One more separated link</a </li 
                    </ul </li 
            </ul 
            <form class="navbar-form navbar-left" role="search" 
                <div class="form-group" 
                    <input type="text" class="form-control" placeholder="Search" 
                </div 
                <button type="submit" class="btn btn-default" Submit</button 
            </form 
            <ul class="nav navbar-nav navbar-right" 
                <li <a href="#" Link</a </li 
                <li class="dropdown" <a href="#" class="dropdown-toggle"
                    data-toggle="dropdown" Dropdown <b class="caret" </b </a 
                    <ul class="dropdown-menu" 
                        <li <a href="#" Action</a </li 
                        <li <a href="#" Another action</a </li 
                        <li <a href="#" Something else here</a </li 
                        <li class="divider" </li 
                        <li <a href="#" Separated link</a </li 
                    </ul </li 
            </ul 
        </div 
        <!-- /.navbar-collapse -- 
    </nav 
</body 
</html 

But I get this error

 Jan 10, 2014 1:29:48 AM org.apache.jasper.compiler.TldLocationsCache tldScanJar
 INFO: 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.
 Jan 10, 2014 1:29:49 AM org.springframework.web.servlet.DispatcherServlet noHandlerFound
 WARNING: No mapping found for HTTP request with URI [/web-crud/webjars/jquery-ui/1.10.3/themes/base/jquery-ui.css] in  DispatcherServlet with name 'dispatcher'
 Jan 10, 2014 1:29:49 AM org.springframework.web.servlet.DispatcherServlet noHandlerFound
 WARNING: No mapping found for HTTP request with URI [/web-crud/webjars/bootstrap/3.0.3/css/bootstrap-theme.min.css] in  DispatcherServlet with name 'dispatcher'
 Jan 10, 2014 1:29:49 AM org.springframework.web.servlet.DispatcherServlet noHandlerFound
 WARNING: No mapping found for HTTP request with URI [/web-crud/webjars/bootstrap/3.0.3/css/bootstrap.min.css] in  DispatcherServlet with name 'dispatcher'

Answer

James Ward picture James Ward · Feb 15, 2014

It doesn't look like you've added the resource handler for WebJars. See the WebJars Spring MVC docs for more info.