2013-11-21 83 views
1

我有一個web應用程序。我的控制器看起來是這樣的:錯誤的鏈接位置錯誤

@Controller 
@RequestMapping(value = "/") 
public class MainController {  

    @RequestMapping(method = RequestMethod.GET) 
    public String index() { 
     return "index"; 
    } 

    @RequestMapping(value = "/add", method = RequestMethod.POST) 
    public String add(ModelMap model, User user) { 
     userService.create(user); 
     model.addAttribute("message", "User successfully created."); 
     return "index"; 
    } 
} 

而且我有這樣一種形式:

<form:form method="POST" action="/add" commandName="user"> 

的web.xml

<servlet> 
    <servlet-name>client</servlet-name> 
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> 
    <load-on-startup>1</load-on-startup> 
</servlet> 

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

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

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

我的應用程序通過鏈接訪問:http://localhost:8080/Client
但是,當我提交表格提交至http://localhost:8080/add應該是http://localhost:8080/Client/add
我想,我可以在每個鏈接之前使用${pageContext.request.contextPath},但有沒有其他方法?

+1

讓我們看看'web.xml' – MariuszS

+0

哦,我想我得到了你的觀點:) – qiGuar

+0

尼斯:)回答補充:) – MariuszS

回答

2

試試這個:

<form:form method="POST" action="${requestContext.pathToServlet}/add" commandName="user"> 

瞭解更多:

相關的問題:

+0

也適用。看來,在春季3.2.3(我使用)這個選項被刪除,而他們做了'servletRelativeAction'標記,但是當我把它設置爲true仍然出錯,但用'$ {requestContext.pathToServlet}'工作正常。難道我做錯了什麼? – qiGuar

+0

也許'servletRelativeAction'用於[僅限portlet](https://github.com/spring-projects/spring-framework/commit/399f887128f2dc0dcaadb7b7df2826ce0b9dcf79)?我認爲'$ {requestContext.pathToServlet}'是推薦的方法。 – MariuszS

+0

我明白了,但如果回滾它,requestContext如何工作?或者我錯過了什麼? – qiGuar

3

使用c:url可將上下文根自動添加到您的URL。

<c:url var="formUrl" value="/add" /> 
<form:form method="POST" action="${formUrl}" commandName="user"> 
+0

是的,它的工作原理,但我會必須爲我擁有的每一個環節都做到這一點。有另一種方法嗎?如果有幫助,還添加'web.xml'。 – qiGuar

+0

這也可以:) – MariuszS