学习角色管理模块错误总结---基于SpringMVC框架

   总是不明白jsp页面与controller交互,前台数据如何传到后台,后台数据如何传到前台。

一,保存

    写保存功能时,jsp写了一个function,当保存成功时,将result置为“1”,弹出提示框“保存成功”,不然置“0”,提示失败。

    jsp和controller之间是通过把数据转为json形式传输的,当前台将需要保存的表单提交,数据转为json传到后台。springMVC框架会检索javabean,new一个bean进行匹配,使得数据属性不变,前台是Role对象,在controller中就可以直接处理Role对象,而不需要进行json转换过程。前台是什么,后台直接用什么,属性也一样,前台String id ,后台也是String id。

    保存时,controller传入参数直接可以为Role对象,然后进行保存数据库操作。

    向前台返回标志位时,使用Map或者Response对象,均可以自动转为json传输,或者String--转为json---推送前台。

//角色的保存功能controller部分

@ResponseBody @RequestMapping(value = "/saveRole" ,method = RequestMethod.POST) public Map<String,Object>saveRole(Role param)throws IOException{ String msg; Map<String,Object> result = new HashMap<String,Object>(); try{ if (StringUtils.isNotEmpty(param.getRoleCode())&&StringUtils.isNotEmpty(param.getRoleName())){ if(kroleService.isExistRoleCode(param)){ result.put("result","-1"); }else{ msg = kroleService.saveRole(param); result.put("result", msg); } }else result.put("result", "-1"); }catch(Exception e){ result.put("result", "-1"); } return result; } //为对比,引入其他模块代码。 @RequestMapping(value = "task/saveTaskPlan") public void saveTaskPlan(TaskPlan taskPlan, HttpServletResponse response){ String resultMessage = "保存成功!"; try { resultMessage = taskPlanService.saveTaskPlan(taskPlan); logService.saveLog("保存成功"); } catch (Exception e) { resultMessage = "保存失败!"; logService.saveErrorLog(resultMessage, e); LogUtils.error(resultMessage+e.getMessage(), e); } SpringUtil.jsonToStr(response, resultMessage); }

 保存功能前台的jQuery的function代码

 function save(){
    	var params = $("#searchForm").serializeArray();//searchForm为提交表单id
    	
    		$.ajax({
    			dataType:"json",                       //接收数据格式
    			type:"POST",                           //数据传送方式
    			url:"${ctx}/Krole/saveRole",           //后台处理程序
    			data:params,                           //要传递的数据
    			success:function(data){                //data对应后台的"result"
    				if(data.result == "1"){
    					layer.alert("保存成功");
    					cancel();
    					
    				}else if(data.result == "-1"){
    					layer.alert("保存失败");
    				}else{
    					layer.alert(data.result);
    				}
    			},
    			error: function(e){
    				for(var k in e){
    					console.log(k + "====="+e[k]);
    				}
    				layer.alert("保存失败");
    			}
    		});
    	
    }
原文地址:https://www.cnblogs.com/kunsunshine/p/6428674.html