KirbyD
KirbyD

Reputation: 51

How to convert int to String?

how can i convert int to String so that i can getparameter?

My Controller

@RequestMapping(method = RequestMethod.POST, value = "/searchUsers")
public String searchUsers(HttpServletRequest request, ModelMap map, 
        @RequestParam(value = "page", required = false) Integer page,
        @RequestParam(value = "size", required = false) Integer size) {
    String searchId = request.getParameter("userId");

    String searchProductName = request.getParameter("productName");
    String searchQuantity = request.getParameter("quantity");
    String searchStock = request.getParameter("stock");
    String searchDate = request.getParameter("date");


    Product searchProduct = new Product();
    searchProduct.setPid(searchId);
    searchProduct.setPname(searchProductName);
    searchProduct.setPquantity(searchQuantity);
    searchProduct.setPstock(searchStock);
    searchProduct.setPdate(searchDate);

MyClass

private int id;

@Column(name="p_name")
private String pname;

@Column(name="p_quantity")
private String pquantity;

as you can see in my class i have int id use for autoincrement in my db. how can i convert my Id to String without changing String Id in my class so that i can request.getParameter it in my controller??

as you can see in my controller String searchId It can not store in my database because it is set to String.

so how can i convert my int Id to String?can someone help me. thanks in advance

Upvotes: 2

Views: 2942

Answers (3)

Cat Snacks
Cat Snacks

Reputation: 96

If you just need to use the int as a String

String s = String.valueOf(id);

is what you want

String.valueOf(int i) Returns the string representation of the int argument.

Upvotes: 1

Charles Brown
Charles Brown

Reputation: 927

From top, there are three replies.

1st, String s = String.valueOf(int). This is correct.

2nd, String z = "" + myInt. This is workable but take more memory. (Not a good practice)

3rd, return Integer.toString(id); Better use String.valueOf instead.

See Java - Convert integer to string

Integer.toString(int i) vs String.valueOf(int i)

Thank you.

Upvotes: 0

Naman Gala
Naman Gala

Reputation: 4692

Approach 1: You can caste the String in your controller

String searchId = request.getParameter("userId");
int id = Integer.parseInt(searchId); //Null check and NumberFormatException to be handled.
searchProduct.setPid(id);

Approach 2: You create methods in your entity class which takes String as input.

private int id;

/*Default getter setter*/
public int getId() {
    return id;
}
public void setId(int id) {
    this.id = id;
}

/*String based getter setter*/
public String getIdStr() {
    return Integer.toString(id);
}
public void setId(String id) throws NumberFormatException {
    this.id = Integer.parseInt(id); // Null check to be added 
}

Use it in your controller.

searchProduct.setId(searchId);  //searchId is String

Upvotes: 0

Related Questions