Simplify request by reflection

When you submit data for adding, you can set the name attribute of input, and then servlet uses request.getParameter("name") to receive par...

When you submit data for adding, you can set the name attribute of input, and then servlet uses request.getParameter("name") to receive parameters. However, when there are many parameters, it will become very cumbersome, and you may write repeated code.

public void Insert(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { //Get parameters in request String Name = request.getParameter("name"); String PassWord = request.getParameter("password"); String Rid = request.getParameter("rid"); String Sex = request.getParameter("sex"); String Age = request.getParameter("age"); String Phone = request.getParameter("phone"); String Site = request.getParameter("site"); UserPo user = new UserPo(); user.setName(Name); user.setPassword(PassWord); if(Tools.isNum(Sex)){ user.setSex(Integer.parseInt(Sex)); } if(Tools.isNum(Age)){ user.setAge(Integer.parseInt(Age)); } user.setPhone(Phone); user.setSite(Site); if(Tools.isNum(Age)){ user.setRid(Integer.parseInt(Rid)); }

Then you can think that when we write the Update method, we need to acquire and process these fields. This makes coding hard, and the amount of repeated code is increasing.

Under the guidance of the teacher, I use the knowledge I have learned to encapsulate some simplified code, and simplify the code through reflection acquisition and assignment.

public static <T> T setSingleResultSet(HttpServletRequest request,Class<T> obj) { T instance = null; try { instance = obj.newInstance();//Create an instance of obj using newInstance Field[] fields = obj.getDeclaredFields();//Get the property field collection of this class for (int i = 0; i < fields.length; i++) { //Loop to get field names in turn String name = fields[i].getName(); //It should be noted here that since name is the field name in the obtained instance class, the value of the name property in the page must be the same as the field name in the entity class String Name = request.getParameter(name);//Get the value in the request //Capitalize name String replace = name.substring(0, 1).toUpperCase() + name.substring(1); //Gets the type of the property field Class<?> type = obj.getDeclaredField(name).getType(); //How to get this field Method setMethod = obj.getMethod("set" + replace, type); // Determine the type of data read //If there is no cyclically acquired field in the request, the value is null, and assigning null to UserPo will cause an exception //So we should judge and deal with the value if (type.isAssignableFrom(String.class)) { if (Name == null) { Name = ""; } setMethod.invoke(instance, Name); } else if (type.isAssignableFrom(int.class) || type.isAssignableFrom(Integer.class)) { if (Name == null) { Name = "0"; } setMethod.invoke(instance, Integer.parseInt(Name)); } else if (type.isAssignableFrom(Boolean.class) || type.isAssignableFrom(boolean.class)) { if (Name == null) { Name = "false"; } setMethod.invoke(instance, Boolean.parseBoolean(Name)); } else if (type.isAssignableFrom(Date.class)) { setMethod.invoke(instance, Name); } } } catch (NoSuchFieldException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SecurityException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchMethodException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvocationTargetException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InstantiationException e) { // TODO Auto-generated catch block e.printStackTrace(); } return instance; }

The method is called in servlet instead of the original code.

/* Above omitted*************** user.setPhone(Phone); user.setSite(Site); if(Tools.isNum(Age)){ user.setRid(Integer.parseInt(Rid)); }*/ UserPo user = BackInfoHelp.setSingleResultSet(request, UserPo.class); boolean success = service.insert(user); if(success){ request.getSession().setAttribute("strMsg", "insert success"); }else{ request.getSession().setAttribute("strMsg", "insert fial"); }

In this way, we can not only realize the function, but also avoid repeated code.

10 November 2019, 12:47 | Views: 8374

Add new comment

For adding a comment, please log in
or create account

0 comments