2015-08-18 2 views
0

У меня возникла проблема с загрузкой изображений, CSS и тем в Spring MVC.
При добавлении ресурсов, я получаю сообщение об ошибке, таких как No mapping found for HTTP request with URISpring MVC Нет сопоставления для HTTP-запроса с URI

Я использую Spring 4.1.4 RELEASE работает на Java 1.8 и Tomcat 8.

Проект представлен в структуре проекта.

Project Structure

web.xml

<?xml version="1.0" encoding="UTF-8"?> 
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> 
    <display-name>SpringHibernate</display-name> 
    <servlet> 
     <servlet-name>mvc-dispatcher</servlet-name> 
     <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> 
     <!-- <init-param> 
      <param-name>contextConfigLocation</param-name> 
      <param-value>/WEB-INF/config/SpringHibernate-servlet.xml</param-value> 
     </init-param> --> 
     <load-on-startup>1</load-on-startup> 
    </servlet> 

<context-param> 
     <param-name>contextConfigLocation</param-name> 
     <param-value>/WEB-INF/mvc-dispatcher-servlet.xml 
        /WEB-INF/spring-security.xml 
     </param-value> 
    <!--  <param-value>/WEB-INF/config/SpringHibernate-servlet.xml</param-value> --> 
</context-param> 


<listener> 
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> 
</listener> 

    <servlet-mapping> 
     <servlet-name>mvc-dispatcher</servlet-name> 
     <url-pattern>*.html</url-pattern> 
     <url-pattern>/</url-pattern> 
    </servlet-mapping> 

    <welcome-file-list> 
    <welcome-file>loginPage.jsp</welcome-file>  
    </welcome-file-list> 



    <filter> 
     <filter-name>springSecurityFilterChain</filter-name> 
     <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class> 
    </filter> 

    <filter-mapping> 
     <filter-name>springSecurityFilterChain</filter-name> 
     <url-pattern>/*</url-pattern> 
    </filter-mapping> 



</web-app> 

MVC-диспетчерская-servlet.xml

<?xml version="1.0" encoding="UTF-8"?> 
<beans xmlns="http://www.springframework.org/schema/beans" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xmlns:context="http://www.springframework.org/schema/context" 
xmlns:mvc="http://www.springframework.org/schema/mvc" 
xmlns:tx="http://www.springframework.org/schema/tx" 
xsi:schemaLocation=" 
http://www.springframework.org/schema/beans 
http://www.springframework.org/schema/beans/spring-beans-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/mvc 
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd 
http://www.springframework.org/schema/tx 
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"> 

    <context:property-placeholder location="classpath:resources/database.properties" /> 
    <context:component-scan base-package="com.wbview" /> 

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

    <bean class="org.springframework.web.servlet.view.UrlBasedViewResolver" id="viewResolver"> 
    <property name="viewClass"> 
    <value> 
     org.springframework.web.servlet.view.tiles3.TilesView 
    </value> 
    </property> 
</bean> 
<bean class="org.springframework.web.servlet.view.tiles3.TilesConfigurer" id="tilesConfigurer"> 
    <property name="definitions"> 
    <list> 
     <value>/WEB-INF/tiles.xml</value> 
    </list> 
     </property> 
</bean> 


    <bean id="dataSource" 
     class="org.springframework.jdbc.datasource.DriverManagerDataSource"> 
     <property name="driverClassName" value="${database.driver}" /> 
     <property name="url" value="${database.url}" /> 
     <property name="username" value="${database.user}" /> 
     <property name="password" value="${database.password}" /> 
    </bean> 
<mvc:resources mapping="/resources/**" location="/resources/" /> 
<!-- <mvc:resources mapping="/theme/**" location="/theme/" /> 
    <mvc:resources mapping="/script/**" location="/script/" /> 
--> 
    <bean id="sessionFactory" 
    class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> 
     <!-- class="org.springframework.orm.hibernate4.annotation.AnnotationSessionFactoryBean"> --> 
     <property name="dataSource" ref="dataSource" /> 
     <property name="annotatedClasses"> 
      <list> 
       <value>com.wbview.model.Employee</value> 
       <value>com.wbview.model.UL</value>    
      </list>   
     </property> 
     <property name="mappingResources"> 
      <list> 
       <value>com/wbview/model/ul.hbm.xml</value>       
      </list>   
     </property> 
     <property name="hibernateProperties"> 
      <props> 
       <prop key="hibernate.dialect">${hibernate.dialect}</prop> 
       <prop key="hibernate.show_sql">${hibernate.show_sql}</prop> 
       <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop> 
       <prop key="maxwait">10000</prop> 
       <prop key="maxidle">25</prop> 
       <prop key="minidle">5</prop>    
      </props> 
     </property> 
    </bean> 

    <bean id="hibernateTransactionManager" 
     class="org.springframework.orm.hibernate4.HibernateTransactionManager"> 
     <property name="sessionFactory" ref="sessionFactory" /> 
    </bean> 

</beans> 

Небольшая часть LoginController

@Controller 
public class LoginController { 

    @Autowired 
    private LoginService loginService; 


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

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

    @RequestMapping(value="/validateLogin", method = RequestMethod.POST) 
    public ModelAndView validateLogin(@RequestParam("userId") String userId, HttpSession session) {  
     String sessionId = session.getId(); 
     session.setAttribute("userId", userId); 
     session.setAttribute("sessionId", sessionId); 
     System.out.println("User Id : 1 : "+userId +" : 1 : "+sessionId); 
     boolean loginStatus= loginService.setUserLoginEntries(userId, sessionId, "L"); 
     if (loginStatus) 
      return new ModelAndView("welcome"); 
     else 
      return new ModelAndView("mflogin"); 
    } 


<%@ page import="org.apache.log4j.Logger,java.util.regex.*,java.net.*" errorPage="errorPage.jsp"%> 

<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%> 
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> 

<style> 
#loginBox { 
    /*margin: 0.7in auto;*/  
    width: 60%; 
    padding: 25px; 
    text-align: center; 
    background-color: #F3F2EE; 
    border: 3px solid #fff; 
    vertical-align: middle; 
} 
#loginBox p { 
    padding:0; 
    margin:2ex 0; 
} 
</style> 
<script type="text/javascript" src="resources/script/login.js"></script> 
<script type="text/JavaScript"> 
    curvyCorners.addEvent(window, 'load', initCorners); 
    //window.onload=initCorners; 
    function initCorners() { 
    var settings = { 
     tl: { radius: 10 }, 
     tr: { radius: 10 }, 
     bl: { radius: 10 }, 
     br: { radius: 10 }, 
     antiAlias: true 
    } 


    curvyCorners(settings, "#loginBox"); 
    break_out_of_frame();  
    //document.loginform.userId.focus(); 
    setTimeout(function(){document.getElementById('userId').focus();},300);     
    } 

    var activebtn = "submitbtn"; 
    window.document.onkeydown = function(e) { 
     if (!e){ var e = window.event; }  
     // Enter is pressed  
     if (e.keyCode == 13) 
      { 
       if(activebtn=="submitbtn"){ 
        submit_form();; 
       }    
      }   
    } 

    function greenBtn(obj){ 
     if(obj.value.length>0){ 
      document.getElementById("loginBtn").innerHTML = '<a class="ovalbuttongreen" href="javascript:submit_form();" tabIndex="3" style="text-decoration:none;color:black;width:80px"><span>Login</span></a>'; 
     } 
    } 
    function clearForm(){ 
     document.loginform.userId.value=''; 
     document.loginform.pswd.value='' 
    } 
    function submit_form(){ 
     //document.loginform.userId.value=''; 
     //document.loginform.pswd.value='' 
     alert(document.loginform.userId.value); 
     document.loginform.action="validateLogin.html"; 
     document.loginform.submit(); 
    } 
</script> 
<form:form id="loginform" name="loginform" method="post" action="validateLogin" > 

<div class="rcorn_box2" style="background-image:url('resources/img/globe_background.jpg');"><br><br><br> 
    <table border="0" cellspacing="0" cellpadding="0" width="100%" align="center">   
      <tr><td align="center" valign="middle"> 
       <div id="loginBox"> 
        <table cellspacing="0" cellpadding="0" width="100%" align="center" border="0"> 
         <tr><td bgcolor="#E8EAE2"> 
          <table cellspacing="0" cellpadding="0" width="100%"> 
           <tr> 
            <td bgcolor="#E8EAE2" align="left" width="15%"><img src="resources/img/CitiGroupWebView_LogoV2.gif" alt="" border="0"></td> 
            <td bgcolor="#E8EAE2" width="85%"> 
             <I><B><FONT face='Garamond (W1), Century, Times New Roman ,serif' color=1D5898 size=6>Login</FONT></B></I> 
            </td> 
           </tr> 
          </table>        
         </td></tr>      
         <tr><td>        
          <input id="sortorder" type="hidden" name="sortorder" value="msg"> 
          <input id="sortOrderType" type="hidden" name="sortOrderType" value="asc"> 
          <input id="cmd" type="hidden" name="cmd" value="validateLogin"> 
          <TABLE bgColor=white border=0 cellPadding=2 cellSpacing=0 WIDTH='615'> 
          <TR> 
           <TD width=15%>&nbsp;</TD> 
           <TD width=15%>&nbsp;</TD> 
           <TD width=10%>&nbsp;</TD> 
           <TD width=10%>&nbsp;</TD> 
           <TD width=30%>&nbsp;</TD> 
          </TR>       
          <TR> 
           <TD class="CB" colspan="5"> 

           </TD> 
          </TR>       
          <TR> 
           <TD colspan=5 align="center">&nbsp;</TD> 
          </TR> 

          <TR> 
           <TD>&nbsp;</TD> 
           <TD>&nbsp;</TD> 
           <TD align="left" nowrap>User ID &nbsp;</TD> 
           <TD align="left"><Input type="text" name='userId' id='userId' maxlength='8' style="width:100px" value='<%-- <% if (request.getParameter("userId")!= null) { out.println(filterInputString(request.getParameter("userId"))); }%> --%>'></TD> 
           <TD>&nbsp;</TD>        
          </TR> 
          <TR> 
           <TD>&nbsp;</TD> 
           <TD>&nbsp;</TD> 
           <TD align="left" nowrap>Password &nbsp;</TD> 
           <TD align="left"><input type="password" name='pswd' id='pswd' maxlength='12' style="width:100px" onKeyPress="greenBtn(this);" value='<%-- <% if (request.getParameter("pswd")!= null && sPasswordExpired.equals("Y")) { out.println(request.getParameter("pswd")); }%> --%>'></TD> 
           <TD>&nbsp;</TD> 
          </TR>       
          <TR> 
           <TD>&nbsp;</TD> 
           <TD align="left" nowrap> 

           </TD> 
           <TD align="left" nowrap> 

           </TD> 
           <TD align="left"> 

           </TD> 
           <TD>&nbsp;</TD> 
          </TR> 
          <TR> 
           <TD>&nbsp;</TD> 
           <TD>&nbsp;</TD> 
           <TD align="left" nowrap> 
            <div id=divPwdBlock3 name=divPwdBlock3 <%-- <% if (sPasswordExpired.equals("N")) { %> --%> style="visibility: hidden"<%-- <% } %> --%>>Retype Password &nbsp;</div> 
           </TD> 
           <TD align="left"> 
            <div id=divPwdBlock4 name=divPwdBlock4 <%-- <% if (sPasswordExpired.equals("N")) { %> --%>style="visibility: hidden"<%-- <% } %> --%>> 
             <Input type=password name='retypepswd' id='retypepswd' class='TS' style="width:100px" maxlength=12 size=14 value=''> 
            </div> 
           </TD> 
           <TD>&nbsp;</TD> 
          </TR>       
          <TR> 
           <TD>&nbsp;</TD> 
           <TD>&nbsp;</TD> 
           <TD>&nbsp;</TD> 
           <TD align="left"> 
            <div class="buttonwrapper" id="loginBtn"> 
             <a class="ovalbutton" href="javascript:submit_form();" style="cursor:hand;text-decoration:none;color:black;width:80px"><span>Login</span></a> 
            </div> 
           </TD> 
           <TD align="left"> 
            <div class="buttonwrapper" id="clearBtn"> 
             <a class="ovalbutton" href="javascript:clearForm();" style="cursor:hand;text-decoration:none;color:black;width:80px"><span>Clear</span></a> 
            </div> 
           </TD> 
          </TR> 
          <%-- <%}else{%> --%> 
           <tr><td colspan="5" height="100px">&nbsp;</td></tr> 
          <%-- <%}%> --%> 
          <TR> 
           <%-- <% if (request.getAttribute("errMsg") == null) { %> --%> 
            <TD colspan=5><br></TD> 
           <%-- <% } else { %> --%> 
            <TD colspan=5 class="LB"><%=request.getAttribute("errMsg")%><br></TD> 
           <%-- <% } %> --%> 
          </TR>       
          <TR> 
           <TD colspan=5 align="center">&nbsp;If you are experiencing any difficulties, please reference our <a target="_blank" href="ReportServlet?cmd=sharePoint">Sharepoint Site</a> 
            <br><br>Also visit our <a target="_blank" href="ReportServlet?cmd=sharePoint">Sharepoint Site</a> for access instructions, training, and request forms 
           </TD> 
          </TR> 
          <TR> 
           <TD colspan=5 align="center"></TD> 
          </TR> 
          <TR> 
           <TD colspan=5 align="center"> 
            <a target="_blank" href="https://globalconsumer.collaborationtools.consumer.citigroup.net/sites/webview/Web%20View%20Training1/AboutWebView.pdf">About Web View</a>&nbsp;&nbsp;&nbsp; 
            <a target="_blank" href="https://globalconsumer.collaborationtools.consumer.citigroup.net/sites/webview/Password%20Reset/How%20to%20%20reset%20your%20Web%20View%20password.pdf">Password Reset</a> 
           </TD> 
          </TR> 
          <TR> 
          <TD colspan=5 align="center"><font color="#B5B6CF"> 
          <p align="justify" style="padding-left:10px;padding-right:10px">Please be aware that the files you are requesting contains sensitive information and will be written to your temporary 
          internet file cache on your workstation and is accessible offline from that location. Please clean up your temporary internet cache for security reasons. 
          </p></font></TD> 
          </TR>              
         </table> 
          <font color="#5D5D5D"> 
          <p align="justify" style="padding-left:10px;padding-right:10px">You are authorized to use this System for approved business purposes only. Use for any other purpose is prohibited. All transactional records, reports, email, 
          software and other data generated by or residing upon this System, to the extent permitted by local law, are the property of Citigroup Inc. or one of its subsidiaries 
          or their affiliates (individually or collectively ' Citigroup ') and may be used by Citigroup for any purpose authorized and permissible in your country of work. Activities on this System are monitored to the extent permitted by local law. 
          </p></font>      
         </td></tr> 
        </table> 
       </div> 
       </td>   
      </tr>   
    </table><br><br><br> 
</div> 
</form:form> 

Основная проблема заключается в том, когда iam не включает ресурсы в mvc-dispatcher-servlet.xml i.e. Моя страница загружается без изображений или тем или css.

журналы консоли, как показано ниже

08/18/2015 22:15:19.192|;|PageNotFound|;|No mapping found for HTTP request with URI [/SpringMVCDemo/script/curvycorners.src.js] in DispatcherServlet with name 'mvc-dispatcher' 
08/18/2015 22:15:19.228|;|PageNotFound|;|No mapping found for HTTP request with URI [/SpringMVCDemo/theme/buttons.css] in DispatcherServlet with name 'mvc-dispatcher' 
08/18/2015 22:15:19.249|;|PageNotFound|;|No mapping found for HTTP request with URI [/SpringMVCDemo/img/banner_1.jpg] in DispatcherServlet with name 'mvc-dispatcher' 
08/18/2015 22:15:19.312|;|PageNotFound|;|No mapping found for HTTP request with URI [/SpringMVCDemo/theme/tab_support.css] in DispatcherServlet with name 'mvc-dispatcher' 
08/18/2015 22:15:19.328|;|PageNotFound|;|No mapping found for HTTP request with URI [/SpringMVCDemo/resources/img/fitiGroupWebView_LogoV2.gif] in DispatcherServlet with name 'mvc-dispatcher' 
08/18/2015 22:15:19.343|;|PageNotFound|;|No mapping found for HTTP request with URI [/SpringMVCDemo/img/f_cglogo11.gif] in DispatcherServlet with name 'mvc-dispatcher' 
08/18/2015 22:15:19.359|;|PageNotFound|;|No mapping found for HTTP request with URI [/SpringMVCDemo/resources/script/login.js] in DispatcherServlet with name 'mvc-dispatcher' 
08/18/2015 22:15:21.241|;|PageNotFound|;|No mapping found for HTTP request with URI [/SpringMVCDemo/img/spacer.gif] in DispatcherServlet with name 'mvc-dispatcher' 
08/18/2015 22:15:21.867|;|PageNotFound|;|No mapping found for HTTP request with URI [/SpringMVCDemo/resources/img/globe_background.jpg] in DispatcherServlet with name 'mvc-dispatcher' 

при РМКО определении пути ресурсов в MVC-диспетчерская-servlet.xml IAM получаю ошибку ниже

HTTP Status 404 - 


type Status report 

message 

description The requested resource is not available. 

-------------------------------------------------------------------------------- 

Apache Tomcat/8.0.20 

в консоли, как 08/18/2015 22:32:23.817|;|PageNotFound|;|No mapping found for HTTP request with URI [/SpringMVCDemo/] in DispatcherServlet with name 'mvc-dispatcher'

Я пробовал с изменением url-pattern

<url-pattern>/</url-pattern> 

to 

<url-pattern>/*</url-pattern> 

но без успеха.

Может кто-нибудь, пожалуйста, помогите мне IAM ударили

+1

Вы слишком сложны. Сначала разделите его без ссылки на базу данных, чтобы другие могли попытаться скомпилировать и протестировать его. Во всяком случае, вы используете один и тот же файл xml для контекста Spring root и контекста mvc. ** Никогда не делайте этого **. Вы будете получать разные экземпляры bean-компонента в каждом контексте и никогда не будете уверены в том, что будет использоваться. –

+0

Я использую тот же XML-файл для контекста Spring root и контекста mvc. не могли бы вы привести мне пример, чтобы я мог различать два разных xml. – Learner

+0

Вы явно инициализируете свой корневой контекст с помощью 'mvc-dispatcher-servlet.xml'. И ваш сервлет называется 'mvc-dispatcher' и не имеет явного параметра' ContextConfigLocation', поэтому он ищет файл 'mvc-dispatcher-servlet.xml' для инициализации дочернего контекста. Таким образом, все бобы, объявленные в этом файле, заканчиваются как корневым, так и дочерним контекстом. –

ответ

0

Вы должны отобразить ресурсы в весенней конфигурации mvc-dispatcher-servlet.xml. Есть два способа сделать это:

  1. Сначала объявить

    <mvc:default-servlet-handler/>

  2. Во-вторых, использовать

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

и т.д.для каждой папки ресурсов (/resource/img/, /img/, /theme/, /resources/img/, /resources/script/)

+0

Я внес изменения, как предлагалось \t \t или \t \t .... \t нет прогресса, пока я получаю HTTP-статус 404 -/SpringMVCDemo/на этот раз нет консольных журналов – Learner

0

почему бы не попробовать добавить корневой контекст вашего примера имя изображения и не забудьте карту свои ресурсы, как Геннадию сказал

стиль = "фоновое изображение: URL ('SpringMvcDemo/ресурсы/IMG/globe_background.jpg ');»

надеюсь, что это помогает

0

Просто удалите шаблон URL "* .html" от отображения сервлета. Надеюсь, это решит проблему.

<servlet-mapping> 
     <servlet-name>mvc-dispatcher</servlet-name> 
     <url-pattern>/</url-pattern> 
</servlet-mapping> 
+0

Извините, я попытался удалить шаблон, но все равно не увенчался успехом .... я не понимаю, почему после включения ресурсы, которые он выбросит Http 404 Error .., но когда я закомментирую ресурсы страница будет загружаться без изображений :( – Learner

Смежные вопросы