更多技术文章请访问我的个人博客http://www.rain1024.com
在Javaweb中表单中的参数在提交给servlet时都是以字符串的类型出现,需要对各种参数进行类型的转换,而如果每次都写一遍类型转换方法,代码的实用性太低(其实是懒得写),于是把这些方法写到一个类中,以后直接调用就好,其中有参数的空值判断,Int类型转换,Double类型转换,Array类型转换,Date类型的转换,Timestamp类型的转换。使用时放入util包中即可,下面是源代码。
package cn.itshixun;
import java.sql.Date;
import java.sql.Timestamp;
import javax.servlet.http.HttpServletRequest;
public class RequestUtil {
public static String getString(HttpServletRequest req, String name) {
String str = req.getParameter(name);
str = isBlank(str) ? "" : str.trim();
return str;
}
public static int getInt(HttpServletRequest req, String name) {
try {
return Integer.parseInt(RequestUtil.getString(req, name));
} catch (Exception ex) {
return 0;
}
}
public static int[] getIntArray(HttpServletRequest req, String name) {
String[] strs = req.getParameterValues(name);
if (strs == null) {
return null;
}
int[] array = new int[strs.length];
for (int i = 0; i < strs.length; i++) {
array[i] = Integer.parseInt(strs[i]);
}
return array;
}
public static double getDouble(HttpServletRequest req, String name) {
try {
return Double.parseDouble(RequestUtil.getString(req, name));
} catch (Exception ex) {
return 0.0;
}
}
public static Date getDate(HttpServletRequest req, String name) {
try {
return Date.valueOf(RequestUtil.getString(req, name));
} catch (Exception ex) {
return null;
}
}
public static Timestamp getTimestamp(HttpServletRequest req, String name) {
try {
return Timestamp.valueOf(RequestUtil.getString(req, name));
} catch (Exception ex) {
return null;
}
}
private static boolean isBlank(String str) {
return str == null || str.trim().length() == 0;
}
}