************************************************************服务器端代码**************************************************************************
spring Web MVC(Servlet) 具体细节就不说了,比较不一样的地方,下面会注明!
1. web.xml 的内容如下:
- <?xml version="1.0" encoding="UTF-8"?>
- <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
- <display-name>FCAS</display-name>
- <servlet>
- <servlet-name>foodcenter</servlet-name>
- <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
- <load-on-startup>1</load-on-startup>
- </servlet>
- <servlet-mapping>
- <servlet-name>foodcenter</servlet-name>
- <url-pattern>*.json</url-pattern>
- </servlet-mapping>
- </web-app>
2. foodcenter-servlet.xml 的内容如下:
- <?xml version="1.0" encoding="UTF-8"?>
- <beans xmlns="http://www.springframework.org/schema/beans"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xmlns:p="http://www.springframework.org/schema/p"
- xmlns:context="http://www.springframework.org/schema/context"
- xsi:schemaLocation="
- http://www.springframework.org/schema/beans ;
- http://www.springframework.org/schema/beans/spring-beans-3.0.xsd ;
- http://www.springframework.org/schema/context ;
- http://www.springframework.org/schema/context/spring-context-3.0.xsd">
- <context:annotation-config/>
- <!-- Controller 类的注解标识-->
- <context:component-scan base-package="com.liuxi.foodcenter.controller"/>
- <!--这个ViewResolver 的具体原来没细究,不过CV战士们 中的一员,这样用是没问题的(参考官文) -->
- <bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
- <property name="mediaTypes">
- <map>
- <entry key="json" value="application/json"/> <!-- 告诉视图解析器 返回的类型为json 格式 -->
- </map>
- </property>
- <property name="defaultViews">
- <list>
- <!-- 这个 View 比较重要,ModelAndView 里的数据变成JSON -->
- <bean class="org.springframework.web.servlet.view.json.MappingJacksonJsonView">
- </bean>
- </list>
- </property>
- </bean>
- <!--真正的项目,业务Bean 有专门对应的配置文件,这里为了简单起见,就写在这里了 -->
- <bean id="foodService" class="com.liuxi.food.service.FoodServiceImpl"/>
- </beans>
3. 子控制器FindFoodListController.java
- package com.liuxi.foodcenter.controller;
- import java.util.HashMap;
- import java.util.List;
- import java.util.Map;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.beans.factory.annotation.Qualifier;
- import org.springframework.stereotype.Controller;
- import org.springframework.web.bind.annotation.RequestMapping;
- import org.springframework.web.bind.annotation.RequestParam;
- import org.springframework.web.servlet.ModelAndView;
- import com.liuxi.bean.Food;
- import com.liuxi.food.service.IFoodService;
- @Controller
- public class FindFoodListController {
- @Autowired @Qualifier("foodService")
- private IFoodService foodService;
- /** 根据餐菜的类别返回 该类别下的所有菜*/
- @RequestMapping("/findFoodList")
- public ModelAndView queryFoodList(@RequestParam("typeId") int typeId){
- List<Food> list=foodService.getFoodListByType(typeId);
- ModelAndView modelView=new ModelAndView();
- Map<String,Object> modelMap=new HashMap<String,Object>();
- modelMap.put("FOOD_LIST", list);
- modelMap.put("TYPE_ID", typeId);
- modelView.addAllObjects(modelMap);
- return modelView;
- }
- }
4. FoodServiceImpl.java
- package com.liuxi.food.service;
- import java.util.ArrayList;
- import java.util.List;
- import com.liuxi.bean.Food;
- public class FoodServiceImpl implements IFoodService{
- @Override
- public List<Food> getFoodListByType(int typeId) {
- //这里本来要调DAO层接口的,这边暂时写死
- Food food1=new Food(1,1,"鱼香肉丝", 12.00,"好吃的不得了-鱼香肉丝",4.5,5.0);
- Food food2=new Food(2,1,"农家小炒肉", 15.00,"好吃的不得了-农家小炒肉",3.7,4.3);
- Food food3=new Food(3,1,"韭菜炒蛋", 10.00,"好吃的不得了-韭菜炒蛋",2.6,3.0);
- Food food4=new Food(4,1,"回锅肉", 13.00,"好吃的不得了-回锅肉",3.1,3.8);
- Food food5=new Food(5,1,"宫保鸡丁", 14.00,"好吃的不得了-宫保鸡丁",3.7,5.0);
- Food food6=new Food(6,1,"苦瓜炒蛋", 9.00,"好吃的不得了-宫保鸡丁",4.9,4.7);
- Food food7=new Food(7,1,"莴笋肉片", 10.00,"好吃的不得了-莴笋肉片",2.6,3.9);
- List<Food> list=new ArrayList<Food>();
- list.add(food1);
- list.add(food2);
- list.add(food3);
- list.add(food4);
- list.add(food5);
- list.add(food6);
- list.add(food7);
- return list;
- }
- }
5.IFoodService.java
- package com.liuxi.food.service;
- import java.util.List;
- import com.liuxi.bean.Food;
- public interface IFoodService {
- List<Food> getFoodListByType(int typeId);
- }
6.Food.Java
- package com.liuxi.bean;
- public class Food {
- private int id; // ID
- private String name; // 菜名
- private double price; // 价格
- private String notes; // 菜的简要介绍
- private int foodTypeId; // 菜所属的类别
- private double kouWeiScore; // 口味的分值
- private double hotLevel; // 星级别
- public Food(int id, int foodTypeId, String name, double price,
- String notes, double kouWeiScore, double hotLevel) {
- this.id = id;
- this.name = name;
- this.price = price;
- this.notes = notes;
- this.foodTypeId = foodTypeId;
- this.kouWeiScore = kouWeiScore;
- this.hotLevel = hotLevel;
- }
- public Food() {
- }
- public int getId() {
- return id;
- }
- public void setId(int id) {
- this.id = id;
- }
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public double getPrice() {
- return price;
- }
- public void setPrice(double price) {
- this.price = price;
- }
- public String getNotes() {
- return notes;
- }
- public void setNotes(String notes) {
- this.notes = notes;
- }
- public int getFoodTypeId() {
- return foodTypeId;
- }
- public void setFoodTypeId(int foodTypeId) {
- this.foodTypeId = foodTypeId;
- }
- public double getKouWeiScore() {
- return kouWeiScore;
- }
- public void setKouWeiScore(double kouWeiScore) {
- this.kouWeiScore = kouWeiScore;
- }
- public double getHotLevel() {
- return hotLevel;
- }
- public void setHotLevel(double hotLevel) {
- this.hotLevel = hotLevel;
- }
- public String toString() {
- return id + "--" + name + "--" + price + "--" + notes + "--"
- + foodTypeId + "--" + kouWeiScore + "--" + hotLevel;
- }
- }
7.Spring Web MVC 中 将ModelAndView 中的数据自动转换成json ,靠的是jackjson 中 连个jar 包 (这个下载大本营里有下,花了我2积分哦)
jackson-core-asl-1.4.2.jar
jackson-mapper-asl-1.4.2.jar
*************************************以上是服务器端代码,已全部贴完!**********************************************
访问链接是: http://192.168.1.104:8088/FCAS/findFoodList.json?typeId=1
***************************************************************************Android 客户端 访问部分************************************************************
下面进入 Android 客户端访问部分(这里暂不贴 界面,用android 的单元测试 来 测试 服务器返回的json 数据是什么样的
8. GetFoodListTest.java
- package com.liuxi.takeorder.test;
- import java.io.BufferedReader;
- import java.io.InputStreamReader;
- import java.util.ArrayList;
- import org.apache.http.HttpResponse;
- import org.apache.http.HttpStatus;
- import org.apache.http.NameValuePair;
- import org.apache.http.client.HttpClient;
- import org.apache.http.client.entity.UrlEncodedFormEntity;
- import org.apache.http.client.methods.HttpPost;
- import org.apache.http.impl.client.DefaultHttpClient;
- import org.apache.http.message.BasicNameValuePair;
- import android.test.AndroidTestCase;
- import android.util.Log;
- public class GetFoodListTest extends AndroidTestCase {
- private static final String TAG="GetFoodListTest";
- public void testFindFoodList() {
- String uri="http://192.168.1.104:8088/FCAS/findFoodList.json?typeId=1";
- try{
- HttpClient httpClient=new DefaultHttpClient();
- //HttpPost 实现 HttpUriRequest 接口,HttpUriRequest接口 继承 HttpRequest
- HttpPost httpPostReq=new HttpPost(uri);
- ArrayList<NameValuePair> paramList=new ArrayList<NameValuePair>();
- NameValuePair param1=new BasicNameValuePair("typeId",String.valueOf(1));
- paramList.add(param1);
- httpPostReq.setEntity(new UrlEncodedFormEntity(paramList));
- HttpResponse resp=httpClient.execute(httpPostReq);
- if(resp.getStatusLine().getStatusCode()==HttpStatus.SC_OK){
- BufferedReader reader=new BufferedReader(
- new InputStreamReader(resp.getEntity().getContent())
- );
- StringBuffer result=new StringBuffer();
- String inputLine=null;
- while((inputLine=reader.readLine())!=null){
- result.append(inputLine);
- }
- Log.i(TAG, result.toString());
- }
- }catch(Exception e){
- Log.i(TAG,e.getMessage());
- }
- }
- }
9. 激动人心的时刻-----> 结果是啥?
日志记录为:
07-19 16:12:53.282: INFO/GetFoodListTest(1287): {"TYPE_ID":1,"FOOD_LIST":[{"name":"鱼香肉丝","id":1,"price":12.0,"notes":"好吃的不得了-鱼香肉丝","foodTypeId":1,"kouWeiScore":4.5,"hotLevel":5.0},{"name":"农家小炒肉","id":2,"price":15.0,"notes":"好吃的不得了-农家小炒肉","foodTypeId":1,"kouWeiScore":3.7,"hotLevel":4.3},{"name":"韭菜炒蛋","id":3,"price":10.0,"notes":"好吃的不得了-韭菜炒蛋","foodTypeId":1,"kouWeiScore":2.6,"hotLevel":3.0},{"name":"回锅肉","id":4,"price":13.0,"notes":"好吃的不得了-回锅肉","foodTypeId":1,"kouWeiScore":3.1,"hotLevel":3.8},{"name":"宫保鸡丁","id":5,"price":14.0,"notes":"好吃的不得了-宫保鸡丁","foodTypeId":1,"kouWeiScore":3.7,"hotLevel":5.0},{"name":"苦瓜炒蛋","id":6,"price":9.0,"notes":"好吃的不得了-宫保鸡丁","foodTypeId":1,"kouWeiScore":4.9,"hotLevel":4.7},{"name":"莴笋肉片","id":7,"price":10.0,"notes":"好吃的不得了-莴笋肉片","foodTypeId":1,"kouWeiScore":2.6,"hotLevel":3.9}]}
我把上面{} 里的东西 放到一个foodlist.json 文件中,格式化后的内容如下:
- {
- "TYPE_ID" : 1,
- "FOOD_LIST" : [{
- "name" : "鱼香肉丝",
- "id" : 1,
- "price" : 12.0,
- "notes" : "好吃的不得了-鱼香肉丝",
- "foodTypeId" : 1,
- "kouWeiScore" : 4.5,
- "hotLevel" : 5.0
- }, {
- "name" : "农家小炒肉",
- "id" : 2,
- "price" : 15.0,
- "notes" : "好吃的不得了-农家小炒肉",
- "foodTypeId" : 1,
- "kouWeiScore" : 3.7,
- "hotLevel" : 4.3
- }, {
- "name" : "韭菜炒蛋",
- "id" : 3,
- "price" : 10.0,
- "notes" : "好吃的不得了-韭菜炒蛋",
- "foodTypeId" : 1,
- "kouWeiScore" : 2.6,
- "hotLevel" : 3.0
- }, {
- "name" : "回锅肉",
- "id" : 4,
- "price" : 13.0,
- "notes" : "好吃的不得了-回锅肉",
- "foodTypeId" : 1,
- "kouWeiScore" : 3.1,
- "hotLevel" : 3.8
- }, {
- "name" : "宫保鸡丁",
- "id" : 5,
- "price" : 14.0,
- "notes" : "好吃的不得了-宫保鸡丁",
- "foodTypeId" : 1,
- "kouWeiScore" : 3.7,
- "hotLevel" : 5.0
- }, {
- "name" : "苦瓜炒蛋",
- "id" : 6,
- "price" : 9.0,
- "notes" : "好吃的不得了-宫保鸡丁",
- "foodTypeId" : 1,
- "kouWeiScore" : 4.9,
- "hotLevel" : 4.7
- }, {
- "name" : "莴笋肉片",
- "id" : 7,
- "price" : 10.0,
- "notes" : "好吃的不得了-莴笋肉片",
- "foodTypeId" : 1,
- "kouWeiScore" : 2.6,
- "hotLevel" : 3.9
- }]
- }
10. OK! 返回数据正确。
************************************************Spring 是用ObjectMapper 将 数据转换成json 数据的*****************************
下面自己写了个转换的例子:
ObjectMapperTest.java
- package com.bean.test;
- import java.util.ArrayList;
- import java.util.HashMap;
- import java.util.List;
- import java.util.Map;
- import org.codehaus.jackson.map.ObjectMapper;
- public class ObjectMapperTest {
- /**
- * @param args
- */
- public static void main(String[] args) throws Exception {
- ObjectMapper mapper=new ObjectMapper();
- Map<String,Object> foodListData=new HashMap<String,Object>();
- List list=new ArrayList();
- Map<String,Object> foodData=new HashMap<String,Object>();
- foodData.put("id", 1);
- foodData.put("name", "鱼香肉丝");
- foodData.put("price", 12.00);
- foodData.put("notes", "好吃啊,真的!");
- foodData.put("kouWeiScore", 4.5);
- foodData.put("hotLevel", 5.0);
- list.add(foodData);
- foodListData.put("foodlist", list);
- String str=mapper.writeValueAsString(foodListData);
- System.out.println(str);
- }
- }
上述程序输出的是:
{"foodlist":[{"id":1,"kouWeiScore":4.5,"price":12.0,"hotLevel":5.0,"name":"鱼香肉丝","notes":"好吃啊,真的!"}]}
format 下:
{
"foodlist" : [{
"id" : 1,
"kouWeiScore" : 4.5,
"price" : 12.0,
"hotLevel" : 5.0,
"name" : "鱼香肉丝",
"notes" : "好吃啊,真的!"
}]
}