Spring 4:如何将RequestMapping的URL映射到特定的控制器

6

我写了一个包含多个控制器的Spring MVC应用程序。

在JSP上,我在表单中使用了action

 <form id="createTableForm" method="post" name="createTable" action="${pageContext.request.contextPath}/saveTable" >

同时,相同的操作被映射到控制器中的一个方法:

@Controller
public class TableController implements TableConstants {

  @RequestMapping(value="/saveTable")
  public String saveTable(HttpServletRequest request,RedirectAttributes redirectAttributes) {
  //...
  }
}

在我的web.xml中:

  <context-param>
    <description>Context name of the Application</description>
    <param-name>contextName</param-name>
    <param-value>W****</param-value>
</context-param>
<context-param>
    <description>Database used for</description>
    <param-name>databaseName</param-name>
    <param-value>w*****</param-value>
</context-param>

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

<filter>
    <filter-name>FilterChainProxy</filter-name>
    <filter-class>com.abc.w****.configuration.FilterChainProxy
    </filter-class>
</filter>
<filter-mapping>
    <filter-name>FilterChainProxy</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

<session-config>
    <session-timeout>1</session-timeout>
</session-config>


<jsp-config>
    <taglib>
        <taglib-uri>http://displaytag.sf.net</taglib-uri>
        <taglib-location>/WEB-INF/tld/displaytag.tld</taglib-location>
    </taglib>
</jsp-config>

我需要将特定控制器的URL映射包含在web.xml文件中还是WebAppConfig类中?

我已经在WebAppConfig上注释了@Configuration、@ComponentScan和@EnableWebMVC。它有以下方法:

 public UrlBasedViewResolver setupViewResolver() {
 }
 public MessageSource messageSource() {
 }
 public void addResourceHandlers(ResourceHandlerRegistry registry) {
 }
 public CommonsMultipartResolver multipartResolver() { 
 }

请给予建议。

那么你想要实现特定控制器也有自己的URL映射吗? - Branislav Lazic
我想知道正确的方法,因为我的Controller类只是用@Controller注解进行了标注。因此,我们应该向Controller类提供URL映射,并将该映射附加到JSP中的action上,同时使用RequestMapping URL。 - user3403462
请发布您的servlet-config.xml文件。 - Chetan Verma
1
在控制器中添加RequestMapping注解。 - Stefan
你的问题不是很清楚。你想让你的控制器拥有一个URL,这样你的请求URL“/saveTable”就变成了“/foo/saveTable”? - dustin.schultz
2个回答

1

@RequestMapping注解可以应用于控制器类。在这种情况下,该类中的所有方法将从类注解中派生默认值,实现可以覆盖它。


0

你需要做几件事情

  1. 在web.xml中配置Spring的DispatcherServlet来拦截请求并将其定向到Controllers。例如,要将DispatcherServlet映射到根目录的请求,请添加以下行:

    <servlet>
        <servlet-name>mvc-dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    
    <servlet-mapping>
        <servlet-name>mvc-dispatcher</servlet-name>
        <url-pattern>/*</url-pattern>
    </servlet-mapping>
    
  2. 确保在bean定义xml中,您已经配置了组件扫描,扫描包含您的控制器的包,以便Spring容器可以发现它们。


不需要使用web.xml,这个人正在使用注释进行配置。请查看http://docs.spring.io/autorepo/docs/spring-framework/3.1.x/javadoc-api/org/springframework/web/WebApplicationInitializer.html 并执行相同的操作。 - Darryl Miles

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接