twitter-bootstrap 使用 Spring MVC 进行引导

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22693452/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 20:23:11  来源:igfitidea点击:

Bootstrap with Spring MVC

cssspringtwitter-bootstrapspring-mvc

提问by claytoncasey01

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

我正在尝试使用引导程序来设置我的应用程序的样式,但我不会应用这些样式。这就是我的 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.

此 css 文件夹与 WEB-INF 不在同一级别,不在其中,但如果它在其中,或者即使文件在视图目录中,它也不会工作。可能是什么问题?将映射添加到我的 servlet.xml 时,我不再收到无映射错误,但它仍然看不到文件,或者我可以假设它看不到,因为没有应用样式,然后我将其更改为链接到在线托管版本和我所有的样式都正确应用。

Servlet XML

服务端 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

}



}

回答by Prasad

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

创建一个与WEB-INF同级的资源名称文件夹,如下图:

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

Include the following line in your servlet xml:

在您的 servlet xml 中包含以下行:

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

Access these resources in your jsp as:

在您的 jsp 中访问这些资源:

    <%@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>
    ....

回答by Maxime

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

您应该在调度程序 servlet 配置中声明资源的位置(例如 js、css、img 等):

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

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

locationcontains the path to your resources folder. mappingis how you call your resources in your jsp.

location包含资源文件夹的路径。mapping是您在jsp 中调用资源的方式。

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

不要忘记在调度程序配置中声明您的 mvc 命名空间。

回答by Aniket Thakur

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

如果您需要基于 Java 的配置进行相同的使用,请按照上面的 Prasads 回答 -

@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/>

此外,如果您使用基于 xml 的配置,请不要忘记 <mvc:default-servlet-handler/>