claytoncasey01
claytoncasey01

Reputation: 150

Bootstrap with Spring MVC

I am trying to use bootstrap to style my app but I won't apply the styles. This is what is in my JSP

<c:url value="css/bootstrap.min.css" var="cssBoostrap" />  
<link href="${cssBootstrap}" rel="stylesheet">

This css folder is on the same level as WEB-INF not inside of it but it won't work if it is inside of it or even if the files are inside of the view dir. What could the problem possibly be? I no longer get the no mapping error when adding the mapping to my servlet.xml but yet it still doesn't see the file or I can assume it doesn't because no styling is applied, then I change it to link to the online hosted version and all my styles are applied correctly.

Servlet XML

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd 
   http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
   http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
   http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd">


<!-- Scans for annotated @Controllers in the classpath -->
<context:component-scan base-package="com.eaglecrk.recognition" />
<mvc:annotation-driven />


<bean
    class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="locations">
        <list>
            <value>classpath:properties/system.properties</value>
        </list>
    </property>
</bean>

<!-- messageSource -->
<bean id="messageSource"
    class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
    <property name="basenames">
        <list>
            <value>file:${external.property.directory}PMS.EOTM.SendEmail</value>
        </list>
    </property>
</bean>

<!-- dataSource -->
<bean id="dataSource"
    class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="${jdbc.driverClassName}" />
    <property name="url" value="${jdbc.url}" />
    <property name="username" value="${jdbc.username}" />
    <property name="password" value="${jdbc.password}" />
</bean>

<!-- session factory -->
<bean id="sessionFactory"
    class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
    <property name="dataSource">
        <ref bean="dataSource" />
    </property>

    <property name="hibernateProperties">
        <props>
            <prop key="hibernate.dialect">${hibernate.dialect}</prop>
            <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
            <prop key="hibernate.cache.use_second_level_cache">${hibernate.cache.use_second_level_cache}</prop>
            <prop key="hibernate.cache.use_query_cache">${hibernate.cache.use_query_cache}</prop>
            <prop key="hibernate.cache.provider_class">${hibernate.cache.provider_class}</prop>
        </props>
    </property>

    <property name="packagesToScan" value="com.eaglecrk.recognition.persistence" />
</bean>

<!-- Transaction Manager -->
<bean id="transactionManager"
    class="org.springframework.orm.hibernate3.HibernateTransactionManager">
    <property name="sessionFactory" ref="sessionFactory" />
</bean>

<tx:annotation-driven transaction-manager="transactionManager" />

<bean
    class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix" value="/WEB-INF/views/" />
    <property name="suffix" value=".jsp" />
</bean>

<bean id="javaMailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
    <property name="host" value = "${email.host}" />
    <property name="port" value="${email.port}" />
    <property name="username" value="${email.username}" />
    <property name="password" value="${email.password}" />
    <property name="javaMailProperties">
        <props>
            <prop key="mail.smtp.ssl.trust">${email.mail.smtp.ssl.trust}</prop>
            <prop key="mail.smtp.starttls.enable">${email.mail.smtp.starttls.enable}</prop>
            <prop key="mail.smtp.auth">${email.mail.smtp.auth}</prop>
        </props>
    </property>
</bean>

</beans>

Controller

package com.eaglecrk.recognition.controller;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.MessageSourceAware;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.eaglecrk.recognition.dao.award.AwardDao;
import com.eaglecrk.recognition.dao.award.AwardDaoInterface;
import com.eaglecrk.recognition.dao.employee.EmployeeDaoInterface;
import com.eaglecrk.recognition.model.AwardTypeModel;
import com.eaglecrk.recognition.model.EmployeeModel;
import com.eaglecrk.recognition.persistence.AwardNomination;
import com.eaglecrk.recognition.persistence.AwardType;
import com.eaglecrk.recognition.persistence.Employee;
import com.eaglecrk.recognition.util.Functions;
import com.eaglecrk.recognition.util.SpringMailSender;

@Controller
public class TestController extends BaseController implements MessageSourceAware {

private static final Logger LOG = LogManager
        .getLogger(TestController.class);

@Autowired
private EmployeeDaoInterface employeeDao;

@Autowired
private AwardDaoInterface awardDao;

@Autowired
private SpringMailSender springMailSender;

/**
 * @param request
 * @return (ModelAndView) object
 */
@RequestMapping(value = "/test", method = RequestMethod.GET)
public ModelAndView test() {
    try {
    LOG.info("Entered the controller");
    springMailSender.sendMail();
    } catch (Exception e) {
        e.printStackTrace();
    }
    ModelAndView mav = new ModelAndView();
    ArrayList<String> names = new ArrayList<String>();
    List<Employee> employees = employeeDao.findAll();
    Collections.sort(employees, Functions.lastNameOrder);
    for (Employee employee : employees) {
        EmployeeModel model = new EmployeeModel(employee);
        names.add(model.getLocation().getLocationId() + " " + 
        model.getFirstName() + " " + model.getLastName());

    }
    mav.addObject("names", names);
    mav.setViewName("test");
    return mav;
}

@RequestMapping(value = "/test", method = RequestMethod.POST)
public void addNomination(
        @ModelAttribute("SpringWeb") AwardNomination nomination,
        ModelMap model) {

}

@RequestMapping(value = "/login", method = RequestMethod.GET)
public ModelAndView login() {
    ModelAndView mav = new ModelAndView();
    mav.setViewName("login");
    return mav;
}

@RequestMapping(value="/newAwardType", method=RequestMethod.GET)
public ModelAndView addAward() {
    ModelAndView mav = new ModelAndView();
    ArrayList<AwardTypeModel> models = new ArrayList<AwardTypeModel>();
    try{
    AwardTypeModel newAwardTypeModel = new AwardTypeModel();
    newAwardTypeModel.setActive(false);
    newAwardTypeModel.setName("AwardTypeModel.name");
    newAwardTypeModel.setDescription("AwardTypeModel.description");
//      newAwardTypeModel.setId(123456);
    newAwardTypeModel.setCreated(new Date());
    newAwardTypeModel.setModified(new Date());
    models.add(newAwardTypeModel);
    } catch (Exception e){
        e.printStackTrace();
    }

    mav.addObject("awardTypes", models);
    mav.addObject("model", new AwardTypeModel());
    mav.setViewName("addAward");
    return mav;
}

@RequestMapping(value="/addAward", method=RequestMethod.POST)
public String addAwardForm(@ModelAttribute("model") AwardTypeModel model, BindingResult result){

        model.setCreated(new Date());
        model.setModified(new Date());

    AwardType dbo = (AwardType) model.convertToDb();
    awardDao.save(dbo);
    return "redirect:/test";

}

@Override
public void setMessageSource(MessageSource messageSource) {
    // TODO Auto-generated method stub

}



}

Upvotes: 5

Views: 15628

Answers (3)

Aniket Thakur
Aniket Thakur

Reputation: 68905

Following Prasads Answer above if you need Java based configuration for the same use -

@Configuration
@ComponentScan("com.eaglecrk.recognition")
@EnableWebMvc  
public class SpringConfig extends WebMvcConfigurerAdapter {  

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

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

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

Also if you are using xml based configuration don't forget <mvc:default-servlet-handler/>

Upvotes: 0

Prasad
Prasad

Reputation: 3795

Create one folder by name resources at same level as WEB-INF as shown below:

    WebApp-|    
           | - resources -|
           |              |-styles-|
           |              |        |-bootstrap.min.css
           |              |
           |              |-javascript-|
           |                           |-example.js
           |
           | - WEB-INF     

Include the following line in your servlet xml:

    <mvc:resources mapping="/resources/**" location="/resources/"/>

Access these resources in your jsp as:

    <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
    <html>
    <head>
    <link href="<c:url value="/resources/styles/bootstrap.min.css" />" rel="stylesheet">
    <script src="<c:url value="/resources/javascript/example.js" />"></script>
    ....

Upvotes: 10

Maxime
Maxime

Reputation: 560

You should declare in your dispatcher servlet config the location of you resources (e.g js, css, img etc.) :

<mvc:resources mapping="/public/**" location="/public/" />

location contains the path to your resources folder. mapping is how you call your resources in your jsp.

Don't forget to declare your mvc namespace in dispatcher config.

Upvotes: 0

Related Questions