标签:
前台向后台传递参数:
@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,先进行配置,用的比较多的应该是下面两种:
<bean id="fastJsonHttpMessageConverter"
class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>application/json;charset=UTF-8</value>
<value>text/html;charset=UTF-8</value><!-- 避免IE出现下载JSON文件的情况 -->
</list>
</property>
<property name="features">
<array value-type="com.alibaba.fastjson.serializer.SerializerFeature">
<value>WriteMapNullValue</value>
<value>QuoteFieldNames</value>
<value>DisableCircularReferenceDetect</value>
</array>
</property>
</bean>
以及:
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"> <property name="messageConverters"> <list> <ref bean="mappingJacksonHttpMessageConverter" /> </list> </property> </bean> <bean id="mappingJacksonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"> <property name="supportedMediaTypes"> <list> <value>text/html;charset=UTF-8</value> </list> </property> </bean>
代码示例:
@ResponseBody @RequestMapping(value = "/findById/{id}", method = { RequestMethod.POST, RequestMethod.GET }) public Map findById(@PathVariable("id") Long id) { Person person=new Person(); person.setId(id); Map<String, Object> map = new HashedMap(); map.put("total", "1"); map.put("value", person); return map; }
附带mybatis的分页功能
maven包配置:
<dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper</artifactId> <version>3.7.3</version> </dependency>
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); List<Person> result=personDao.findByParams(person); Map<String,Object> resMap = new HashMap<String,Object>(); resMap.put("rows",result); resMap.put("total",page.getTotal()); ResultBean resultBean = new ResultBean(); resultBean.setResultObj(resMap); return resultBean; }
标签:
原文地址:http://www.cnblogs.com/garfieldcgf/p/5668061.html