Spring MVC url-mapping

2019-08-06 14:11发布

问题:

I made a simple web application by Spring mvc.

I want to use these URL

  • /user
  • /user/{id}
  • /user/create
  • /user/edit/{id}

in web.xml

first case

<servlet-mapping> 
    <servlet-name>SpringMVC1</servlet-name> 
    <url-pattern>/</url-pattern> 
</servlet-mapping> 

It works well.
but I can not read http://localhost:8080/res/images/image.png - 404 error
in {my project path}/WebContent/res/images/logo.png

second case

<servlet-mapping> 
    <servlet-name>SpringMVC1</servlet-name> 
    <url-pattern>/*</url-pattern> 
</servlet-mapping> 

I can see image on http://localhost:8080/res/images/image.png but http://localhost:8080/user/create - 404 error

What's wrong??

回答1:

You need something like this in your XML:

<mvc:resources mapping="/res/**" location="/path/to/your/resources"/>

See 16.14.5. Configuring Serving of Resources



回答2:

more detail explain..

in my spring configuration xml file

i append

<mvc:resources mapping="/res/**" location="/path/to/your/resources"/>

it have to append next..

append to root node - beans

xmlns:mvc="http://www.springframework.org/schema/mvc"

and append to xsi:schemaLocation

http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd

and append mvc:annotation-driven node.

<mvc:annotation-driven />

It is my spring configuration xml

<?xml version="1.0" encoding="UTF-8"?>
<beans 
    xmlns="http://www.springframework.org/schema/beans"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:schemaLocation="http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans-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/context
            http://www.springframework.org/schema/context/spring-context-3.0.xsd">
    <context:component-scan base-package="com.test" />
    <bean id="viewResolver"
        class="org.springframework.web.servlet.view.UrlBasedViewResolver">
        <property name="viewClass"
            value="org.springframework.web.servlet.view.JstlView" />
        <property name="prefix" value="/WEB-INF/jsp/" />
        <property name="suffix" value=".jsp" />
    </bean>
    <mvc:annotation-driven />
    <mvc:resources mapping="/res/**" location="/res/" />
</beans>

It works well.
Thanks Sean Patrick Floyd.