本例需要添加的依赖:
<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