- 保存表单提交数据
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;
@WebServlet("/register")
public class AnswerThreeRegisterServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Map<String, String[]> parameterMap = request.getParameterMap();
User user = new User();
try {
BeanUtils.toBean(parameterMap, user);
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
response.getWriter().println(user);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
import com.sun.xml.internal.ws.util.StringUtils;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Map;
import java.util.Set;
public class BeanUtils {
private static final String PRE_FIX = "set";
public static void toBean(Map<String, String[]> parameterMap, Object user) throws InvocationTargetException, IllegalAccessException {
Set<String> keySet = parameterMap.keySet();
Class<?> userClass = user.getClass();
for (String key : keySet) {
String[] values = parameterMap.get(key);
Field field = null;
Method method = null;
String simpleName = "";
try {
field = userClass.getDeclaredField(key);
simpleName = field.getType().getSimpleName();
method = userClass.getDeclaredMethod(PRE_FIX + StringUtils.capitalize(key), field.getType());
} catch (NoSuchFieldException | NoSuchMethodException e) {
e.printStackTrace();
}
if("String".equalsIgnoreCase(simpleName)){
method.invoke(user,values[0]);
}else if("int".equalsIgnoreCase(simpleName)){
method.invoke(user, Integer.parseInt(values[0]));
}else if("double".equalsIgnoreCase(simpleName)){
method.invoke(user, Double.parseDouble(values[0]));
}else if("String[]".equalsIgnoreCase(simpleName)){
method.invoke(user,new Object[]{values});
}else{
throw new UnsupportedOperationException("暂不支持除了简单数据类型以外的封装");
}
}
}
}