开发者

How can I add a URL parameter but hide others in a POST - Spring MVC

开发者 https://www.devze.com 2023-03-06 00:13 出处:网络
I\'m trying to add a URL parameter within a Spring MVC application.It\'s a basic search page that shows results.

I'm trying to add a URL parameter within a Spring MVC application. It's a basic search page that shows results.

In the search page, there is a form that is set to POST. There are many hidden fields and other fields I don't want in the URL. So, I don't want to do a GET.

I do want the search query in the URL. So after clicking the search button, the resulting search results page needs to have a URL like /search?query=hello

To get it to work, I'm creating a RequestMapping method in the Spring MVC Controller and doing a redirect: tacking on the query parameter. However, I'm not sure using a redirect is the best answer, seems there could be performance concerns redirecting as well.

I looked around and noti开发者_StackOverflow中文版ced folks using javascript and the location object, but setting the location object obviously relaunches the URL you set it to. I also looked at the HTTPServletResponse & HTTPServletRequest objects, but couldn't find much.

Any thoughts on how I can force the search parameter to be added to the URL?


Your form will have an 'action' specified telling it where to POST to. I'd have thought you could attach an onclick event to your submit button (or an onsubmit event to your form) that updates the action url by appending "?query=" to it.

document.<form name>.action += "?query=...";

Then you just have to worry about someone posting your form without JavaScript enabled - in this case you could fall back to your redirect.

I don't know how the server technology so I can't say if it will be happy giving you both GET and POST parameters, if not you'll have to manually strip the GETs out of the URL.

But anyway, this seems like a rather odd situation to be in - is it really that big a deal to show the parameters in the URL? Anything that gets posted by an HTML form can still be inspected with the right tools, it's just ever so slightly more difficult.


I wanted to provide a more complete answer to my question with code. The previous user helped me down this path, so I'll keep it as the accepted answer. However, there is one item to note:

If you add on to the action, and you have an input text box with the same name, the page posts a duplicate value like: query=hello,hello.

So, I needed to remove the name on the input box, and use the following javascript. Note, I am using the prototype.js framework:

Event.observe(window, 'load', function(event) {

Event.observe('searchForm', 'submit', function(event) {     

    $('searchForm').action += "?query="+$('searchBox').value;

});
0

精彩评论

暂无评论...
验证码 换一张
取 消