evg02gsa3
evg02gsa3

Reputation: 591

Spring framework <form:form> how does it generate the action attribute?

I'm using <form:form> on a JSP page in with Spring framework. When I look at the generated page, I see <form action="[the path of my page]">.

action="[the path of my page]" is added automatically.

I could theoretically manually edit each <form> to add the action="" desired attribute (edit: using something like ${root} in gerrytan's answer), but that would not be a practical option.


Edit: I cannot assume / to be the root path because it will be constantly changing since it's behind a proxy.)


How can I alter this automatic "behavior", so I concatenate a path at the beginning of [the path of my page]?

Upvotes: 0

Views: 334

Answers (2)

gerrytan
gerrytan

Reputation: 41123

Below are 2 common approaches I've seen being used along with their pros and cons:

Always assume the context path is /

You would put <form:form action="/controller1/path1". The benefit of this approach is the URL always refer to consistent place regardless of what path used to serve the page. However this implies your app is deployed into / context path. If you had to change this (eg: due to reverse proxy / load balancer) then you'd have to do tons of find / replace

Always lookup the context path using implicit variable

This is my preferred approach. First define a jsp variable like this:

<c:set var="root" value="${pageContext.request.contextPath}"/>

And whenever you have to refer to an internal path, use ${root}

<form:form action="${root}/controller1/path1" ...

The cons of this approach is the variable ${root} have to be declared on every single page. But when you change the context root rest assured all your references are still correct

You can also use <spring:url> or <c:url> as an alternative to this, or even better use HandlerInterceptor to make the root attribute available automatically on all views

Edit It seems ${pageContext.request.servletPath} is what you're looking for

Upvotes: 2

evg02gsa3
evg02gsa3

Reputation: 591

I will manually alter all form as and I will populate ${fullPathUrl} in some kind of filter method that gets called before every JSP page.

Upvotes: 0

Related Questions