Java 如何将int转换为String?

Java 如何将int转换为String?,java,Java,如何将int转换为String以便获取参数 我的控制器 @RequestMapping(method = RequestMethod.POST, value = "/searchUsers") public String searchUsers(HttpServletRequest request, ModelMap map, @RequestParam(value = "page", required = false) Integer page, @Reque

如何将int转换为String以便获取参数

我的控制器

@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);
我的班级

private int id;

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

@Column(name="p_quantity")
private String pquantity;
正如您在我的类中所看到的,我在数据库中使用int-id进行自动增量。 如何在不更改类中的字符串Id的情况下将Id转换为字符串,以便在控制器中请求.getParameter

正如你在我的控制器中看到的 字符串搜索ID 它无法存储在我的数据库中,因为它已设置为字符串


那我怎么才能把我的int-Id转换成String呢?有人能帮我吗。如果您只需要将int用作字符串,请提前感谢

String s = String.valueOf(int);
这就是你想要的


将尝试将您传递给它的任何内容转换为字符串,因为它返回toString()值,即您试图查找其值的对象的字符串表示形式

方法1: 您可以在控制器中铸造字符串

String searchId = request.getParameter("userId");
int id = Integer.parseInt(searchId); //Null check and NumberFormatException to be handled.
searchProduct.setPid(id);
方法2: 您可以在实体类中创建以字符串作为输入的方法

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 
}
在控制器中使用它

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

从上面看,有三个回复

第一个,
String s=String.valueOf(int)
。这是正确的

第二,
字符串z=”“+myInt
。这是可行的,但需要更多的内存。(这不是一个好的做法)

第三,
返回整数.toString(id)最好改用String.valueOf


谢谢。

哪个
id
要从int转换为String?aw-okey可能重复,我稍后再试。您可以在类中定义另一个setter,将String作为输入,并将其转换为int,然后设置id的值。用同样的方法创建一个getter,将int转换为String(Integer.toString(id))我想我可以使用int-id=request.getParameter(“userId”);我错了…还是不走运,先生。java.lang.NumberFormatException:java.lang.Integer.parseInt(未知源)处的java.lang.Integer.parseInt(未知源)处为null,您可以在setter方法中设置值之前添加null检查。