/**
* action注解:ActionName相当于web.xml配置中的url-pattern
* @author linling
*
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface ActionAnnotation
{
String ActionName() default "";
ResultAnnotation[] results() default {};
}
/**
* 返回注解对象:name相当于struts配置中的result的name,包括'SUCCESS'、'NONE'、'ERROR'、'INPUT'、'LOGIN';value相当于struts配置中对应返回跳转内容
* @author linling
*
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface ResultAnnotation
{
ResultType name() default ResultType.SUCCESS;
String value() default "index.jsp";
}
/**
* 实现模拟struts根据配置文件跳转至action执行相应方法中需要的内容
* @author linling
*
*/
public class ActionContext
{
/**
* 相当于web.xml中url-pattern,唯一的
*/
private String Url;
/**
* ActionAnnotation注解对应方法,也就是action中要执行的方法
*/
private String method;
/**
* ActionAnnotation中的Result,对应action方法返回的类型。例如:key:'SUCCESS';value:'index.jsp'
*/
private Map<ResultType, String> results;
/**
* action的类
*/
private Class<?> classType;
/**
* action的对象
*/
private Object action;
/**
* 方法参数类型
*/
private Class<?>[] paramsType;
/**
* 方法参数的名称,注意这里方法名称需要和上面paramType参数一一对应
* 可以理解为是struts中action中的属性
*/
private String[] actionParamsName;
/**
* 本次请求的HttpServletRequest
*/
private HttpServletRequest request;
/**
* 本次请求的HttpServletResponse
*/
private HttpServletResponse response;
/**
* 遍历scan_package包下的class文件,将使用了ActionAnnotation注解的方法进行解析,组装成ActionContext对象 并放入urlMap中
* @param real_path
* @param scan_package
* @throws ClassNotFoundException
* @throws InstantiationException
* @throws IllegalAccessException
* @throws NotFoundException
*/
public static void analysePackage(String real_path, String scan_package) throws ClassNotFoundException, InstantiationException, IllegalAccessException, NotFoundException
{
File file = new File(real_path);
if(file.isDirectory())
{
File[] files = file.listFiles();
for(File f : files)
{
analysePackage(f.getAbsolutePath(),scan_package);
}
}
else
{
String str = real_path.replaceAll("/", ".");
if (str.indexOf("classes." + scan_package) <= 0 || !str.endsWith(".class"))
{
return;
}
String fileName = str.substring(str.indexOf(scan_package),str.lastIndexOf(".class"));
Class<?> classType = Class.forName(fileName);
Method[] methods = classType.getMethods();
for(Method method : methods)
{
if(method.isAnnotationPresent(ActionAnnotation.class))
{
ActionContext actionContext = new ActionContext();
ActionAnnotation actionAnnotation = (ActionAnnotation)method.getAnnotation(ActionAnnotation.class);
String url = actionAnnotation.ActionName();
ResultAnnotation[] results = actionAnnotation.results();
if(url.isEmpty() || results.length < 1)
{
throw new RuntimeException("method annotation error! method:" + method + " , ActionName:" + url + " , result.length:" + results.length);
}
actionContext.setUrl(url);
actionContext.setMethod(method.getName());
Map<ResultType, String> map = new HashMap<ResultType, String>();
for(ResultAnnotation result : results)
{
String value = result.value();
if(value.isEmpty())
{
throw new RuntimeException("Result name() is null");
}
map.put(result.name(), value);
}
actionContext.setResults(map);
actionContext.setClassType(classType);
actionContext.setAction(classType.newInstance());
actionContext.setParamsType(method.getParameterTypes());
actionContext.setActionParamsName(getActionParamsName(classType, method.getName()));
urlMap.put(url, actionContext);
}
}
}
}
/**
* 根据 参数类型parasType 和 参数名actinParamsName 来解析请求request 构建参数object[]
* @param request
* @param paramsType
* @param actionParamsName
* @return
* @throws InstantiationException
* @throws IllegalAccessException
* @throws IllegalArgumentException
* @throws InvocationTargetException
* @throws NoSuchMethodException
* @throws SecurityException
*/
public static Object[] getParams(HttpServletRequest request, Class<?>[] paramsType, String[] actionParamsName) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException
{
Object[] objects = new Object[paramsType.length];
for(int i = 0; i < paramsType.length; i++)
{
Object object = null;
if(ParamsUtils.isBasicType(paramsType[i]))
{
objects[i] = ParamsUtils.getParam(request, paramsType[i], actionParamsName[i]);
}
else
{
Class<?> classType = paramsType[i];
object = classType.newInstance();
Field[] fields = classType.getDeclaredFields();
for(Field field : fields)
{
Map<String, String[]> map = request.getParameterMap();
for(Iterator<String> iterator = map.keySet().iterator(); iterator.hasNext();)
{
String key = iterator.next();
if(key.indexOf(".") <= 0)
{
continue;
}
String[] strs = key.split("\\.");
if(strs.length != 2)
{
continue;
}
if(!actionParamsName[i].equals(strs[0]))
{
continue;
}
if(!field.getName().equals(strs[1]))
{
continue;
}
String value = map.get(key)[0];
classType.getMethod(convertoFieldToSetMethod(field.getName()), field.getType()).invoke(object, value);
break;
}
}
objects[i] = object;
}
}
return objects;
}
public class LoginAction
{
@ActionAnnotation(ActionName="login.action",results={@ResultAnnotation(name=ResultType.SUCCESS,value="index.jsp"),@ResultAnnotation(name=ResultType.LOGIN,value="login.jsp")})
public ResultType login(String name, String password)
{
if("hello".equals(name) && "world".equals(password))
{
return ResultType.SUCCESS;
}
return ResultType.LOGIN;
}
@ActionAnnotation(ActionName="loginForUser.action",results={@ResultAnnotation(name=ResultType.SUCCESS,value="index.jsp"),@ResultAnnotation(name=ResultType.LOGIN,value="login.jsp")})
public ResultType loginForUser(int number, LoginPojo loginPojo)
{
if("hello".equals(loginPojo.getUsername()) && "world".equals(loginPojo.getPassword()))
{
return ResultType.SUCCESS;
}
return ResultType.LOGIN;
}
}
<servlet>
<servlet-name>StrutsInitServlet</servlet-name>
<servlet-class>com.bayern.struts.one.servlet.StrutsInitServlet</servlet-class>
<init-param>
<param-name>scan_package</param-name>
<param-value>com.bayern.struts.one</param-value>
</init-param>
<load-on-startup>10</load-on-startup>
</servlet>
<servlet>
<servlet-name>DispatcherServlet</servlet-name>
<servlet-class>com.bayern.struts.one.servlet.DispatcherServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>DispatcherServlet</servlet-name>
<url-pattern>*.action</url-pattern>
</servlet-mapping>
ublic void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
request.setCharacterEncoding("utf-8");
String url = request.getServletPath().substring(1);
ActionContext actionContext = DispatcherServletUtil.urlMap.get(url);
if(actionContext != null)
{
actionContext.setRequest(request);
actionContext.setResponse(response);
try
{
Object[] params = DispatcherServletUtil.getParams(request, actionContext.getParamsType(), actionContext.getActionParamsName());
Class<?> classType = actionContext.getClassType();
Method method = classType.getMethod(actionContext.getMethod(), actionContext.getParamsType());
ResultType result = (ResultType)method.invoke(actionContext.getAction(), params);
Map<ResultType,String> results = actionContext.getResults();
if(results.containsKey(result))
{
String toUrl = results.get(result);
request.getRequestDispatcher(toUrl).forward(request, response);
}
else
{
throw new RuntimeException("result is error! result:" + result);
}
}
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有