1

Spring MVCでのリクエストマッピングを理解しようとしています。アプリケーションがあります。実際、SpringMVCを使い始めたばかりです。

私はこれらの2つのURLを持っています

最後にスラッシュが付いている最初のものは正常に機能しているようです。 http://localhost:8080/contactmanager/index/

最後にスラッシュがない2番目のものは機能しません

http://localhost:8080/contactmanager/index

この2つ目は、「HTTPステータス404-」エラーを表示します。URLの最後にスラッシュを追加するようにアプリケーションを強制するにはどうすればよいですか?

コントローラのメソッドは次のようになります

@RequestMapping("/index")
public String listContacts(Map<String, Object> map) {

    map.put("contact", new Contact());
    map.put("contactList", contactService.listContact());
    //org.springframework.web.context.ContextLoaderListener
    //org.springframework.web.context.ContextLoaderListener
    //org.springframework.web.servlet.DispatcherServlet
    //org.springframework.web.servlet.DispatcherServlet
    return "contact";
}

私のweb.xmlは次のようになります

<servlet>
    <servlet-name>contactmanager</servlet-name>
    <servlet-class>
        org.springframework.web.servlet.DispatcherServlet
    </servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/contactmanager-servlet.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>contactmanager</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

前もって感謝します。

4

1 に答える 1

2

Java構成の使用:

@Configuration
@EnableWebMvc
public class WebConfig {}

または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:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="
    http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc.xsd">

<mvc:annotation-driven />

Springのリファレンスドキュメントから:

上記は、@ RequestMapping、@ ExceptionHandlerなどのアノテーションを使用したアノテーション付きコントローラーメソッドでのリクエストの処理をサポートするために、RequestMappingHandlerMapping、RequestMappingHandlerAdapter、およびExceptionHandlerExceptionResolver(とりわけ)を登録ます。

RequestMappingHandlerMapping有用なブールフラグがあります-Javadocからの説明:

/**
 * Whether to match to URLs irrespective of the presence of a trailing slash.
 * If enabled a method mapped to "/users" also matches to "/users/".
 * <p>The default value is {@code true}.
*/
public void setUseTrailingSlashMatch(boolean useTrailingSlashMatch) {
   this.useTrailingSlashMatch = useTrailingSlashMatch;
}

これはデフォルトで有効になっているため、構成でがを使用していることを確認してくださいRequestMappingHandlerMapping

これで問題が解決しない場合は、Springのデフォルトサーブレットが構成されていることを確認してください<mvc:default-servlet-handler/>web.xml

<!-- Disables Servlet Container welcome file handling. Needed for compatibility with   Servlet 3.0 and Tomcat 7.0 -->
<welcome-file-list>
   <welcome-file></welcome-file>
</welcome-file-list>
于 2013-03-01T08:26:33.097 に答える