Spring RequestMapping to read encoded &amp - java

I'm trying to get a RequestMapping to pick up the following url pathname.
action?param1=6&param2=b&param3=true&param4=50652&param5=2
I'm able to get the path below to work. However when converting & to '& amp;' I am unable to read any parameters.
action?param1=6&param2=b&param3=true&param4=50652&param5=2
Method for action
#RequestMapping(value = "/action", method = RequestMethod.GET)
public ModelAndView doAction(HttpServletRequest httpRequest, HttpServletResponse httpResponse)
throws Exception {
log.info(httpRequest.getParameter("param1"));
}
FYI
I want to steer clear of any string manipulations

Related

Xml tags printing differently in Restcontroller

I am using a controller for post mapping in spring
#PostMapping(value ="/HttpNoRespAdapter",consumes = { MediaType.APPLICATION_FORM_URLENCODED_VALUE, MediaType.APPLICATION_XML_VALUE}, produces=MediaType.APPLICATION_XML_VALUE)
protected String process(#RequestBody String request, HttpServletResponse response) {
}
I am taking whatever coming in the requestbody as string, the following xml should come
<REQ><FEATURE>DELIVERY-RECEIPT</FEATURE><TIME-STAMP><![CDATA[20200925190730]]></TIME-STAMP><TRANSACTION-ID><![CDATA[71554]]></TRANSACTION-ID><SMPP-ID><![CDATA[airtel]]></SMPP-ID><COMMAND-ID><![CDATA[5]]></COMMAND-ID><OA><![CDATA[8407600010]]></OA><DA><![CDATA[555]]></DA><DCS><![CDATA[0]]></DCS><SMS><![CDATA[stat:DELIVRD err:000 Text:silent]]></SMS><MESSAGE-ID><![CDATA[19]]></MESSAGE-ID></REQ>
But it coming as
%3CREQ%3E%3CFEATURE%3EDELIVERY-RECEIPT%3C%2FFEATURE%3E%3CTIME-STAMP%3E%3C%21%5BCDATA%5B20201007175019%5D%5D%3E%3C%2FTIME-STAMP%3E%3CTRANSACTION-ID%3E%3C%21%5BCDATA%5B60564%5D%5D%3E%3C%2FTRANSACTION-ID%3E%3CSMPP-ID%3E%3C%21%5BCDATA%5Bairtel%5D%5D%3E%3C%2FSMPP-ID%3E%3CCOMMAND-ID%3E%3C%21%5BCDATA%5B5%5D%5D%3E%3C%2FCOMMAND-ID%3E%3COA%3E%3C%21%5BCDATA%5B8007600010%5D%5D%3E%3C%2FOA%3E%3CDA%3E%3C%21%5BCDATA%5B555%5D%5D%3E%3C%2FDA%3E%3CDCS%3E%3C%21%5BCDATA%5B0%5D%5D%3E%3C%2FDCS%3E%3CSMS%3E%3C%21%5BCDATA%5Bid%3A69+sub%3A001+dlvrd%3A001+submit+date%3A2010071750+done+date%3A2010071750+stat%3ADELIVRD+err%3A000+Text%3Asilent%5D%5D%3E%3C%2FSMS%3E%3CMESSAGE-ID%3E%3C%21%5BCDATA%5B69%5D%5D%3E%3C%2FMESSAGE-ID%3E%3C%2FREQ%3E=
the xmltags are been replaced wrongly. how can i rectify this??
Try to use java.net.URLDecoder:
request = URLDecoder.decode(request, "UTF-8");

Receiving a MultiPart file and JSON data using Spring and AngularJS

Here's my controller below:
#RequestMapping(value="/upload", method=RequestMethod.PUT)
public ResponseEntity<String> handleFileUpload(
#RequestParam("file") MultipartFile file,
#RequestParam("data") String campaignJson,
Principal principal) throws JsonParseException, JsonMappingException, IOException {
I want to be able to receive a MultipartFile as well as a JSON string containing data associated to the file (title, description, etc).
I can get MultipartFile uploading to work on it's own, and I can receive a JSON string and parse it on its own, but when I have them together in 1 controller, it fails. Whenever I print out the String campaignJson it says [object Object] instead of the data that I'm sending (when I print out the data being sent in angular, it's in correct JSON format.)
I've tried #RequestBody, #RequestParam, #RequestPart, but to no avail.
My question is: How do I receive both a MultipartFile and data in the form of JSON in one Spring controller?
This worked for me :
#RequestMapping(value = "/{id}/upload", method = RequestMethod.PUT)
public DocumentResource uploadPut(#PathVariable("id") Long id,
MultipartHttpServletRequest request,
HttpServletResponse response) {
String next = request.getFileNames().next();
MultipartFile file = request.getFile(next);
.....
}
Edit :
Using the MultipartHttpServletRequest should not limit you in any way to use other #PathVariables or #RequestParams, so passing title and description should be possible.
I used it to upload multiple images with AngularJS and FileUploader
( angular-file-upload v1.1.5 )
like this
var uploader = new FileUploader({
url: config.apiUrl('/machine/' + $scope.id + '/images/'),
method: "post",
queueLimit: maxFiles
});

Form submit, doesn't call spring controller correctly

I am submitting a form using jquery in my Spring mvc.
this is the jquery call to submit form.
function uploadJqueryFormForEdit(documentId){
alert("ccc");
$('#result').html('');
$("#editDocumentForm").ajaxForm({
success:function(data) {
alert("ddd");
$('#result').html(data);
alert("eee");
//getProjectSegment('documents','DocumentSegment',projectId);
$('#editDocumentForm').remove();
},
error:function(e){
alert(e.responseText);
$("#msgDiv").html('Error');
},
dataType:"text"
}).submit();
}
And this is the form that I'm going to submit.
<form action="cont/uploadEdit?documentId=15&projectId=2" name="editDocumentForm" id="editDocumentForm" enctype="multipart/form-data" method="post">
When i'm using one parameter in action url, eg.
action="cont/uploadEdit?documentId=15"
it works fine. but when i'm using two parameters as
action="cont/uploadEdit?documentId=15&projectId=2"
it doesn't call to controller method correctly(not hitting that method at all)
here is the controller method
#RequestMapping(value = "cont/uploadEdit", method = RequestMethod.POST)
public #ResponseBody String uploadEdit(#ModelAttribute("sessionId") String sessionId,#RequestParam("documentId") int documentId,#RequestParam("projectId") int projectId,MultipartHttpServletRequest request, HttpServletResponse response, UploadedFile fileDetail,UserBean userbean,Model model) throws SessionException {
logger.info("uploadEdit");
}
why can't I use two parameters in action tag.?
this is the controller method that worked fine with first action
#RequestMapping(value = "cont/uploadEdit", method = RequestMethod.POST)
public #ResponseBody String uploadEdit(#ModelAttribute("sessionId") String sessionId,#RequestParam("documentId") int documentId,MultipartHttpServletRequest request, HttpServletResponse response, UploadedFile fileDetail,UserBean userbean,Model model) throws SessionException {
logger.info("uploadEdit");
}
Add params = {"documentId", "projectId"} attribute to the RequestMapping annotation
#RequestMapping(value = "cont/uploadEdit", params = {"documentId", "projectId"}, method = RequestMethod.POST)
public #ResponseBody String uploadEdit(#ModelAttribute("sessionId") String sessionId,#RequestParam("documentId") int documentId,#RequestParam("projectId") int projectId,MultipartHttpServletRequest request, HttpServletResponse response, UploadedFile fileDetail,UserBean userbean,Model model) throws SessionException {
logger.info("uploadEdit");
found the error:
In the form that we are going to submit (in my case "editDocumentForm") there should be no any other input tags with the same name as in action url variables,
eg if there is something like this,
<input type="hidden" id="projectId" name="projectId" value="somevalue"/>
it will make conflicts. So make sure that no conflicts occur.

Handling both Multipart and non-multipart HTTP POSTs in Spring MVC

I have a SpringMVC web service for uploading files which looks like this:
#RequestMapping(value="/upload.json", method = RequestMethod.POST)
public #ResponseBody Map<String, Object> upload(MultipartHttpServletRequest request) {
// upload the file
}
and everything is dandy. But if one of the consumers posts a non-multipart form, then i get this exception
java.lang.IllegalStateException: Current request is not of type [org.springframework.web.multipart.MultipartHttpServletRequest]
Which makes sense.. however I dont want my end users to see 500 servlet exceptions. I want a friendly error message.
I just tried this (to be like a catchall for other POSTs):
#RequestMapping(value="/upload.json", method = RequestMethod.POST)
public #ResponseBody Map<String, Object> upload2(){
// return friendly msg
}
but I get this error:
java.lang.IllegalStateException: Ambiguous handler methods mapped for HTTP path '/upload.json'
Is there any way to safely handle both multipart and non-multipart POST requests? in one method, or 2 different methods i dont care.
Check if the request is a multipart yourself:
#RequestMapping(value="/upload.json", method = RequestMethod.POST)
public #ResponseBody Map<String, Object> upload(HttpServletRequest request) {
if (request instanceof MultipartHttpServletRequest) {
// process the uploaded file
}
else {
// other logic
}
}

Insert info into an HTTP header

I’m trying to add some data to the http header that comes back from a RESTful web service call. Is it possible to use JAX-RS or something else to add data to the response header?
Example of my method:
#GET
#Path("getAssets")
public List<Asset> getAssets(#QueryParam("page") #DefaultValue("1") String page,
#QueryParam("page_size") #DefaultValue(UNLIMITED) String pageSize) throws Exception
{
stuff…
}
Thanks for your help.
Using something such as Spring's MVC controller, you can easily get and set response headers as in the below example. A list of common headers can be found here Wikipedia - Common Headers
...
#RequestMapping(method = RequestMethod.GET)
public String myGetMethod(#PathVariable string owner, #PathVariable string pet, HttpServletResponse response) {
response.setContentType("text/html");
response.setHeader("Content-disposition","Content-Disposition:attachment;filename=fufu.png");
}
...

Categories

Resources