首页 > 其他分享 >通过反射的内省机制获取URL地址中出入的参数,并封装到对应的实体类中

通过反射的内省机制获取URL地址中出入的参数,并封装到对应的实体类中

时间:2022-10-09 16:25:00浏览次数:57  
标签:实体类 return String URL void 内省 private Integer public

本例需要添加的依赖:

<dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.5.7</version>
    </dependency>
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>8.0.28</version>
    </dependency>
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>druid</artifactId>
      <version>1.2.8</version>
    </dependency>
    <!--mybatis分页插件-->
    <dependency>
      <groupId>com.github.pagehelper</groupId>
      <artifactId>pagehelper</artifactId>
      <version>5.3.1</version>
    </dependency>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>3.1.0</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>fastjson</artifactId>
      <version>2.0.12</version>
    </dependency>
GoodsInfo 实体类:
import java.util.Objects;

/**
 * GoodsInfo和GoodsType的映射关系
 * N        :  1
 *
 * 一个商品必定会对应一个商品分类
 */
public class GoodsInfo {
    private Integer goodsId;
    private String goodsName;
    private String goodsSerial;
    private String goodsImg;
    private Integer goodsSort;
    // 一级分类 在表中是一个外键
    private GoodsType parentType;
    // 二级分类 在表中是一个外键
    private GoodsType middleType;
    // 三级分类 在表中是一个外键
    private GoodsType subType;
    private Integer storeNumber;
    private Integer selledNumber;
    private Integer warnNumber;
    private Double marketPrice;
    private Double shopPrice;
    private Integer goodsEnable;
    private String summary;
    private Integer isnew;
    private Integer ishot;
    private Integer isrecommand;

    public Integer getGoodsId() {
        return goodsId;
    }

    public void setGoodsId(Integer goodsId) {
        this.goodsId = goodsId;
    }

    public String getGoodsName() {
        return goodsName;
    }

    public void setGoodsName(String goodsName) {
        this.goodsName = goodsName;
    }

    public String getGoodsSerial() {
        return goodsSerial;
    }

    public void setGoodsSerial(String goodsSerial) {
        this.goodsSerial = goodsSerial;
    }

    public String getGoodsImg() {
        return goodsImg;
    }

    public void setGoodsImg(String goodsImg) {
        this.goodsImg = goodsImg;
    }

    public Integer getGoodsSort() {
        return goodsSort;
    }

    public void setGoodsSort(Integer goodsSort) {
        this.goodsSort = goodsSort;
    }

    public GoodsType getParentType() {
        return parentType;
    }

    public void setParentType(GoodsType parentType) {
        this.parentType = parentType;
    }

    public GoodsType getMiddleType() {
        return middleType;
    }

    public void setMiddleType(GoodsType middleType) {
        this.middleType = middleType;
    }

    public GoodsType getSubType() {
        return subType;
    }

    public void setSubType(GoodsType subType) {
        this.subType = subType;
    }

    public Integer getStoreNumber() {
        return storeNumber;
    }

    public void setStoreNumber(Integer storeNumber) {
        this.storeNumber = storeNumber;
    }

    public Integer getSelledNumber() {
        return selledNumber;
    }

    public void setSelledNumber(Integer selledNumber) {
        this.selledNumber = selledNumber;
    }

    public Integer getWarnNumber() {
        return warnNumber;
    }

    public void setWarnNumber(Integer warnNumber) {
        this.warnNumber = warnNumber;
    }

    public Double getMarketPrice() {
        return marketPrice;
    }

    public void setMarketPrice(Double marketPrice) {
        this.marketPrice = marketPrice;
    }

    public Double getShopPrice() {
        return shopPrice;
    }

    public void setShopPrice(Double shopPrice) {
        this.shopPrice = shopPrice;
    }

    public Integer getGoodsEnable() {
        return goodsEnable;
    }

    public void setGoodsEnable(Integer goodsEnable) {
        this.goodsEnable = goodsEnable;
    }

    public String getSummary() {
        return summary;
    }

    public void setSummary(String summary) {
        this.summary = summary;
    }

    public Integer getIsnew() {
        return isnew;
    }

    public void setIsnew(Integer isnew) {
        this.isnew = isnew;
    }

    public Integer getIshot() {
        return ishot;
    }

    public void setIshot(Integer ishot) {
        this.ishot = ishot;
    }

    public Integer getIsrecommand() {
        return isrecommand;
    }

    public void setIsrecommand(Integer isrecommand) {
        this.isrecommand = isrecommand;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        GoodsInfo goodsInfo = (GoodsInfo) o;
        return Objects.equals(goodsId, goodsInfo.goodsId);
    }

    @Override
    public int hashCode() {
        return Objects.hash(goodsId);
    }

    @Override
    public String toString() {
        return "GoodsInfo{" +
                "goodsId=" + goodsId +
                ", goodsName='" + goodsName + '\'' +
                ", goodsSerial='" + goodsSerial + '\'' +
                ", goodsImg='" + goodsImg + '\'' +
                ", goodsSort=" + goodsSort +
                ", parentType=" + parentType +
                ", middleType=" + middleType +
                ", subType=" + subType +
                ", storeNumber=" + storeNumber +
                ", selledNumber=" + selledNumber +
                ", warnNumber=" + warnNumber +
                ", marketPrice=" + marketPrice +
                ", shopPrice=" + shopPrice +
                ", goodsEnable=" + goodsEnable +
                ", summary='" + summary + '\'' +
                ", isnew=" + isnew +
                ", ishot=" + ishot +
                ", isrecommand=" + isrecommand +
                '}';
    }
}
GoodsType 实体类:
public class GoodsType {
    private Integer typeId; // 假设当前查询的商品分类的编号为1
    private String typeName;
    private String typeImg;
    private Integer sort;
    private Integer parentId;
    private String parentLevel;
    private Integer showNav;
    private Integer showIndex;
    private String icon;
    private String value2;
    private String value3;
    private List<GoodsInfo> goodsInfos;
    public GoodsType() {
    }

    public Integer getTypeId() {
        return typeId;
    }

    public void setTypeId(Integer typeId) {
        this.typeId = typeId;
    }

    public String getTypeName() {
        return typeName;
    }

    public void setTypeName(String typeName) {
        this.typeName = typeName;
    }

    public String getTypeImg() {
        return typeImg;
    }

    public void setTypeImg(String typeImg) {
        this.typeImg = typeImg;
    }

    public Integer getSort() {
        return sort;
    }

    public void setSort(Integer sort) {
        this.sort = sort;
    }

    public Integer getParentId() {
        return parentId;
    }

    public void setParentId(Integer parentId) {
        this.parentId = parentId;
    }

    public String getParentLevel() {
        return parentLevel;
    }

    public void setParentLevel(String parentLevel) {
        this.parentLevel = parentLevel;
    }

    public Integer getShowNav() {
        return showNav;
    }

    public void setShowNav(Integer showNav) {
        this.showNav = showNav;
    }

    public Integer getShowIndex() {
        return showIndex;
    }

    public void setShowIndex(Integer showIndex) {
        this.showIndex = showIndex;
    }

    public String getIcon() {
        return icon;
    }

    public void setIcon(String icon) {
        this.icon = icon;
    }

    public String getValue2() {
        return value2;
    }

    public void setValue2(String value2) {
        this.value2 = value2;
    }

    public String getValue3() {
        return value3;
    }

    public void setValue3(String value3) {
        this.value3 = value3;
    }

    public List<GoodsInfo> getGoodsInfos() {
        return goodsInfos;
    }

    public void setGoodsInfos(List<GoodsInfo> goodsInfos) {
        this.goodsInfos = goodsInfos;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        GoodsType goodsType = (GoodsType) o;
        return Objects.equals(typeId, goodsType.typeId);
    }

    @Override
    public int hashCode() {
        return Objects.hash(typeId);
    }

    @Override
    public String toString() {
        return "GoodsType{" +
                "typeId=" + typeId +
                ", typeName='" + typeName + '\'' +
                ", typeImg='" + typeImg + '\'' +
                ", sort=" + sort +
                ", parentId=" + parentId +
                ", parentLevel='" + parentLevel + '\'' +
                ", showNav=" + showNav +
                ", showIndex=" + showIndex +
                ", icon='" + icon + '\'' +
                ", value2='" + value2 + '\'' +
                ", value3='" + value3 + '\'' +
                '}';
    }
}

查询参数对象:

/**
 * DTO: data transfer object ,  数据传输对象
 * 将来自于客户端查询参数封装到一个dto对象中,以供mybatis动态查询使用
 */
public class GoodsInfoDto extends PageDto{
    private Integer storeNumber;
    private Double marketPrice;
    private Integer selledNumber;

    public Integer getStoreNumber() {
        return storeNumber;
    }

    public void setStoreNumber(Integer storeNumber) {
        this.storeNumber = storeNumber;
    }

    public Double getMarketPrice() {
        return marketPrice;
    }

    public void setMarketPrice(Double marketPrice) {
        this.marketPrice = marketPrice;
    }

    public Integer getSelledNumber() {
        return selledNumber;
    }

    public void setSelledNumber(Integer selledNumber) {
        this.selledNumber = selledNumber;
    }

    @Override
    public String toString() {
        return "GoodsInfoDto{" +
                "pageNumber = " + super.getPageNum() +
                ",pageSize = " + super.getPageSize() +
                ",storeNumber=" + storeNumber +
                ", marketPrice=" + marketPrice +
                ", selledNumber=" + selledNumber +
                '}';
    }
}

继承自PageDto类:

public class PageDto {
    // 当前页码
    private Integer pageNum = 1;
    // 每页显示的条数
    private Integer pageSize = 5;

    public Integer getPageNum() {
        return pageNum;
    }

    public void setPageNum(Integer pageNum) {
        this.pageNum = pageNum;
    }

    public Integer getPageSize() {
        return pageSize;
    }

    public void setPageSize(Integer pageSize) {
        this.pageSize = pageSize;
    }
}

servlet类:

@WebServlet("/goods")
public class GoodsInfoServlet extends HttpServlet{
    GoodsInfoService service = new GoodsInfoServiceImpl();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //String name = Thread.currentThread().getName();
        //System.out.println("当前负责处理请求的线程为:" + name + ", 当前所访问的servlet对象为:" + this);
        //设置编码方式
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");

        ///////////////////////////第一种写法//////////////////////////////
        // 读取request请求中的参数,并封装到一个Map集合中
        //Map<String, String> map = RequestUtil.parameter2Map(req);
        // 利用反射和内省机制,将map集合中的键值映射为一个具体的GoodsInfoDto的对象
        //GoodsInfoDto goodsInfoDto = RequestUtil.convertMap2Object(GoodsInfoDto.class, map);

        /////////////////////////////第二种写法//////////////////////////////
        // 原始的写法,一次获取url参数中的所有参数
        /*String pageNumber = req.getParameter("pageNumber");
        String pageSize = req.getParameter("pageSize");
        String storeNumber = req.getParameter("storeNumber");
        String selledNumber = req.getParameter("selledNumber");
        String marketPrice = req.getParameter("marketPrice");

        // 手动实例化dto对象,并将参数转型赋值给dto
        GoodsInfoDto goodsInfoDto = new GoodsInfoDto();
        if (pageSize != null) {
            goodsInfoDto.setPageSize(Integer.valueOf(pageSize));
        }
        if (pageNumber != null) {
            goodsInfoDto.setPageNumber(Integer.valueOf(pageNumber));
        }
        if (storeNumber != null) {
            goodsInfoDto.setStoreNumber(Integer.valueOf(storeNumber));
        }
        if (selledNumber != null) {
            goodsInfoDto.setSelledNumber(Integer.valueOf(selledNumber));
        }
        if (marketPrice != null) {
            goodsInfoDto.setMarketPrice(Double.valueOf(marketPrice));
        }*/

        /////////////////////////第三种写法///////////////////////
        Map<String, String> map = RequestUtil.parameter2Map(req);
        // 将map集合转换为json字符串
        String jsonString = JSONObject.toJSONString(map);
        // 利用fastjson将json字符串还原为java对象
        GoodsInfoDto goodsInfoDto = JSONObject.parseObject(jsonString, GoodsInfoDto.class);

        System.out.println("goodsInfoDto=====" + goodsInfoDto);

        //调用业务逻辑层开始查询
        Result result = service.selectByCondition(goodsInfoDto);

        //将result对象转换为json字符串
        String json = JSONObject.toJSONString(result);

        // 告诉客户端,本次响应的结果为json字符串
        resp.setContentType("application/json");
        try (PrintWriter writer = resp.getWriter()) {
            // 将json响应给客户端
            writer.write(json);
            writer.flush();
        }
    }
}

RequestUtil类:

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.nio.charset.StandardCharsets;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;

public class RequestUtil {

    /**
     * 从request请求中,提取url参数,并封装到一个map集合中
     * @param request
     * @return
     */
    public static Map<String, String> parameter2Map(HttpServletRequest request) {
        Map<String, String> map = new HashMap<>();

        // 一个可迭代的枚举,每一个元素为url参数
        Enumeration<String> parameterNames = request.getParameterNames();
        while (parameterNames.hasMoreElements()) {
            // 获取所有的参数
            String parameter = parameterNames.nextElement();
            // 获取参数的值
            String value = request.getParameter(parameter);
            map.put(parameter, value);
        }

        return map;
    }

    /**
     * 将集合中的键值转换为泛型T的对象.
     * BUG:不能转换弗雷中的属性
     * @param tClass
     * @param map
     * @param <T>
     * @return
     */
    public static <T> T convertMap2Object(Class<T> tClass, Map<String, String> map) {
        try {
            // 实例化空对象
            T t = tClass.newInstance();
            Map<String, PropertyDescriptor> propertyDescriptorMap = new HashMap<>();
            try {
                // 得到tClass类对应类信息
                BeanInfo beanInfo = Introspector.getBeanInfo(tClass);
                // 得到tClass类的所有属性描述符,从而得到他们的set方法
                PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();

                //将属性描述符已属性名和PropertyDescriptor的映射到Map集合
                for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
                    // 排除掉class
                    if (propertyDescriptor.getName().equals("class")) continue;
                    // 已属性名作为键,属性描述符作为值,保存到map集合
                    propertyDescriptorMap.put(propertyDescriptor.getName(), propertyDescriptor);
                }
            } catch (IntrospectionException e) {
                e.printStackTrace();
            }

            // 遍历map,将map中所有的键值映射为泛型T对象的属性上
            map.forEach((key,value) -> {
                try {
                    // 从属性映射中得到当前key键对应的属性
                    PropertyDescriptor propertyDescriptor = propertyDescriptorMap.get(key);
                    // 基于内省机制获取tClass对应的属性的封装方法
                    Method writeMethod = propertyDescriptor.getWriteMethod(); // setXxx封装方法
                    Class<?> type = propertyDescriptor.getPropertyType(); // 得到属性的类型
                    // 获取属性类型对应的转换器
                    Function<String, Object> function = Converters.lookup(type);
                    // 通过类型转换器,将字符串value转换为属性对应的类型
                    Object apply = function.apply(value);
                    //调用封装方法,为属性赋值
                    writeMethod.invoke(t, apply);
                }catch (InvocationTargetException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            });

            return t;
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }

        return null;
    }

    public static String extractJson(HttpServletRequest req) throws IOException {
        try (// 字节输入流
             ServletInputStream inputStream = req.getInputStream();
             // 将字节输入流转换为字符输入流
             InputStreamReader reader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
             // 缓冲流
             BufferedReader bufferedReader = new BufferedReader(reader)) {

            StringBuffer stringBuffer = new StringBuffer();
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                stringBuffer.append(line);
            }
            return stringBuffer.toString();
        }
    }
}
Converters类:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;

public class Converters {
    private static Map<Class<?>, Function<String,Object>> converts;

    static {
        // 将字符串转换为Integer的对象
        Function<String, Integer> integerFunction = (value) -> Integer.valueOf(value);
        // 将字符串转换为Double的对象
        Function<String, Double> doubleFunction = (value) -> Double.valueOf(value);

        // 将字符串转换为日期的对象
        Function<String, Date> dateFunction = (value) -> {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date = null;
            try {
                date = format.parse(value);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            return date;
        };

        // 提起注册了两个转换器
        converts = new HashMap(){{
            put(Integer.class,integerFunction);
            put(Double.class,doubleFunction);
            put(Date.class, dateFunction);
        }};
    }

    /**
     * 对外提供自定义注册转换的方法
     * @param aClass
     * @param function
     * @param <T>
     */
    public static <T> void register(Class<T> aClass, Function<String, Object> function) {
        converts.put(aClass, function);
    }

    public static Function<String, Object> lookup(Class<?> aClass) {
        if (!converts.containsKey(aClass)) {
            throw new RuntimeException("尚未注册" + aClass.getName() + "对应的转换器");
        }
        return converts.get(aClass);
    }
}

测试方法:

 @Test
    public void test3(){
        Map<String, String> map = new HashMap<String, String>(){{
            put("storeNumber", "100");
            put("marketPrice", "200");
            put("selledNumber", "20");
            put("pageNum", "5");
            put("pageSize", "10");
        }};

        GoodsInfoDto goodsInfoDto = RequestUtil.convertMap2Object(GoodsInfoDto.class, map);
        System.out.println(goodsInfoDto);
    }

测试效果图:

 

标签:实体类,return,String,URL,void,内省,private,Integer,public
From: https://www.cnblogs.com/huang2979127746/p/16772537.html

相关文章

  • 微信公众号支付报错:当前页面的url未注册
    问题描述公众号支付报错:“当前页面的URL未注册”原因分析用户实际的支付目录必须和在微信支付商户平台设置的一致,否则会报错"当前页面的URL未注册"​​​支付授权目录:商户......
  • IIS URL重写实现代理输出
    由于某些需要,我们可能需要通过代理输出其它服务器内容,并用使用https。下面使用两条规则,先转向https然后再使用代理输出。IIS版本需要7.0及以上版本 在web.config配置如......
  • URL地址
    使用@RequestMapping注解可以在类/方法上加@Controller@RequestMapping("url")//http://localhost:8080/url/u01.do类级别publicclassUrlController{@Reque......
  • Spring Lombok 实体类死循环问题
    在SpringJPA1对多查询的时候出现死循环的问题。如下图所示:所有的配置都是正确的的,就是没有办法获得数据,并且出现死循环问题和解决因为使用lombak的 @Data ,在toString(......
  • 漏洞修复:tomcat中间件修复 检测到目标URL存在http host头攻击漏洞
    漏洞名称:检测到目标URL存在httphost头攻击漏洞风险级别:中危修复方案:修改tomcat\conf\server.xml打开server.xml配置文件,找到如下配置:  将Host里name的值localhost......
  • Java如何调用HttpURLConnection类模拟浏览器访问呢?
    下文笔者讲述使用Java代码模拟浏览器请求的方法分享,如下所示:实现思路:使用HttpURLConnection类即可模拟浏览器访问例:packagecom.java265.other;importjava.......
  • 从输入url到页面完成加载发生了什么(完整版)
    在写这篇文章之前本想着这个知识点涉及知识点太多太杂,找一篇大牛写的看看就算了,但是看了大概七八篇后,内心更纠结了——......
  • Flask学习笔记(九)-构造URL(url_for)和重定向
    一、构造URL(url_for)一般我们通过一个URL就可以执行到某一个函数。如果反过来,我们知道一个函数,怎么去获得这个URL呢?url_for函数就可以帮我们实现这个功能。url_for()函数接......
  • # github报错:The requested URL returned error:
    一、重新绑定密匙ssh-keygen-trsa-C'[email protected]'按下enter记录下生成的路径:C:\Users\Administrator.ssh从提示的路径找到对应的.ssh文件,打开id_rsa.pub文件......
  • curl查看请求是走http还https
    下面是http请求过程curl-vhttp://www.boyblue.xyz*Abouttoconnect()towww.boyblue.xyzport80(#0)*Trying192.168.1.28...*Connectedtowww.boyblue.x......