用于匹配所有URL的Servlet URL模式

时间:2015-11-25 15:10:39

标签: spring jsp web.xml url-pattern

我目前正在使用Spring MVC来完成一个项目。我有问题使用url-pattern来指导我的jsp页面。每次我创建一个新的jsp页面时,我都必须将jsp名称硬编码到web.xml中。

的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" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
  <display-name>ShoppingCart</display-name>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>

<!-- Once DispatcherServlet is initialized will look for file name [servlet-name]-servlet.xml, dispatcher-servlet.xml -->
<servlet>
    <servlet-name>dispatcher</servlet-name>
    <servlet-class>
        org.springframework.web.servlet.DispatcherServlet
    </servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>

 <!-- all request matches with <url-pattern> will be handled by DispatcherServlet instance named dispatcher -->
<servlet-mapping>
    <servlet-name>dispatcher</servlet-name>
    <url-pattern>/register.jsp</url-pattern>
    <url-pattern>/login.jsp</url-pattern>        
    <url-pattern>/update.jsp</url-pattern>        
</servlet-mapping>

</web-app>

下面的图片是我的文件夹结构

folder structure

1 个答案:

答案 0 :(得分:2)

url-mapping上指定您的servlet常规web.xml,然后在您的控制器上处理其子URLS

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

InternalResourceViewResolver

上配置dispatcher-context.xml bean
<beans:bean
    class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <beans:property name="prefix" value="/WEB-INF/views/" />
    <beans:property name="suffix" value=".jsp" />
</beans:bean>

在您的控制器上:

@Controller
@RequestMapping("/")
public class ControllerRegister{

  @RequestMapping("register") 
  public String goToRegisterPage(){
      return "register";
  }

}

这将在register.jsp文件夹WEB-INF/views/下方URL投放http://yourHost:port/yourApp/register

{{1}}