编程语言
首页 > 编程语言> > java内省

java内省

作者:互联网

1.Java的内省机制是基于JavaBean的

主要是用在框架底层

2.让后台的Model对象统一的接收表单提交过来的参数

servlet


public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        user u=new user();
        populate(request.getParameterMap(),u);
        System.out.println(u);
        
    }
    
    private void populate(Map<String,String[]> map,user u){
        try {
            Map<String,String[]> params=map;
            //1 获得 java Bean的描述信息
            BeanInfo info =Introspector.getBeanInfo(user.class);
            //2 获得 User中的属性信息
            PropertyDescriptor [] pds =info.getPropertyDescriptors();
            //3 遍历属性信息
            for (PropertyDescriptor pd : pds) {
                String[] param=params.get(pd.getName());
                if (param!=null && param.length>0) {
                    pd.getWriteMethod().invoke(u, param[0]);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

javaBean


public class user {
    private String name;
    private String password;
    public user(){
        
        super();
    }
    
    public String getName() {
        return name;
    }
 
    public void setName(String name) {
        this.name = name;
    }
 
    public String getPassword() {
        return password;
    }
 
    public void setPassword(String password) {
        this.password = password;
    }
    
    @Override
    public String toString() {
        return "user [name=" + name + ", password=" + password + " ]";
    }

}

jsp

<body>
        <form action="/JavaBean/BServlet" method="post" >
            用户名:<input type="text" name="name" /><br>
            密码:<input type="password" name="password" /><br>
        
            <input type="submit" /><br>
        </form>
 </body>

标签:java,String,内省,param,user,password,public,name
来源: https://www.cnblogs.com/moris5013/p/10977774.html