My controller attaches a question mark at the end of a string. It works great for every types of string.
https://www.mywebsite.com/attachQuestionmark/33 returns 33?
https://www.mywebsite.com/attachQuestionmark/hello returns hello?
However it returns not found error for urls such as https:://www.test.com.
https://www.mywebsite.com/attachQuestionmark/https:://www.test.com returns 404 error.
Is there any way to pass a full url to spring mvc controller?
#RequestMapping(
value = MyUrlBuilder.API_CREATIVE_CREATE + "/attachQuestionmark/{string}",
method = RequestMethod.GET,
produces = MediaType.ALL_VALUE)
#ResponseBody
#PMET
public static String attachQustionmark(#PathVariable("url") String value)
{
return value + "?";
}
Try URL-encoding the path variable, eg:
https://www.mywebsite.com/attachQuestionmark/https%3A%3A%2F%2Fwww.test.com
Because otherwise the / inside the variable will be interpreted as another path
Related
I have the below code as my restful service operation.
#GET
#UnitOfWork
#Timed(name = "get-requests")
#Path("/{referenceId}")
public Response get(#Auth #ApiParam(access = "internal") UserPrincipal user,
#ApiParam(name = "id", value = "reference ID", required = true)
#PathParam("referenceId") String id) {
return Response.ok(id).build();
}
However, I noticed if I pass in m1234;5678, I get only m1234 returned. I tried #Path("/{referenceId:.*}"), but it doesn't work.
I also tried use #Encode at the top of the method to make sure the url is not decoded and then try to replace %3B with ";" in the code. But it seems not working also.
Please note that I cannot use Spring framework. Thanks.
The ; denotes a matrix parameter. Use #MatrixParam to get its value.
See also the answers to this question: URL matrix parameters vs. request parameters
Edit: The key of the matrix parameter would be 5678, the value would be null.
There is a way to get achieve what you want by using PathSegment as the type of the parameter instead of String:
#PathParam("referenceId) PathSegment id
In the body of the method, you can use
String idValue = id.getPath();
to get m1234;5678.
I have some problem with slashes in variable thats hould be send in url.
For example id could be like this:
ID: /gfdge1/DkxA8P+jYw43
URL: localhost:8080/find-user//gfdge1/DkxA8P+jYw43
"error": "Internal Server Error",
"exception": "org.springframework.security.web.firewall.RequestRejectedException",
"message": "The request was rejected because the URL was not normalized.",
because of this slash on first place it make problem
Before that i had problems with these slash in middle of ID but I've solved that with this code:
#RequestMapping(name = "Get user data by ID", value = "/find-user/{userId}/**", method = RequestMethod.GET)
#ResponseBody
public User getUserData(#PathVariable String userId, HttpServletRequest request) {
final String path =
request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE).toString();
final String bestMatchingPattern =
request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE).toString();
String arguments = new AntPathMatcher().extractPathWithinPattern(bestMatchingPattern, path);
String id="";
if (null != arguments && !arguments.isEmpty()) {
id = userId + '/' + arguments;
} else {
id = userId;
}
return userService.getUserData(id);
}
but this doesn't work for this case when slash is on first place.
I've also try to user RequestParam instead of PathVariable, but it have problems with some special characters for example when I user RequestParam it replace '+' with empty space,...
Does anyone can help me how to solve this problem?
Its an inherent issue with using Strings as path variables, it's not an issue with your code but how the HTTP request is interpreted so you can't do anything in your code to make this work.
You do have some options though:
Ensure the values you use cannot be created with special characters such as "/"
Avoid using Strings in path variables completely.
I lean more towards 2 as maintaining 1 for all possible problem characters/strings is pretty messy and unnecessary.
To do 2 correctly you should consider having all your REST getters finding their related entities by a numeric ID only e.g.
localhost:8080/find-user/3
If you need to add additional search parameters e.g. username in your case then you should use something like QueryDSL to create a predicate of search parameters which are passed as query parameters instead of path variables e.g.:
localhost:8080/find-user?username=/gfdge1/DkxA8P+jYw43
I am trying to implement datatable editor with spring boot ,but the client to server data varies for create ,update and delete even not constant for create as well and depends on fields
I have implemented this till now
#RequestMapping(value="/datatabledata" , method=RequestMethod.POST)
#ResponseBody
public String datatabledata(HttpServletRequest request)
{
Enumeration<String> params = request.getParameterNames();
while(params.hasMoreElements()){
String paramName = params.nextElement();
System.out.println("Parameter Name - "+paramName+", Value - "+request.getParameter(paramName));
}
//System.out.println(data);
//System.out.println(request.);
//Map<String,String>ak=new HashMap<>();
//ak.put("data", "hello ");
return "done";
}
Above code prints following output on console for create
Parameter Name - action, Value - create
Parameter Name - data[0][username], Value - dddddd
Parameter Name - data[0][date], Value - 2018-11-28
Parameter Name - data[0][balance], Value - dddddddddd
and this for edit
Parameter Name - action, Value - edit
Parameter Name - data[5bfab595507af613f409c0c4][username], Value - four
Parameter Name - data[5bfab595507af613f409c0c4][date], Value - 2018-11-25
Parameter Name - data[5bfab595507af613f409c0c4][balance], Value - 9000.0
The only constant parameter here is action and so I can use
#RequestParam("action")
but how to get rest data ?? something like #RequestParam() String data
You can create a DTO class which can be mapped from the request and can be used further.
#RequestMapping(value="/datatabledata" , method=RequestMethod.POST)
#ResponseBody
public String datatabledata(HttpServletRequest request)
{
UserDTO object = new ObjectMapper().setDateFormat(simpleDateFormat).readValue(request.getReader(), UserDTO.class);
performYourOperation(object);
}
I see we should utilize REST in more richer way here.
So create three different controller method handlling create, update and delete and maps them to difference HTTP methods like below :
//For Create. Take the parameter as (#RequestBody List<User>)
#RequestMapping(value="/datatabledata" , method=RequestMethod.POST)
//For Update/Edit, Take the parameter as (#RequestBody List<User>)
#RequestMapping(value="/datatabledata" , method=RequestMethod.PUT)
//For Delete, Just take either list of ids or id to be delete. Nothiing else required
#RequestMapping(value="/datatabledata" , method=RequestMethod.DELETE)
Now you don't need action as parameter. Client just need to specify the correct http method.
You should use #RequestParam Map<String,String> allRequestParams in your endpoint:
#RequestMapping(value="/datatabledata" , method=RequestMethod.POST)
#ResponseBody
public String datatabledata(#RequestParam Map<String,String> allRequestParams) {
/ ... rest of your code
}
I have a REST API like this:
#RequestMapping(value = "/services/produce/{_id}", method = RequestMethod.PATCH,
consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
public String patchObject(#RequestBody PatchObjectRequest obj,
#PathVariable("_id") String id) {
// some code
}
My problem is that the id that might be given is in the form:
US%2FCA%2FSF%2FPlastic
Which is a URL encoding of "US/CA/SF/Plastic".
My problem is that when a % character is put into the URL the #RequestMapping does not map it to this method and it will return a 404. Is there a way to accept ids that have % character in them as part of the URL?
You are receiving this error because using it as path variable it is decoded and then server tries to match it to a path that doesn't exits. Similar questions where posted a few years ago: How to match a Spring #RequestMapping having a #pathVariable containing "/"?, urlencoded Forward slash is breaking URL.
A good option for you would be to change _id from #PathVariable to #RequestParam and problem solved, and remove it from path.
Hope you can add regex in the path variable like:
#RequestMapping(value = "/services/produce/{_id:.+}",
method = RequestMethod.PATCH,
consumes = MediaType.APPLICATION_JSON_VALUE,
produces = MediaType.APPLICATION_JSON_VALUE)
In my test application I have a controller with the following method:
#RequestMapping(value = "/{city}", method = RequestMethod.GET)
public #ResponseBody
MyAnwser getAnwser(#PathVariable String city) {
return new MyAnwser(city);
}
which returns the following
{"result":{"valueA":"valueB"}}
I'm looking for a way to remove the first object sign from the response - "{" to get:
"result":{"valueA":"valueB"}
but I can't figure out a way to do it while using #ResponseBody
If you do that, you wouldn't end up with a valid JSON! In other words, you can't mustn't do that.
As you want to Remove First And Last Character of your Received String Then use
String str="your Received String goes here";
str=str.substring(1, str.length()-1)