使用Spring MVC在JSP中设置HTML链接

时间:2016-08-04 20:31:50

标签: java spring jsp spring-mvc

我在Spring MVC textbox example上尝试教程。运作良好,但我不知道处理链接的名称。

唯一有效的是http://localhost:8080/SpringMVC/textbox.html,我不知道如何将textbox.html部分更改为其他任何内容。

根据评论和关于我的所有信息,我意识到它是根据控制类命名的。

  

TextBoxController.java - > textbox.html

以下是相关代码:

的web.xml

<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>*.html</url-pattern>
</servlet-mapping>

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/mvc-dispatcher-servlet.xml</param-value>
</context-param>

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

MVC-调度-servlet.xml中

<bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping" />

<bean class="nch.customer.controller.TextBoxController">
    <property name="formView" value="CustomerForm" />
    <property name="successView" value="CustomerSuccess" />
    // Anything to put here?

    <property name="validator">
        <bean class="nch.customer.validator.CustomerValidator" />
    </property>
</bean>

TextBoxController.java

public class TextBoxController extends SimpleFormController {

public TextBoxController() {
    setCommandClass(Customer.class);
    setCommandName("customerForm");
    // Or anything to put here?
}

@Override
protected ModelAndView onSubmit (
    HttpServletRequest request, HttpServletResponse response, 
    Object command, BindException errors) throws Exception {

    Customer customer = (Customer) command;
    return new ModelAndView("CustomerSuccess","customer",customer);
}

我的问题是。如何更改链接名称而不更改类的名称?例如:

  

TextBoxController.java - &gt; txb.html

1 个答案:

答案 0 :(得分:3)

这个bean ControllerClassNameHandlerMapping正在进行转换 TextBoxController -> /textbox*

使用此配置,textbox.htmltextboxxx.html都可以使用。

  

...取得Class的短名称,删除'Controller'后缀(如果存在)并返回剩下的文本,lower-cased,作为映射,带有前导/.

<bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping" />

将其替换为另一个bean SimpleUrlHandlerMapping,并在想要自定义路径时为id bean提供TextBoxController。您的mvc-dispatcher-servlet.xml将如下所示:

<bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
   <property name="mappings">
    <props>
       <prop key="/txb.html">txtboxController</prop>
     </props>
   </property>
</bean>

<bean id="txtboxController" class="nch.customer.controller.TextBoxController">
   <property name="formView" value="CustomerForm" />
   <property name="successView" value="CustomerSuccess" />
   <property name="validator">
      <bean class="nch.customer.validator.CustomerValidator" />
   </property>
</bean>