LOFTER for ipad —— 让兴趣,更有趣

点击下载 关闭
SpringMVC个人笔记 part2 底层实现方法
Nowakii 2018-10-10

继续更改controller,去掉login方法的参数,在类里面private两个参数

private String userName;

private String password;

并且使用source创建两个属性的get set方法

创建一个注解包:com.xxx.annotation 在此包里写一个注解类

代码:

package com.hpe.annotation;


import java.lang.annotation.Documented;

import java.lang.annotation.ElementType;

import java.lang.annotation.Inherited;

import java.lang.annotation.Retention;

import java.lang.annotation.RetentionPolicy;

import java.lang.annotation.Target;


@Target({ElementType.TYPE})

@Retention(RetentionPolicy.RUNTIME)

@Inherited

@Documented

public @interface SessionAttributes {

String[] names() default {};

}

通过这个注解类来调用控制器logincontroller

在此控制器中加入注解@SessionAttributes(names="{userName,admin}")

稍后我们会在前段控制器中调用注解的方法。

2.现在在前段控制器中写处理参数的方法

/**

 * 

 * 方法描述:处理前台传递的参数,反射调用set方法注入数据

 * param 处理类  处理类对象

 * void

 * @author Azure

 */

public void resolveParam (Class<?> controller,Object controllerInstance,HttpServletRequest request) throws Exception{

//3、填充数据

Field[] fields = controller.getDeclaredFields();

for(Field field: fields){

            String name = field.getName();

            String methodStr = "set"+name.toUpperCase().substring(0, 1)+name.substring(1);

            Method method2 = controller.getMethod(methodStr,new Class[]{field.getType()});

            if(field.getType().getSimpleName().equals("String")){

                method2.invoke(controllerInstance, request.getParameter(name));

            }else if(field.getType().getSimpleName().equals("Integer")){

                method2.invoke(controllerInstance, request.getParameter(name));

            }

        }

}

注解方法:

/**

 * 

 * 方法描述:解析注解,把需要储存在session的ket解析出来,并保存到session中

 * controller  类

 * mv对象包含返回页面信息

 *   requset

 */

public  void resolveAnnotation(Class<?> controller,ModelandView mv,HttpServletRequest request){

SessionAttributes sa = controller.getDeclaredAnnotation(SessionAttributes.class);

String[] names = sa.names();

//获得的userName  admin

String[] annoKeys=names[0].substring(1, names[0].length()-1).split(",");

    for(int i=0;i<annoKeys.length;i++){

    request.getSession().setAttribute(annoKeys[i], mv.getObjMap().get(annoKeys[i]));

    }

在上面get方法中 try catch中分别调用这两个方法

try {

//加载controller类

Class<?> controller = Class.forName(className);

//反射生成对象

Object controllerInstance = controller.newInstance();

//通过反射注入请求参数

resolveParam(controller, controllerInstance, req);

//获得方法对象,参数为方法名  参数的数据类型

Method method=controller.getMethod(methodName);

//使用方法对象调用

ModelandView mv=(ModelandView) method.invoke(controllerInstance);

    //解析mv中的对象map并封装到requset中

resolveReturnParam(req, mv);

//把注解中的定义放到session中

resolveAnnotation(controller, mv, req);

//页面跳转

req.getRequestDispatcher(mv.getViewName()).forward(req, resp);

} catch (Exception e) {

e.printStackTrace();

}





推荐文章
评论(0)
分享到
转载我的主页