spring mvc 与 jquery ajax
在 Spring mvc3中,响应、接受 JSON都十分方便。
使用注解@ResponseBody可以将结果(一个包含字符串和JavaBean的Map),转换成JSON。
使用 @RequestBody 注解前台只需要向 Controller 提交一段符合格式的 JSON,Spring 会自动将其拼装成 bean。
Spring这个转换是靠org.codehaus.jackson这个组件来实现的,所有需要引入jackson-core-asl和org.codehaus.jackson两个jar包
@Controller @RequestMapping("/user") public class DemoController { private Logger logger = LoggerFactory.getLogger(DemoController.class); @RequestMapping(value = "/list", method = RequestMethod.GET) @ResponseBody public Map<String, Object> getUserList() { logger.info("列表"); List<UserModel> list = new ArrayList<UserModel>(); UserModel um = new UserModel(); um.setId("1"); um.setUsername("sss"); um.setAge(222); list.add(um); Map<String, Object> modelMap = new HashMap<String, Object>(3); modelMap.put("total", "1"); modelMap.put("data", list); modelMap.put("success", "true"); return modelMap; } @RequestMapping(value = "/add", method = RequestMethod.POST) @ResponseBody public Map<String, String> addUser(@RequestBody UserModel model) { logger.info("新增"); logger.info("捕获到前台传递过来的Model,名称为:" + model.getUsername()); Map<String, String> map = new HashMap<String, String>(1); map.put("success", "true"); return map; } }
另外一种参数传递方式
前端代码:
@ResponseBody @RequestMapping(value="/assign", method=RequestMethod.POST) public String assign( @RequestParam(value="userId", required=true) int userId, @RequestParam(value="add[]", required=false) int[] add, @RequestParam(value="del[]", required=false) int[] del) { System.out.println("userId:" + userId); System.out.println("add:" + add); System.out.println("del:" + del); return ""; }
相关推荐
Lzs 2020-10-23
聚合室 2020-11-16
零 2020-09-18
Justhavefun 2020-10-22
jacktangj 2020-10-14
ChaITSimpleLove 2020-10-06
Andrea0 2020-09-18
周游列国之仕子 2020-09-15
afanti 2020-09-16
88234852 2020-09-15
YClimb 2020-09-15
风雨断肠人 2020-09-04
卖口粥湛蓝的天空 2020-09-15
stulen 2020-09-15
pythonxuexi 2020-09-06
abfdada 2020-08-26
梦的天空 2020-08-25