Javaweb中封装servlet对post参数的各种类型转换方法

algorain

在Javaweb中表单中的参数在提交给servlet时都是以字符串的类型出现,需要对各种参数进行类型的转换,而如果每次都写一遍类型转换方法,代码的实用性太低(其实是懒得写),于是把这些方法写到一个类中,以后直接调用就好,其中有参数的空值判断,Int类型转换,Double类型转换,Array类型转换,Date类型的转换,Timestamp类型的转换。使用时放入util包中即可,下面是源代码。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
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;
}
}
  • Title: Javaweb中封装servlet对post参数的各种类型转换方法
  • Author: algorain
  • Created at: 2017-02-14 00:00:03
  • Updated at: 2023-05-14 21:39:50
  • Link: http://www.rain1024.com/2017/02/14/javaweb-article55/
  • License: This work is licensed under CC BY-NC-SA 4.0.
 Comments