前台向后台传递参数:
@ResponseBody @RequestMapping(value = "/findById/{id}", method = { RequestMethod.POST, RequestMethod.GET }) public void findById(@PathVariable("id") Long id) { Person person=new Person(); person.setId(id); }
访问地址为:项目地址+/findById/1.do
如果参数是一个对象bean:(@RequestBody注解帮助自动封装成bean,前台只需要传递格式正确的json)
@ResponseBody @RequestMapping(value = "/findById", method = { RequestMethod.POST, RequestMethod.GET }) public void findById(@RequestBody Person person) { person.setId(100); }
如果需要有返回值到前台:(普通bean或者list)
@ResponseBody @RequestMapping(value = "/findById/{id}", method = { RequestMethod.POST, RequestMethod.GET }) public Person findById(@PathVariable("id") Long id) { Person person=new Person(); person.setId(id); return person; }
如果需要返回json,先进行配置,用的比较多的应该是下面两种:
application/json;charset=UTF-8 text/html;charset=UTF-8 WriteMapNullValue QuoteFieldNames DisableCircularReferenceDetect
以及:
代码示例:
@ResponseBody @RequestMapping(value = "/findById/{id}", method = { RequestMethod.POST, RequestMethod.GET }) public Map findById(@PathVariable("id") Long id) { Person person=new Person(); person.setId(id); Mapmap = new HashedMap(); map.put("total", "1"); map.put("value", person); return map; }
附带mybatis的分页功能
maven包配置:
com.github.pagehelper pagehelper 3.7.3
service层分页代码示例:
@Override public ResultBean findByParams(Person person, HttpServletRequest request) { int currentPage = Integer.parseInt(request.getParameter("page") == null ?"1":request.getParameter("page"));//当前页 int pageSize = Integer.parseInt(request.getParameter("rows")== null?"10":request.getParameter("rows"));//每页条数 Page page = PageHelper.startPage(currentPage, pageSize); Listresult=personDao.findByParams(person); Map resMap = new HashMap (); resMap.put("rows",result); resMap.put("total",page.getTotal()); ResultBean resultBean = new ResultBean(); resultBean.setResultObj(resMap); return resultBean; }