public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
try {
User u = new User();
System.out.println("封裝數據前:"+u);
//獲取表單數據
Map<String,String[]> map = request.getParameterMap();
for (Map.Entry<String, String[]> m : map.entrySet()) {
String name = m.getKey();
String[] value = m.getValue();
//創建一屬性描述器
PropertyDescriptor pd = new PropertyDescriptor(name,User.class);
//得到setter屬性
Method setter = pd.getWriteMethod();
if(value.length==1){
setter.invoke(u, value[0]);//給一個值的變量賦值
}else{
setter.invoke(u, (Object)value);//相當於給復選框賦值
}
}
System.out.println("封裝數據後:"+u);
} catch (Exception e) {
e.printStackTrace();
}
}
報錯:
封裝數據前:User [userName=null, pwd=null, sex=null, hobby=null, city=null]
java.lang.IllegalArgumentException: argument type mismatch
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at Demon.servlet.servletDemo3.doGet(servletDemo3.java:39)
at Demon.servlet.servletDemo3.doPost(servletDemo3.java:80)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:646)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1040)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:607)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:315)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
at java.lang.Thread.run(Thread.java:619)
這個是哪裡錯了
肯定有個類型不匹配,你的請求參數都是string類型的,但是你的User類的屬性並不都是string類型的,直接調用設置就可能報這個異常了。你的sex屬性是什麼類型呢?