image.png

image.png

1、在web的xml文件中配置监听器

image.png

  1. <context-param>
  2. <param-name>contextConfigLocation</param-name>
  3. <param-value>classpath:applicationContext.xml</param-value>
  4. </context-param>
  5. <!-- Bootstraps the root web application context before servlet initialization -->
  6. <listener>
  7. <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  8. </listener>

2、获取ioc容器

image.png

package com.hao.utils;

import org.apache.commons.beanutils.BeanUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.WebApplicationContext;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

/**
 * 把Map中的值注入到对应的javaBean属性中
 * @author shkstart
 * @create 2021-05 11:08
 */
public class WebUtils {

//    private static ApplicationContext ioc = new ClassPathXmlApplicationContext("applicationContext.xml");

    public static <T>T getBean(Class<T> clazz){
        WebApplicationContext ioc = ContextLoader.getCurrentWebApplicationContext();
        return ioc.getBean(clazz);
    }

    public static <T>  T copyParamToBean(Map value, T bean){
        try {
            BeanUtils.populate(bean,value);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

        return bean;
    }

    public static int parseInt(String strInt,int defaultValue){
        try {
            return Integer.parseInt(strInt);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return defaultValue;
    }

}