三种前台与后台,传表单数据包含文件上传。第三Jackson 将数据映射成实体类
方法1
使用表单action 属性 直接访问后台,
后台是servlet
后台方法入参:protected void doPost(HttpServletRequest request, HttpServletResponse response)
方法中上传的文件处理:(这里只写了关键代码)
//解析请求之前先判断请求类型是否为文件上传类型 boolean isMultipart = ServletFileUpload.isMultipartContent(request); if(isMultipart==true){ //创建文件上传核心类 FileItemFactory factory = new DiskFileItemFactory(); // 实例化一个FileItem工厂,用来配置上传组件ServletFileUpload ServletFileUpload upload = new ServletFileUpload(factory); // 用以上工厂实例化上传组件 try{ //处理表单请求 List<FileItem> items = upload.parseRequest(request); Iterator<FileItem> iter = items.iterator(); while(iter.hasNext()){ FileItem item = (FileItem)iter.next(); if(item.isFormField()){// 如果是普通表单控件 fieldName = item.getFieldName();// 获得该字段名称 if(fieldName.equals("title")){ news.setTitle(item.getString("UTF-8"));//获得该字段值 }else if(fieldName.equals("categoryId")){ news.setCategoryId(Integer.parseInt(item.getString())); } }else{// 如果为文件域 String fileName = item.getName();// 获得文件名(全路径) if(fileName != null && !fileName.equals("")){ File fullFile = new File(fileName); File saveFile = new File(uploadFilePath,fullFile.getName());//将文件保存到指定的路径 item.write(saveFile); uploadFileName = fullFile.getName(); news.setPicPath(uploadFileName); bUpload = true; } } } }catch(Exception e){ e.printStackTrace(); } } System.out.println("上传成功之后的文件名:" + news.getPicPath()); //调用后台的方法,将新闻信息插入数据库中 News_detilService news_detilService = new News_detilServiceImpl(); bRet = news_detilService.addNews(news);
方法2
前台使用ajax 取得表单,直接把表单放入FormData()对象中表单发送过来
后台使用springMvc 处理
前端代码:(只写了关键代码!)
js:
$("#addUser").click(function(){ //var form=$("#form1"); //使用js 获取表单,在ajax中直接入参传后台 var form = new FormData(document.getElementById("form1")); $.ajax({ type:"POST", url:"../adduserSave", data:form, async: false, cache: false, contentType: false, processData: false, dataType:"json", success:function(data){ // 省略成功的处理 } })
springMvc的后台:(只写关键代码)
@RequestMapping(value="/adduserSave",method=RequestMethod.POST) @ResponseBody //入参的filename 是表单中的文件元素的 name属性!!!! public ResultUtil adduserSave(@RequestParam("filename") MultipartFile file, User user, HttpServletRequest request) { Map<String, Object> result=new HashMap<String, Object>(); String path = request.getSession().getServletContext().getRealPath("statics/images"); String fileName = file.getOriginalFilename(); File fil = new File(path, fileName); if(!fil.exists()){ fil.mkdirs(); } try { file.transferTo(fil); } catch (IllegalStateException | IOException e) { e.printStackTrace(); } String zpath=path+"\\"+fileName; user.setFile("statics/images/"+fileName); user.setJurisdiction("yes"); boolean flag=userService.addUser(user); if(flag) { // 对应的结果处理 } }
方法3
前端传 FormData 对象,文字数据转成JSON ,以键值对方式传入数据,
后台 springMvc处理通过jsonson 映射成实体类
前端代码:(只写关键代码)
/* 提交表单数据封装 */ $('#submit').click(function() { /* 获取表单信息封装 */ var shop = {}; if (isEdit) { shop.shopId = shopId; } shop.shopName = $('#shop-name').val(); shop.shopDesc = $('#shop-desc').val(); shop.shopCategory = { shopCategoryId: $("#shop-category").val() } //获得图片文件 var shopImg = $('#shop-img')[0].files[0]; var formData = new FormData(); //图片文件以键值对的方式存入 formData.append('shopImg', shopImg); //JSON.stringify(shop)将数据封装成 json formData.append('shopStr', JSON.stringify(shop)); formData.append('verifyCodeActual', verifyCodeActual); $.ajax({ url : (isEdit ? editShopUrl:registerShopUrl), type : 'POST', data : formData, contentType : false, processData : false, cache : false, success : function(data) { //相应处理 } }) });
后台代码:
参数入参是: private Map<String,Object> registerShop(HttpServletRequest request)
接收数据:
//接收并且转化接收的信息成实体类使用jackson String shopStr = HttpServletRequestUtil.getString(request, "shopStr"); Shop shop =null; ObjectMapper mapper = new ObjectMapper(); shop = mapper.readValue(shopStr, Shop.class);
图片处理:
//店铺图片 CommonsMultipartFile shopImg = null; //解析从request中得到上下文 CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver( request.getSession().getServletContext()); //得到的上下文来判断是否有文件流 if(commonsMultipartResolver.isMultipart(request)){ MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest)request; shopImg = (CommonsMultipartFile)multipartHttpServletRequest.getFile("shopImg"); }else{ modelMap.put("success", false); modelMap.put("errMsg", "上传图片不能为空"); }