前台向后台傳遞參數:
@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; }
