当前页面: 开发资料首页 → JSP 专题 → jsp参数强制转换怎么写?
jsp参数强制转换怎么写?
摘要: jsp参数强制转换怎么写?
兄弟们,字符强制转换为数字要写么写,
比如url参数test.jsp?id=1,id要是输入字符就出错.
String my_str=request.getParameter("id");
int id = Integer.valueOf(my_str).intValue();
有什么办法可以据字符转换为0,先谢谢大家了~~
id输入字符时不能转换为int
有没有其他的办法呀~
test.jsp?id=1
....
我认为你写的完全没问题啊。就是这么转换的。
出错信息是什么?
String - int
String id = request.getParameter("id");
int id2 = Integer.ParseInt(id);
String my_str=request.getParameter("id"); //这里返回的一定是String类型
int id = Integer.parseInt(my_str); /*强制转换,若要对输入的非数字字符进行处理,可以抓
NumberFormatException */
楼上说的正解,
楼上的楼上,同意!
int i=Integer.parseInt(s);
我日 这个也问?
服了``````````````
比如test.jsp?id=傻B
id是int类型,怎么样把"傻B"转换为0;
int id = 0;
try
{
id = Integer.parseInt(request.getParameter("id"));
}catch(NumberFormatException e1){}
就可以了 只接受正确的值
应该还要判断一下,id是否为null;
String id = request.getParameter("id");
if(id=null){return;}
如果request.getParameter("id")为null;
Integer.parseInt(null)还是会报NumberFormatException 的
String id = request.getParameter("id");
int id2 = Integer.ParseInt(id);
这个理论上可以
但是实际上我推荐这么写
String id = request.getParameter("id");
int id2 = 0
try
{
id2=Integer.ParseInt(id);
}
catch(Exception e)
{
id2=0;
}
这样试下呢
<%
String my_str=request.getParameter("id");
int id = 0;
try
{
id = Integer.valueOf(my_str).intValue();
}
catch(Exception e)
{
id=0;
}
out.println("id="+id);
%>
谢谢大家了,问题解决了~~