Java Web项目中常用的工具类

来源:互联网 发布:nginx 配置文件服务器 编辑:程序博客网 时间:2024/06/03 18:15
今天给大家分享一些Web项目中常用的工具类,稍微大一点的Web项目都会有很多的工具类,工具类的出现是为了减少代码冗余,提高代码程序的可读性,降低程序运行负担。

第一个工具类是Action中常会用到的可写在BaseAction中如下(包省略):

public class BaseAction extends ActionSupport {

public void putInRequest(String key ,Object value){
//获取request对象
Map  request =(Map)ActionContext.getContext().get("request");
//把后台传过来的数据赋值到request中
request.put(key, value);
}
public void responseText(String text){
try {
//如返回对象中有中文要设置一下编码格式,否者返回到前台的数据会出现乱码。
ServletActionContext.getResponse().setContentType("text/html;charset=utf-8");
//获取Response对象将数据传到前台
ServletActionContext.getResponse().getWriter().write(text);
} catch (IOException e) {
e.printStackTrace();
}
}
}

第二个工具类是各种数据转换String类型 如下(包省略):

public class StringUtil {
public static Double getDouble(String str) {
Double result = 0.0;
try {
result = Double.parseDouble(str);
} catch (NumberFormatException e) {
e.printStackTrace();
}
return result;
}

public static Date getDate(String str) {
Date d = null;
try {
SimpleDateFormat sdf = newSimpleDateFormat("yyyy-MM-dd");
d = sdf.parse(str);
} catch (ParseException e) {
e.printStackTrace();
}

return d;

}

public static Boolean getBool(String str) {
Boolean result = null;
try {
result = Boolean.parseBoolean(str);
} catch (NumberFormatException e) {
e.printStackTrace();
}
return result;
}

public static Integer getInt(String str) {
Integer result = 0;
try {
result = Integer.parseInt(str);
} catch (NumberFormatException e) {
e.printStackTrace();
}
return result;
}
public static Short getShort(String str) {
Short result = 0;
try {
result = Short.parseShort(str);
} catch (NumberFormatException e) {
e.printStackTrace();
}
return result;
}

//此方法是主要是为了生成固定的几位数常用字订单生成如果是5(000005)如果是15这生成(000015)
public static String addZero(int len ,int num){
String str  = "";
for (int i = 0; i < len-(""+num).length(); i++) {
str="0"+str;
}
return str+num;
}
public static void main(String[] args) {
System.out.println(StringUtil.addZero(6, 123));
}
}

第三个工具类关于事务开启与关闭的 如下(包省略):
public class OpenSessionInView  implementsFilter {

public void doFilter(ServletRequest request, ServletResponseresponse,
FilterChain chain) throws IOException, ServletException{
//打开session
Session session=HibernateSessionFactory.getSession();
//开启事物
session.beginTransaction();
chain.doFilter(request, response);
session.getTransaction().commit();
session.close();
}
}

今天到此为止这些代码都是可以复制粘贴的,希望可以给你们提供帮助,写的不好希望别喷,有什么不懂的地方可以问我哦。
0 0