#RequestMapping(value = "/{userId:\\d+}", method = RequestMethod.DELETE)
public void delete(#PathVariable Long userId) {
try{
this.authorService.delete(userId);
}catch(Exception e){
throw new RuntimeException("delete error");
}
}
Anybody know what url should I match for this definition "/{userId:\d+}", could you give me an example, like "/userid=1", is this right?
I guess that definition like this "/{userId:\d+}" , using regular expression in url to make sure it pass a number parameter.I am not sure about that , if anybody knows it please give me a link for further learning, thank you!
No, that expression maps /1 for example, all the digits.
The syntax {varName:regex} declares a URI variable with a regular expressions with the syntax {varName:regex} — e.g. given URL "/spring-web-3.0.5 .jar", the below method extracts the name, version, and file extension:
#GetMapping("/{name:[a-z-]+}-{version:\\d\\.\\d\\.\\d}{ext:\\.[a-z]+}")
public void handle(#PathVariable String version, #PathVariable String ext) {
// ...
}
Check the complete doc here
It will match any digit. For example,
/1, /11, /123.
/{userId:\\d+} ===> map one or more digits after / to variable userId.
Regular expression for one or more digits is \d+, but since you are using it as a string you need to escape it using another \.
Related
Consider this method signature that I have
#Cacheable(
key="#name+'::'+#age+'::'+#country"
)
public User validate(String name, String age, String country) {
...
}
Notice the key that I have. Currently I am able to concatenate the name, age and country variables. But on top of concatenating them, I also want to convert the entire expression into a lowercase value.
For example if someone called this method like so: validate("John","24","USA"),
then I want my key to be resolved as: john::24::usa. Notice all the uppercase letters have become lowercase.
TLDR; how to write a spel expression which concatenates multiple variables and converts the entire result into lowercase?
Expression exp = new SpelExpressionParser()
.parseExpression("(#foo + '::' + #bar).toLowerCase()");
StandardEvaluationContext ctx = new StandardEvaluationContext();
ctx.setVariable("foo", "XXX");
ctx.setVariable("bar", "YYY");
System.out.println(exp.getValue(ctx));
xxx::yyy
I have a rest api implementation as below -
#RequestMapping(value = "/getAllProductsByCategory/{category}/{pageNo}/{numberOfProducts}", method = RequestMethod.GET)
public List<ProductProperties> getAllProdutsByCategory(#PathVariable("category") String categoryID, #PathVariable("pageNo") int pageNo,
#PathVariable("numberOfProducts") int numberOfProducts) {
return productService.getProductsByCategory(categoryID, pageNo, numberOfProducts);
}
Now i want to test this method where category variable should be like "men/clothing/jeans". I tried to use escape character %2F to replace forward slash, but had no luck. Is there any way to pass forward slash in uri ? I tried to google same question but didn't find any satisfactory answer.
lets say I have a url param like token=1234235asdjaklj231k209a&name=sam&firname=Mahan
how can I replace the value of the token with new one ?
I've done something similar to this with pattern and matcher before but I don't recall now
but I know there is a way to do so
Update : the token can contain any letter but &
thanks in advance
Spring has a util that handles this need gracefully. Apache httpcomponents does too. Below is a spring example.
import org.springframework.web.util.UriComponentsBuilder;
import java.net.URI;
public class StackOverflow {
private static class SO46303058 {
public static void main(String[] args) {
final String urlString = "https://subdomain.hostname/path/resource?token=1234235asdjaklj231k209a&name=sam&firname=Mahan";
final URI uri = UriComponentsBuilder.fromHttpUrl(urlString)
.replaceQueryParam("token", "abc")
.build().toUri();
System.out.println(uri);
}
}
}
Don't be afraid of adding dependencies to your project, it beats reinventing the wheel.
We can consider doing a simple regex replacement, with a few caveats (q.v. below the code snippet).
String url = "token=1234235asdjaklj231k209a&name=sam&firname=Mahan";
url = url.replaceFirst("\\btoken=.*?(&|$)", "token=new_value$1");
System.out.println(url);
url = "param1=value&token=1234235asdjaklj231k209a";
url = url.replaceFirst("\\btoken=.*?(&|$)", "token=new_value$1");
System.out.println(url);
Edge cases to consider are first that your token may be the last parameter in the query string. To cover this case, we should check for token=... ending in either an ambersand & or the end of the string. But if we don't use a lookahead, and instead consume that ambersand, we have to also add it back in the replacement. The other edge case, correctly caught by #DodgyCodeException in his comment below, is that there be another query parameter which just happens to end in token. To make sure we are really matching our token parameter, we can preface it with a word boundary in the regex, i.e. use \btoken=... to refer to it.
Output:
token=new_value&name=sam&firname=Mahan
param1=value&token=new_value
make a viewModel.
public class veiwModel(){ String token ; // and get and set for exmample }
then use Gson if u have a json text .
Gson gson = new Gson();
yourViewModel = gson.fronJson(jsonText , viewModel.class);
System.out.println(yourViewModel.getToken());
I am using a query parameters to set the values needed by the Google Maps API.
The issue is I do not need the & sign for the first query parameter.
#GET("/maps/api/geocode/json?")
Call<JsonObject> getLocationInfo(#Query("address") String zipCode,
#Query("sensor") boolean sensor,
#Query("client") String client,
#Query("signature") String signature);
Retrofit generates:
&address=90210&sensor=false&client=gme-client&signature=signkey
which causes the call the fail when I need it to be
address=90210&sensor=false&client=gme-client&signature=signkey
How do I fix this?
If you specify #GET("foobar?a=5"), then any #Query("b") must be appended using &, producing something like foobar?a=5&b=7.
If you specify #GET("foobar"), then the first #Query must be appended using ?, producing something like foobar?b=7.
That's how Retrofit works.
When you specify #GET("foobar?"), Retrofit thinks you already gave some query parameter, and appends more query parameters using &.
Remove the ?, and you will get the desired result.
I am new to retrofit and I am enjoying it. So here is a simple way to understand it for those that might want to query with more than one query: The ? and & are automatically added for you.
Interface:
public interface IService {
String BASE_URL = "https://api.test.com/";
String API_KEY = "SFSDF24242353434";
#GET("Search") //i.e https://api.test.com/Search?
Call<Products> getProducts(#Query("one") String one, #Query("two") String two,
#Query("key") String key)
}
It will be called this way. Considering you did the rest of the code already.
Call<Results> call = service.productList("Whatever", "here", IService.API_KEY);
For example, when a query is returned, it will look like this.
//-> https://api.test.com/Search?one=Whatever&two=here&key=SFSDF24242353434
Link to full project: Please star etc: https://github.com/Cosmos-it/ILoveZappos
If you found this useful, don't forget to star it please. :)
public interface IService {
String BASE_URL = "https://api.demo.com/";
#GET("Login") //i.e https://api.demo.com/Search?
Call<Products> getUserDetails(#Query("email") String emailID, #Query("password") String password)
}
It will be called this way. Considering you did the rest of the code already.
Call<Results> call = service.getUserDetails("abc#gmail.com", "Password#123");
For example when a query is returned, it will look like this.
https://api.demo.com/Login?email=abc#gmail.com&password=Password#123
I am using Jersey for Rest and have a method that accepts #QueryParam.
However, the users may send #QueryParam. like this:
contractName# where # is a number from 0-155.
How can I define it in QueryParam (like regex expression)?
You can't specify the regexp. However, you can define a custom Java type to represent that query param and implement your own conversion from String to that type - see http://jersey.java.net/nonav/documentation/latest/jax-rs.html#d4e255 (example 2.15).
I don't think you can do it with QueryParam, but you can get the list of parameters directly:
#GET
public String get(#Context UriInfo ui) {
MultivaluedMap<String, String> queryParams = ui.getQueryParameters();
}
and iterate through that looking for keys that match your regular expression.
#GET
public String get (#QueryParam(value="param") String param){
boolean test =testYourParamWithNativeRegexpTools(param);
if( test==false)return 400;
else //work
.....
}