I have a search method and it has keywords parameter. What I want to do is set a default value(empty String array) to keywords parameter. Is there any way to do this?
#GetMapping(value = "search")
public List<Integer> search(#RequestParam String[] keywords){
return calculate(Arrays.asList(keyword));
}
#RequestParam has an attribute defaultValue to set default value.
public List<Integer> search(#RequestParam(defaultValue="default value") String[] keywords){
return calculate(Arrays.asList(keyword));
}
Try to use below:
#RequestParam(value="keywords[]", required=false) String[] keywords
or
#RequestParam(value=" ", required=false) String[] keywords
Related
I've had an array of enums like below:
enum CountryEnum {
MADAGASCAR,
LESOTHO,
BAHAMAS,
TURKEY,
UAE
}
List<CountryEnum> countryList = new ArrayList<>();
countryList.add(CountryEnum.MADAGASCAR);
countryList.add(CountryEnum.BAHAMAS);
How to convert my countryList into String[]?
I've tried this way:
String[] countries = countryList.toArray(String::new);
but it returned me ArrayStoreException.
It should work so:
String[] strings = countryList.stream() // create Stream of enums from your list
.map(Enum::toString) // map each enum to desired string (here we take simple toString() for each enum)
.toArray(String[]::new); // collect it into string array
you can try this:
enum CountryEnum {
MADAGASCAR("Madagascar"),
LESOTHO("Lesotho"),
BAHAMAS("Bahamas"),
TURKEY("Turkey"),
UAE("UAE");
String country;
CountryEnum(String country) {
this.country = country;
}
public String getCountry() {
return country;
}
}
I added a constructor to be able to get (in String) enum's values. Now you can just use:
List<String> countryList = new ArrayList<>();
countryList.add(CountryEnum.MADAGASCAR.getCountry());
countryList.add(CountryEnum.BAHAMAS.getCountry());
👍 😀
When someone get rest method called by using below url hit the controllerMethod.
For example URL string like:
String queryurl=http://localhost:8081/servcie/details?id=101&type=124;
String changedQueryUrl=null;
#GetMapping(value = "details")
public MyModel controllerMethod(#RequestParam Map<String, String> customQuery,HttpServletRequest request) {
//i have to replace words "id" with rollNo and "type" with datatype
// so that i have done below sample code
for ( Entry<String, String> entry : customQuery.entrySet()) {
if (entry.getKey().equals("id")) {
changedQueryUrl= request.getQueryString().replaceAll("\\bid\\b", "rollNo");
}
else if (entry.getKey().equals("type")) {
changedQueryUrl= request.getQueryString().replaceAll("\\btype\\b", "datatype");
}
}
}
when i am printing changedQueryUrl only one of word is replacing other word is not replacing.
I want to print the output like with exact matching words
changedQueryUrl=http://localhost:8081/servcie/details?rollNo=101&datatype=124
replaceAll returns a new copy of the original string, so the first replace don't change the original String request.queryString(). The second replaceAll works on request.queryString() which has no effect because you need to work with the result of replaceAll.
And don't use request.queryString() anymore in your loop, if you want to make your code working you can assign changedQueryUrl= request.getQueryString(); before the loop and use changedQueryUrl.replaceAll(...) instead of request.getQueryString().replaceAll(...).
Or just do
String queryurl = "http://localhost:8081/servcie/details?id=101&type=124;";
String queryRes = queryurl.replaceAll("\\bid\\b", "rollNo").replaceAll("\\btype\\b", "datatype");
How can I extract attributes values from the string parameter ?
public class Pays{
public Pays(String paysDescriptions) {
//implementation
}
}
pays= new Pays("p1:Europe:France, p2:Amerique:Canada");
Edit:
I gave an answer below to people who have never used this type of constructor (like me :p ) and who may need some explanations.
You should try using String.split(String regex) API.
Break the parameter paysDescriptions using comma(,) as regex, then
Break the individual items using colon(:) as regex
Example:
public Pays(String paysDescriptions) {
String[] split_1 = paysDescriptions.split(",");
for (String split : split_1) {
String[] split_2 = split.split(":");
for (String sp : split_2) {
System.out.println(sp); // use sp.trim() if spaces after comma
// not required.
}
}
}
I misunderstand the logic because it's the first time I saw this kind of conctructor..I have only the unit test class and I should implement the code for the source one. So I've used a Map<String,String[]> to split parameters and then I can access to the various attributes of my class.
Map<String, String[]> paysMap = new HashMap<String, String[]>();
public Pays(String paysDescriptions) {
String s = paysDescriptions;
String[] pairs = s.split(",");
for (int i=0;i<pairs.length;i++) {
String pair = pairs[i];
String[] keyValue = pair.split(":");
paysMap.put(String.valueOf(keyValue[0]),new String[] {String.valueOf(keyValue[1]), String.valueOf(keyValue[2])});
}
}
I need to write a setter for an array using spring's value annotation so it will come from properties file.
private String[] aList;
public String[] getAList()
{
return aList;
}
#value("a:b")
public String[] setAList(String aString)
{
aList = aString.Split(":");
}
I am not sure if this is the right way to do?
Will I get the right value from string?
Thanks,
Always have the same type for getter and setter pairs. In order to perform what you want, you could simply rename setAList to setAListAsColonSeparatedValues or something similar. Also, your setter method should return void.
If you put them in your properties file as
listItems=1,2,3,4,5,6
Spring will load an array for you
#Value( "${listItems}")
private String[] aList;
If iterate through aList you get
item = 1
item = 2
item = 3
I have an ArrayList, Whom i convert to String like
ArrayList str = (ArrayList) retrieveList.get(1);
...
makeCookie("userCredentialsCookie", str.toString(), httpServletResponce);
....
private void makeCookie(String name, String value, HttpServletResponse response) {
Cookie cookie = new Cookie(name, value);
cookie.setPath("/");
response.addCookie(cookie);
} //end of makeCookie()
Now when i retrieve cookie value, i get String, but i again want to convert it into ArrayList like
private void addCookieValueToSession(HttpSession session, Cookie cookie, String attributeName) {
if (attributeName.equalsIgnoreCase("getusercredentials")) {
String value = cookie.getValue();
ArrayList userCredntialsList = (ArrayList)value; //Need String to ArrayList
session.setAttribute(attributeName, userCredntialsList);
return;
}
String value = cookie.getValue();
session.setAttribute(attributeName, value);
} //end of addCookieValueToSession
How can i again convert it to ArrayList?
Thank you.
someList.toString() is not a proper way of serializing your data and will get you into trouble.
Since you need to store it as a String in a cookie, use JSON or XML. google-gson might be a good lib for you:
ArrayList str = (ArrayList) retrieveList.get(1);
String content = new Gson().toJson(str);
makeCookie("userCredentialsCookie", content, httpServletResponce);
//...
ArrayList userCredntialsList = new Gson().fromJson(cookie.getValue(), ArrayList.class);
As long as it's an ArrayList of String objects you should be able to write a small method which can parse the single String to re-create the list. The toString of an ArrayList will look something like this:
"[foo, bar, baz]"
So if that String is in the variable value, you could do something like this:
String debracketed = value.replace("[", "").replace("]", ""); // now be "foo, bar, baz"
String trimmed = debracketed.replaceAll("\\s+", ""); // now is "foo,bar,baz"
ArrayList<String> list = new ArrayList<String>(Arrays.asList(trimmed.split(","))); // now have an ArrayList containing "foo", "bar" and "baz"
Note, this is untested code.
Also, if it is not the case that your original ArrayList is a list of Strings, and is instead say, an ArrayList<MyDomainObject>, this approach will not work. For that your should instead find how to serialise/deserialise your objects correctly - toString is generally not a valid approach for this. It would be worth updating the question if that is the case.
You can't directly cast a String to ArrayList instead you need to create an ArrayList object to hold String values.
You need to change part of your code below:
ArrayList userCredntialsList = (ArrayList)value; //Need String to ArrayList
session.setAttribute(attributeName, userCredntialsList);
to:
ArrayList<String> userCredentialsList = ( ArrayList<Strnig> ) session.getAttribute( attributeName );
if ( userCredentialsList == null ) {
userCredentialsList = new ArrayList<String>( 10 );
session.setAttribute(attributeName, userCredentialsList);
}
userCredentialsList.add( value );