您的位置:首页 > 编程语言 > Java开发

页面输入的数据格式转换类:BaseAction(经常使用于Struts框架中)

2017-05-16 21:01 183 查看
在我们接收页面传来的数据时,这些数据都是以String类型接收的,所以要进行数据格式转换,这时候就能够统一为它们进行转换,并且在处理这些数据的类中能够继承ActionSupport类,然后让每个接收数据并做业务处理的action类继承该类,并调用该类中的数据格式转换方法对接收的数据进行处理。

部分关键代码例如以下:

/**

* 超类BaseAction 数据格式转换

* @author 七录斋

*

*/

public class BaseAction extends ActionSupport{

public void write(Object obj){

HttpServletResponse response = ServletActionContext.getResponse();

response.setContentType("text/html;charset=utf-8");

try {

response.getWriter().print(obj);

} catch (IOException e) {

e.printStackTrace();

}

}

/**

* 把对应的数据转换成整型数据

* @param value String类型 要转换的数据

* @return 整型 转换失败时返回null

*/

public Integer $int(String value){

try {

return Integer.parseInt(ServletActionContext.getRequest()

.getParameter(value));

} catch (Exception e) {

e.printStackTrace();

}

return null;

}

/**

* 把对应的数据转换成Double类型的数据

* @param value String类型 要转换的数据

* @return Double类型 转换失败时返回null

*/

public Double $double(String value){

try {

return Double.parseDouble(ServletActionContext.getRequest()

.getParameter(value));

} catch (Exception e) {

e.printStackTrace();

}

return null;

}

/**

* 把对应的数据转换成String类型的数据

* @param value String类型 要转换的数据

* @return String类型 转换失败时返回null

*/

public String $str(String value){

try {

return ServletActionContext.getRequest().getParameter(value);

} catch (Exception e) {

e.printStackTrace();

}

return null;

}

/**

* 把对应的数据转换成BigDecimal类型的数据

* @param value String类型 要转换的数据

* @return BigDecimal类型 转换失败时返回null

*/

public BigDecimal $bigDecimal(String value){

try {

return new BigDecimal(ServletActionContext.getRequest()

.getParameter(value));

} catch (Exception e) {

e.printStackTrace();

}

return null;

}

/**

* 把对应的数据转换成Date类型的数据

* @param value String类型 要转换的数据

* @return Date类型 转换失败时返回null

*/

public Date $date(String value){

try {

return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")

.parse(ServletActionContext.getRequest().getParameter(value));

} catch (Exception e) {

try {

return new SimpleDateFormat("yyyy-MM-dd")

.parse(ServletActionContext.getRequest().getParameter(value));

} catch (Exception e2) {

e2.printStackTrace();

}

}

return null;

}

/**

* 把对应的数据转换成Time类型的数据

* @param value String类型 要转换的数据

* @return Time类型 转换失败时返回null

*/

public Time $time(String value){

try {

return new Time(new SimpleDateFormat("HH:mm:ss")

.parse(ServletActionContext.getRequest()

.getParameter(value)).getTime());

} catch (Exception e) {

e.printStackTrace();

}

return null;

}

/**

* 把对应的数据转换成Timestamp类型的数据

* @param value String类型 要转换的数据

* @return Timestamp类型 转换失败时返回null

*/

public Timestamp $timestamp(String value){

try {

return new Timestamp(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")

.parse(ServletActionContext.getRequest()

.getParameter(value)).getTime());

} catch (Exception e) {

e.printStackTrace();

}

return null;

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐