一、界面不跳转:AJAX比较好。
举例:
前端:
if(filesArray.length>0) { $.ajax({ type: "post", url: "*********", //data:JSON.stringify(filesArray), data:{"filesArray":filesArray}, async: false, traditional: "true", dataType : "json", success: function(data) { //alert(data.code); if(data.code==100) { alert("导入操作成功!"); } else if(data.code==200) { alert("导入失败!"); } }, error: function (data) { } }); }
controller端:
@RequestMapping({"****"}) @ResponseBody public ReturnMsg ImportSelectedFiles(HttpServletRequest request, HttpServletResponse response, @RequestParam String[] filesArray) throws IOException { String CimeFilePath = request.getSession().getServletContext().getRealPath("/") + cimeFolder +"/"; System.out.println(CimeFilePath); String importPath; Map<String,Object> res_info = new HashMap<String,Object>(); //用户返回给浏览器的数据 if(null!=filesArray) { for(int i=0;i<filesArray.length;i++){ importPath = CimeFilePath + filesArray[i]; try{ //do something ************************ }catch(Exception e){ System.out.println("Test file read or write to mysql failed!"); res_info.put("error1",filesArray[i]+":文件读取失败或写库失败!"); return ReturnMsg.fail().add(res_info); } } return ReturnMsg.success().add(res_info); } res_info.put("error0","界面返回的文件未找到!"); return ReturnMsg.fail().add(res_info); }
二、对于界面会跳转的,比如前端form传递回后端controller的情况,后端的处理现在了解了大概几种情况:
1、如果只需要返回数据的,很简单,用函数的返回值就行了,注意设置@ResponseBody参数,表明返回的是数据。
2、如果只需要返回新的界面,很简单,用函数的返回值就行了,返回值写跳转的url地址。
具体的分为两种情况:重定向和请求转发:
重定向的写法:
@RequestMapping(value = "import/template") public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) { try { String fileName = "用户数据导入模板.xlsx"; List<User> list = Lists.newArrayList(); list.add(UserUtils.getUser()); new ExportExcel("用户数据", User.class, 2).setDataList(list).write(response, fileName).dispose(); return null; } catch (Exception e) { addMessage(redirectAttributes, "导入模板下载失败!失败信息:"+e.getMessage()); } return "redirect:" + adminPath + "/sys/user/list?repage"; }
请求转发或请求定位的类似形式:
@RequestMapping(value = "modifyPwd") public String modifyPwd(String oldPassword, String newPassword, Model model) { User user = UserUtils.getUser(); if (StringUtils.isNotBlank(oldPassword) && StringUtils.isNotBlank(newPassword)){ ****************** } model.addAttribute("user", user); return "modules/sys/userModifyPwd"; }
3、对于同时需要返回界面和数据的:
3.1 可以通过RedirectAttributes类传递数据
redirectAttributes是spring提供的新特性,具有页面重定向,能够向重定向的页面传递参数的功能。
举例:
界面:
<%@ page contentType="text/html;charset=UTF-8" %> <html> <head> <title>个人信息</title> <meta name="decorator" content="default"/> <script type="text/javascript"> $(document).ready(function() { $("#inputForm").validate({ submitHandler: function(form){ loading('正在提交,请稍等...'); form.submit(); }, errorContainer: "#messageBox", }); }); </script> </head> <body> <ul class="nav nav-tabs"> <li class="active"><a href="${ctx}/sys/user/info">个人信息</a></li> <li><a href="${ctx}/sys/user/modifyPwd">修改密码</a></li> </ul><br/> <form:form id="inputForm" modelAttribute="user" action="${ctx}/sys/user/info" method="post" class="form-horizontal"><%-- <form:hidden path="email" htmlEscape="false" maxlength="255" class="input-xlarge"/> <sys:ckfinder input="email" type="files" uploadPath="/mytask" selectMultiple="false"/> --%> <sys:message content="${message}"/> <div class="control-group"> </div> </form:form> </body> </html>
后端:
@RequestMapping(value = "***", method=RequestMethod.POST) public String exportFile(User user, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) { try { String fileName = "用户数据"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx"; Page<User> page = systemService.findUser(new Page<User>(request, response, -1), user); new ExportExcel("用户数据", User.class).setDataList(page.getList()).write(response, fileName).dispose(); return null; } catch (Exception e) { addMessage(redirectAttributes, "导出用户失败!失败信息:"+e.getMessage()); } return "redirect:" + adminPath + "/sys/user/list?repage"; }
3.2 通过getRequestDispatcher
request.setAttribute("message",message); String backPath = ***********; try { request.getRequestDispatcher(backPath).forward(request, response); } catch (ServletException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }