常用的泛型工具类:
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
/**
* 泛型工具类
*
*/
public class GenericsUtils {
/**
* 通过反射,获得指定类的父类的泛型参数的实际类型. 如BuyerServiceBean extends DaoSupport<Buyer>
*
* @param clazz clazz 需要反射的类,该类必须继承范型父类
* @param index 泛型参数所在索引,从0开始.
* @return 范型参数的实际类型, 如果没有实现ParameterizedType接口,即不支持泛型,所以直接返回<code>Object.class</code>
*/
public static Class getClassGenricType(Class clazz, int index) {
Type genType = clazz.getGenericInterfaces()[0];//得到自己
//如果没有实现ParameterizedType接口,即不支持泛型,直接返回Object.class
if (!(genType instanceof ParameterizedType)) {
return Object.class;
}
//返回表示此类型实际类型参数的Type对象的数组,数组里放的都是对应类型的Class, 如BuyerServiceBean extends DaoSupport<Buyer,Contact>就返回Buyer和Contact类型
Type[] params = ((ParameterizedType) genType).getActualTypeArguments();
if (index >= params.length || index < 0) {
throw new RuntimeException("你输入的索引"+ (index<0 ? "不能小于0" : "超出了参数的总数"));
}
if (!(params[index] instanceof Class)) {
return Object.class;
}
return (Class) params[index];
}
/**
* 通过反射,获得指定类的父类的第一个泛型参数的实际类型. 如BuyerServiceBean extends DaoSupport<Buyer>
*
* @param clazz clazz 需要反射的类,该类必须继承泛型父类
* @return 泛型参数的实际类型, 如果没有实现ParameterizedType接口,即不支持泛型,所以直接返回<code>Object.class</code>
*/
public static Class getClassGenricType(Class clazz) {
return getClassGenricType(clazz,0);
}
/**
* 通过反射,获得指定类的父类的泛型参数的实际类型. 如BuyerServiceBean extends DaoSupport<Buyer>
*
* @param clazz clazz 需要反射的类,该类必须继承范型父类
* @param index 泛型参数所在索引,从0开始.
* @return 范型参数的实际类型, 如果没有实现ParameterizedType接口,即不支持泛型,所以直接返回<code>Object.class</code>
*/
public static Class getSuperClassGenricType(Class clazz, int index) {
Type genType = clazz.getGenericSuperclass();//得到泛型父类
//如果没有实现ParameterizedType接口,即不支持泛型,直接返回Object.class
if (!(genType instanceof ParameterizedType)) {
return Object.class;
}
//返回表示此类型实际类型参数的Type对象的数组,数组里放的都是对应类型的Class, 如BuyerServiceBean extends DaoSupport<Buyer,Contact>就返回Buyer和Contact类型
Type[] params = ((ParameterizedType) genType).getActualTypeArguments();
if (index >= params.length || index < 0) {
throw new RuntimeException("你输入的索引"+ (index<0 ? "不能小于0" : "超出了参数的总数"));
}
if (!(params[index] instanceof Class)) {
return Object.class;
}
return (Class) params[index];
}
/**
* 通过反射,获得指定类的父类的第一个泛型参数的实际类型. 如BuyerServiceBean extends DaoSupport<Buyer>
*
* @param clazz clazz 需要反射的类,该类必须继承泛型父类
* @return 泛型参数的实际类型, 如果没有实现ParameterizedType接口,即不支持泛型,所以直接返回<code>Object.class</code>
*/
@SuppressWarnings("unchecked")
public static Class getSuperClassGenricType(Class clazz) {
return getSuperClassGenricType(clazz,0);
}
/**
* 通过反射,获得方法返回值泛型参数的实际类型. 如: public Map<String, Buyer> getNames(){}
*
* @param Method method 方法
* @param int index 泛型参数所在索引,从0开始.
* @return 泛型参数的实际类型, 如果没有实现ParameterizedType接口,即不支持泛型,所以直接返回<code>Object.class</code>
*/
public static Class getMethodGenericReturnType(Method method, int index) {
Type returnType = method.getGenericReturnType();
if(returnType instanceof ParameterizedType){
ParameterizedType type = (ParameterizedType) returnType;
Type[] typeArguments = type.getActualTypeArguments();
if (index >= typeArguments.length || index < 0) {
throw new RuntimeException("你输入的索引"+ (index<0 ? "不能小于0" : "超出了参数的总数"));
}
return (Class)typeArguments[index];
}
return Object.class;
}
/**
* 通过反射,获得方法返回值第一个泛型参数的实际类型. 如: public Map<String, Buyer> getNames(){}
*
* @param Method method 方法
* @return 泛型参数的实际类型, 如果没有实现ParameterizedType接口,即不支持泛型,所以直接返回<code>Object.class</code>
*/
@SuppressWarnings("unchecked")
public static Class getMethodGenericReturnType(Method method) {
return getMethodGenericReturnType(method, 0);
}
/**
* 通过反射,获得方法输入参数第index个输入参数的所有泛型参数的实际类型. 如: public void add(Map<String, Buyer> maps, List<String> names){}
*
* @param Method method 方法
* @param int index 第几个输入参数
* @return 输入参数的泛型参数的实际类型集合, 如果没有实现ParameterizedType接口,即不支持泛型,所以直接返回空集合
*/
public static List<Class> getMethodGenericParameterTypes(Method method, int index) {
List<Class> results = new ArrayList<Class>();
Type[] genericParameterTypes = method.getGenericParameterTypes();
if (index >= genericParameterTypes.length ||index < 0) {
throw new RuntimeException("你输入的索引"+ (index<0 ? "不能小于0" : "超出了参数的总数"));
}
Type genericParameterType = genericParameterTypes[index];
if(genericParameterType instanceof ParameterizedType){
ParameterizedType aType = (ParameterizedType) genericParameterType;
Type[] parameterArgTypes = aType.getActualTypeArguments();
for(Type parameterArgType : parameterArgTypes){
Class parameterArgClass = (Class) parameterArgType;
results.add(parameterArgClass);
}
return results;
}
return results;
}
/**
* 通过反射,获得方法输入参数第一个输入参数的所有泛型参数的实际类型. 如: public void add(Map<String, Buyer> maps, List<String> names){}
*
* @param Method method 方法
* @return 输入参数的泛型参数的实际类型集合, 如果没有实现ParameterizedType接口,即不支持泛型,所以直接返回空集合
*/
@SuppressWarnings("unchecked")
public static List<Class> getMethodGenericParameterTypes(Method method) {
return getMethodGenericParameterTypes(method, 0);
}
/**
* 通过反射,获得Field泛型参数的实际类型. 如: public Map<String, Buyer> names;
*
* @param Field field 字段
* @param int index 泛型参数所在索引,从0开始.
* @return 泛型参数的实际类型, 如果没有实现ParameterizedType接口,即不支持泛型,所以直接返回<code>Object.class</code>
*/
public static Class getFieldGenericType(Field field, int index) {
Type genericFieldType = field.getGenericType();
if(genericFieldType instanceof ParameterizedType){
ParameterizedType aType = (ParameterizedType) genericFieldType;
Type[] fieldArgTypes = aType.getActualTypeArguments();
if (index >= fieldArgTypes.length || index < 0) {
throw new RuntimeException("你输入的索引"+ (index<0 ? "不能小于0" : "超出了参数的总数"));
}
return (Class)fieldArgTypes[index];
}
return Object.class;
}
/**
* 通过反射,获得Field泛型参数的实际类型. 如: public Map<String, Buyer> names;
*
* @param Field field 字段
* @param int index 泛型参数所在索引,从0开始.
* @return 泛型参数的实际类型, 如果没有实现ParameterizedType接口,即不支持泛型,所以直接返回<code>Object.class</code>
*/
public static Class getFieldGenericType(Field field) {
return getFieldGenericType(field, 0);
}
}
struts2工具类:
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts2.ServletActionContext;
public class Struts2Utils {
public static HttpSession getSession() {
return ServletActionContext.getRequest().getSession();
}
public static HttpSession getSession(Boolean b) {
return ServletActionContext.getRequest().getSession(b.booleanValue());
}
public static HttpServletRequest getRequest() {
return ServletActionContext.getRequest();
}
public static HttpServletResponse getResponse() {
return ServletActionContext.getResponse();
}
public static String getParameter(String name) {
return getRequest().getParameter(name);
}
public static String[] getParameterValues(String name){
return getRequest().getParameterValues(name);
}
public static void setAttribute(String name,Object o)
{
ServletActionContext.getRequest().setAttribute(name, o);
}
public static Object getAttribute(String name)
{
return ServletActionContext.getRequest().getAttribute(name);
}
public static Object getContextAttribute(String name)
{
return ServletActionContext.getServletContext().getAttribute(name);
}
public static void setContextAttribute(String name,Object object)
{
ServletActionContext.getServletContext().setAttribute(name,object);
}
}
Web工具类:
package org.j2cms.utils;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.j2cms.model.user.User;
/**
*
* @author Administrator
*
*/
public class WebUtil {
/**
* 获取登录用户
*/
public static User getUser(HttpServletRequest request){
return (User) request.getSession().getAttribute("user");
}
/***
* 获取URI的路径,如路径为http://www.j2cms.com/action/post.htm?method=add, 得到的值为"/action/post.htm"
* @param request
* @return
*/
public static String getRequestURI(HttpServletRequest request){
return request.getRequestURI();
}
/**
* 获取完整请求路径(含内容路径及请求参数)
* @param request
* @return
*/
public static String getRequestURIWithParam(HttpServletRequest request){
return getRequestURI(request) + (request.getQueryString() == null ? "" : "?"+ request.getQueryString());
}
/**
* 添加cookie
* @param response
* @param name cookie的名称
* @param value cookie的值
* @param maxAge cookie存放的时间(以秒为单位,假如存放三天,即3*24*60*60; 如果值为0,cookie将随浏览器关闭而清除)
*/
public static void addCookie(HttpServletResponse response, String name, String value, int maxAge) {
Cookie cookie = new Cookie(name, value);
cookie.setPath("/");
if (maxAge>0) cookie.setMaxAge(maxAge);
response.addCookie(cookie);
}
/**
* 获取cookie的值
* @param request
* @param name cookie的名称
* @return
*/
public static String getCookieByName(HttpServletRequest request, String name) {
Map<String, Cookie> cookieMap = WebUtil.readCookieMap(request);
if(cookieMap.containsKey(name)){
Cookie cookie = (Cookie)cookieMap.get(name);
return cookie.getValue();
}else{
return null;
}
}
protected static Map<String, Cookie> readCookieMap(HttpServletRequest request) {
Map<String, Cookie> cookieMap = new HashMap<String, Cookie>();
Cookie[] cookies = request.getCookies();
if (null != cookies) {
for (int i = 0; i < cookies.length; i++) {
cookieMap.put(cookies[i].getName(), cookies[i]);
}
}
return cookieMap;
}
/**
* 去除html代码
* @param inputString
* @return
*/
public static String HtmltoText(String inputString) {
String htmlStr = inputString; //含html标签的字符串
String textStr ="";
java.util.regex.Pattern p_script;
java.util.regex.Matcher m_script;
java.util.regex.Pattern p_style;
java.util.regex.Matcher m_style;
java.util.regex.Pattern p_html;
java.util.regex.Matcher m_html;
java.util.regex.Pattern p_ba;
java.util.regex.Matcher m_ba;
try {
String regEx_script = "<[\\s]*?script[^>]*?>[\\s\\S]*?<[\\s]*?\\/[\\s]*?script[\\s]*?>"; //定义script的正则表达式{或<script[^>]*?>[\\s\\S]*?<\\/script> }
String regEx_style = "<[\\s]*?style[^>]*?>[\\s\\S]*?<[\\s]*?\\/[\\s]*?style[\\s]*?>"; //定义style的正则表达式{或<style[^>]*?>[\\s\\S]*?<\\/style> }
String regEx_html = "<[^>]+>"; //定义HTML标签的正则表达式
String patternStr = "\\s+";
p_script = Pattern.compile(regEx_script,Pattern.CASE_INSENSITIVE);
m_script = p_script.matcher(htmlStr);
htmlStr = m_script.replaceAll(""); //过滤script标签
p_style = Pattern.compile(regEx_style,Pattern.CASE_INSENSITIVE);
m_style = p_style.matcher(htmlStr);
htmlStr = m_style.replaceAll(""); //过滤style标签
p_html = Pattern.compile(regEx_html,Pattern.CASE_INSENSITIVE);
m_html = p_html.matcher(htmlStr);
htmlStr = m_html.replaceAll(""); //过滤html标签
p_ba = Pattern.compile(patternStr,Pattern.CASE_INSENSITIVE);
m_ba = p_ba.matcher(htmlStr);
htmlStr = m_ba.replaceAll(""); //过滤空格
textStr = htmlStr;
}catch(Exception e) {
System.err.println("Html2Text: " + e.getMessage());
}
return textStr;//返回文本字符串
}
/***********************************************************
* 函数名:strToInt 作 用:把字符串转为整型 参 数:s: 字符串型 返回值:整型
***********************************************************/
public static int StrToInt(String s) {
try {
int i = Integer.parseInt(checkReplace(s));
return i; // 返回转化以后的字符串
} catch (Exception e) {
return 0;
}
}
/*********************************************************
* 函数名:checkReplace 作 用:转化SQL特殊字符串 参 数:s: 字符串型,待转化的字符 返回值:转化以后的字符串
* 调 用:String s2 = checkReplace(s1);
***********************************************************/
public static String checkReplace(String s) {
try {
if (s == null || s.equals(""))
return "";
else {
StringBuffer stringbuffer = new StringBuffer();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
switch (c) {
case 34: // '"'
stringbuffer.append(""");
break;
case 39: // '\''
stringbuffer.append("'");
break;
case 124: // '|'
stringbuffer.append("");
break;
case '&':
stringbuffer.append("&");
break;
case '<':
stringbuffer.append("<");
break;
case '>':
stringbuffer.append(">");
break;
default:
stringbuffer.append(c);
break;
}
}
return stringbuffer.toString().trim(); // 返回转化以后的字符串
}
} catch (Exception e) {
return "";
}
}
}
struts2 与fckeditor冲突
1,自定义filter
public class MyStrutsFilterDispatcher extends StrutsPrepareAndExecuteFilter {
/**
*struts2的拦截器与fck上传文件冲突
*重写struts2的拦截器,增加了判断,如果是fck的编辑器上传文件,则不进行拦截。
* 判断路径是否有fckeditor,实现在fck下的操作不进行拦截
*/
@Override
public void doFilter(ServletRequest req, ServletResponse res,
FilterChain chain) throws IOException, ServletException {
String url = ((HttpServletRequest)req).getRequestURI();
if (url.indexOf("fckeditor") < 0) {
super.doFilter(req, res, chain);
} else {
chain.doFilter(req, res);
}
}
}
2. web.xml中这么配置:
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.j2cms.web.filter.MyStrutsFilterDispatcher</filter-class>
<init-param>
<param-name>actionPackages</param-name>
<param-value>**.**.**.action</param-value>
</init-param>
</filter>