I am trying to get the parameter inside a post request in Spring. I have used both the annotation (#RequestParam) and also the getParam method, but none of them work for me. Same code is able to get the parameters when I send them by URL (?input=input). Can anyone help me with this? Here is my code that handles the request:
#RequestMapping(value ="/this",method = RequestMethod.POST)
public String receiver(HttpServletRequest request,#RequestParam(value="input") String input, Model model){
String input2 = request.getParameter("input");
model.addAttribute("input",input);
return "test";
}
Right now the code uses the annotation to take the input. If I change the model.attribute("input",input) to model.attribute("input",input2) then I would be using the get attribute method. Both work fine when I pass the parameter with the URL but when I pass the parameter using POST form none of them work.
And here is the view. it just prints the input parameter from the model:
<!DOCTYPE http>
<html>
<body>
test
${input}
</body>
</html>
I finally found my answer. I did not know about different types of POST requests. All I needed to do was to enable multipartResolver to be able to get "multipart/form-data". I was not aware that the Request mapping by default does not take POST of type "multipart/form-data". If you want to use multipartResolver here is the documentation.
Related
I want to display that list in json format. When I run this code, it does not display any data in json format but gets in other format. How to display that list?
Controller class
#Controller
public class RoomController {
#RequestMapping(method = RequestMethod.GET)
public ModelAndView saveEmployee(){
System.out.println("welcome");
return new ModelAndView("NewFile","message","hello");
}
#RequestMapping(value="ViewMember",method=RequestMethod.GET)
public #ResponseBody List<RoomMembers> getRoomMembers() {
System.out.println("second test");
List<RoomMembers> roomMemberList= new ArrayList<RoomMembers>();
roomMemberList=roomDao.listMember();
return roomMemberList;
}
Jsp file is
<head>
<title>Spring MVC Ajax Demo</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script type="text/javascript">
function doAjax() {
$.ajax({
url: '/RoomController/ViewMember',
type: 'GET',
success: function(data) {
var roommember=JSON.parse(data);;
$('#time').html(roommember);
}
});
}
</script>
</head>
<body>
<button id="demo" onclick="doAjax()" title="Button">Get the time!</button>
<div id="time">
</div>
</body>
It seems you are requesting the wrong url. In the script in your jsp, the url passed do $.ajax() is url /RoomController/ViewMember.html. But in your controller you have mapped ir as simply 'ViewMember'
#RequestMapping(value="ViewMember",method=RequestMethod.GET,headers="Accept=application/json")
Try requesting just /RoomController/ViewMember and let's us know wether it works or not.
EDIT:
You say that .html url gets called and that you are using Spring 4.0.6, and that you get a HTTP 406 (NOTACCEPTABLE) response.
First check if you are sending Accept header as "application/json". But you won't be able to receive an HTTP 200 with json response in a controller mapped with ".html"/".htm" in a Spring MVC Controller with Spring 3.2 or above. From https://stackoverflow.com/a/39479308/4190848:
As of Spring 3.2+, the content negotiation has other facts in account prior to eval Accept header:
From https://spring.io/blog/2013/05/11/content-negotiation-using-spring-mvc:
Enabling Content Negotiation in Spring MVC
Spring supports a couple of conventions for selecting the format
required: URL suffixes and/or a URL parameter. These work alongside
the use of Accept headers. As a result, the content-type can be
requested in any of three ways. By default they are checked in this
order:
Add a path extension (suffix) in the URL. So, if the incoming URL is something like http://myserver/myapp/accounts/list.html then HTML
is required. For a spreadsheet the URL should be
http://myserver/myapp/accounts/list.xls. The suffix to media-type
mapping is automatically defined via the JavaBeans Activation
Framework or JAF (so activation.jar must be on the class path).
A URL parameter like this: http://myserver/myapp/accounts/list?format=xls. The name of the
parameter is format by default, but this may be changed. Using a
parameter is disabled by default, but when enabled, it is checked
second.
Finally the Accept HTTP header property is checked. This is how HTTP is > actually defined to work, but, as previously mentioned, it
can
be problematic to use.
That actually means that if you map a #Controller method with a
.htm(l) suffix, it is intended to return html and won't return
json nor any other format even if you sent other format as Accept
header.
...
So change your mapping to other suffix than ".html"/".htm" (or use no suffix) and you will solve your error
the url in ajax is wrong,you should write "ViewMember".
I have the following code:
<c:forEach var="listValue" items="${upcomingMovieslists}">
div style="border:thin inset #6E6E6E; text-align: justify;> <p margin-left: 1em;"> <c:set var="movieName" scope="application" value="${listValue.key}"/><a href="/myapp/movie/SubmitMovie/" >${listValue.key}</a></p></div>
</c:forEach>
and movieName is going to be in #RequestParam String movieName in the page that it is going next.
So, When I run this code I am getting an error telling:
error:
message Required String parameter 'movieName' is not present
description The request sent by the client was syntactically incorrect.
Controller method:
My controller class to where the call is going:
#RequestMapping(value="/SubmitMovie", method = RequestMethod.GET)
public ModelAndView getSearchedMovie(#RequestParam String movieName, ModelMap model)
The URL currently is: /myapp/movie/SubmitMovie/
It should be /myapp/movie/SubmitMovie/?movieName=deadpool
in order to work
I should have /?movieName= to show the results in the next page but where as with the above jsp code I will not get the movieName in String format instead it comes in the form ${movieName} which cannot be accepted to a String present in the RequestParam and hence it throws an error.
I want to know how I can fix it to get the moviename in Stringformat in the URL so that I can populate the results
Thanks
There's not a whole lot of code there, so I don't know exactly what you're going for, but you can always add a required=false condition to a request parameter, like so:
#RequestParam(value = "movieName", required = false) String movieName
That should at least clear that error. If the logic in your model does require movieName, though, then you're going to need to refactor around that -- i.e., your link would need to look like href="/myapp/movie/SubmitMovie?movieName='${listValue.key}'" .
(Note: I'm inferring from your code that ${listValue.key} is the name of the movie. Whatever variable you want the controller to receive as the #RequestParam String movieName, place it after ?movieName= in the href string, after escaping it with single quotes (see how I did so above.)
If you're still stuck, maybe try showing the controller for the page with that parameter?
I have a URL say abc.com/somecontroller?someparam=1 which renders a form. Form on submit sends the form params to /ajaxAction
Is there a way I could get this abc.com/somecontroller?someparam=1 (i.e. the form URL?)
I am more interested in getting the someparam value from the URL of the form.
PS: the above URL abc.com/somecontroller?someparam=1 is dynamically generated, so I can not access it otherwise.
And request.forwardURI will give me /ajaxAction (i.e. the URL of the action in form and not the url of the form itself).
EDIT:
I have no control over form as it is also dynamic and user has hundreds of templates to select from. Each template has different no. of fields.
So if I would prefer some other way to get the URL.
Why don't you use javascript in form and add to ajax request array with GET params? (or with the url of the action which generated form)
You can get them from original request f.e. by this script.
While rendering the GSP of your form, you can do like this:
myaction.gsp
<html>
<body>
<!-- Your content -->
<script>
var paramsString = '${params.collect { k, v-> "$k=$v" }.join("&") }';
</script>
</body>
</html>
So, when you GSP is rendered, the script tag will have something like this (for a URL abc.com/somecontroller?someparam=1&foo=2:
var paramsString = 'someparam=1&foo=2';
Now, in your AJAX code, you can pass that string as the query arguments:
$.ajax({
url: '/ajaxAction?' + paramsString
/* rest of the AJAX code */
});
Now, in your ajax controller action, you can simply do the params.someparam.
EDIT
Well, I just realized that you don't have to any GSP stuff I mentioned above. Simply do the AJAX call like this:
$.ajax({
url: '/ajaxAction' + location.search
/* rest of the AJAX code */
});
The location.search will give you the direct string: ?someparam=1&foo=2
I ended up using flash to store the someparam
In my controller which is being used to render the form at abc.com/somecontroller?someparam=1 I use flash as this:
flash.put("someparam", params.someparam)
This worked as a quick workaround to the issue. I feel this would work well in situations where I have no control over the gsp.
If anyone finds any issue, please comment otherwise I will mark this as the answer.
I need to implement a servlet that uploads files to a server, I realize everyone says it has to be a POST method in regard to uploading files and not with GET method. However is there a way to upload a file and have the parameters of the request show up in the url even if the request is coming from POST method? If not, is there another approach?
Currently my servlet using post method is http://example.com/FileUpload/UploadFile
What I want is somehting like http://example.com/FileUpload/UploadFile?id=125&fileNum=5
Thanks for your input.
Simply POST to
http://example.com/FileUpload/UploadFile?id=125&fileNum=5
instead of
http://example.com/FileUpload/UploadFile
There is no such restriction that you cannot post to an URL having parameters. You can process the post data as you are doing now, plus, you can get the get parameters also.
I think it would not be an elegant solution, but you could use JavaScript to alter the action of the form element before submitting it to include querystring parameters.
The form will be something like:
<form method="POST" id="myForm" onSubmit="submitMyForm(this)>
<input type="text" id="id">
Then you will need JavaScript to change the action element of the form:
function submitMyForm(theForm) {
theForm.action="http://example.com/FileUpload/UploadFile?id=" +
getElementById("id").value;
theForm.submit();
}
Is there some reason you cannot just submit the parameters with post and pull them out on the server side?
Alternatively, if you do a multipart/form-data post you can include multiple parameters along with your file. The parameters are sent as part of the post body, along with the file.
You can send parameters and files in the POST. For example in the html you can have a form with this values, they can be of hidden type.
In the servlet you can get the values in the same way you do using the GET.
It is also better to use the POST method because the user can't change the value in the URL direction bar.
Is it possible to call a spring controller from javascript included in a jsp?
I'm trying to call it like this:
form.action='${pageContext.request.contextPath}/spring/myController';
I can see that the control passes throught the lines, but nothing is happening.
Also I get messages like get or post is not supported.
when I submit the form with a post method I get error message post is not supported.
I use the annotations like this in controller.
#RequestMapping(method = RequestMethod.GET)
How can I handle both get and post in spring controllers?
Your javascript is not actually calling anything. Rather, it is setting the "action" attribute of (I assume) a <form> element in your web page to some URL assembled by the JSP. The "call" to your server will happen later ... when the user clicks some button that causes the form to be submitted.