电子拍卖系统开发第四天
来源:互联网 发布:帝国cms分页样式修改 编辑:程序博客网 时间:2024/05/02 04:35
今天主要整理了一下服务端代码。前面一直遇到一个问题?管理人员既能在后台web上可以管理物品等功能,可以实现物品种类的添加,查询,物品的添加及其浏览等一些功能。一直想将管理人员操作这些功能的界面写的也比较好看一些。但是,我们都知道从Android客户端通过URL地址请求,返回的JSON格式的数据提供给客户端进行数据的展示。
遇到问题:
管理人员在后台实现功能的时候,想要通过丰富的界面很容易进行功能的操作,这就必须一个V层(也就是展示层)将数据呈现出来。
而Android通过请求的URL地址,返回响应的数据,也需要展示出来(比如说:添加数据成功后,返回“恭喜您,物品添加成功!”)这样的数据显示到客户端。
请简单看下下面两个服务端和客户端请求后的效果,注意地址栏,地址的变化。
服务端:
客户端:
一般我们会先两个V层,一个提供后台的丰富展示,一个返回Android客户端请求地址响应的数据。这样的话,这两个V层的代码大径相同,代码的冗余度特别高。这不是一个好的程序员所期望的代码。
解决方法:可以通过给请求地址识别附加参数判断哪个是服务端的,那个是客户端的。
前两三篇博客中的服务端代码,我已经修改好了,大家可以重复再看下。
今天任务:
管理拍卖物品:功能一:查看自己拍卖的物品,功能二:添加自己拍卖的物品。
服务端代码:
BussinessServiceImpl.java
//--------------管理拍卖物品-----------------------private StateDao stateDao = new StateDaoImpl();//查找自己拍卖的物品public List<ItemBean> getItemsByOwner(Integer userId)throws AuctionException {try {List<ItemBean> result = new ArrayList<ItemBean>();List<Item> items = itemDao.findItemByOwner(userId);for(Iterator<Item> it = items.iterator();it.hasNext();){ItemBean ib = new ItemBean();initItem(ib, it.next());result.add(ib);}return result;} catch (Exception e) {e.printStackTrace();throw new RuntimeException("查询用户所有的物品出现异常,请重新");}}//添加拍卖物品public int addItem(Item item, int avail, int kindId, Integer userId)throws AuctionException {//根据种类id获取种类Kind kind = kindDao.get(kindId);//根据添加着id获取添加者User owner = userDao.get(userId);//设置Item(物品)属性item.setAddtime(new Date());//创建Calendar(日历)对象Calendar c = Calendar.getInstance();c.add(Calendar.DATE, avail);item.setEndtime(c.getTime());item.setMax_price(item.getInit_price());item.setItemState(stateDao.get(1));item.setKind(kind);item.setOwner(owner);//保存item对象itemDao.save(item);return item.getItem_id();}KindDao.java
package com.xbmu.dao;import java.util.List;import com.xbmu.bean.Kind;public interface KindDao {/** * 查询所有种类 * @return */List<Kind> findAll();/** * 添加种类 * @param kind 待添加的种类 */void save(Kind kind);/** * 根据种类id查找种类对象 * @param kindId 种类id * @return 返回种类对象 */Kind get(int kindId);}
KindDaoImpl.java
package com.xbmu.dao.impl;import java.sql.SQLException;import java.util.List;import org.apache.commons.dbutils.QueryRunner;import org.apache.commons.dbutils.handlers.BeanHandler;import org.apache.commons.dbutils.handlers.BeanListHandler;import org.apache.commons.dbutils.handlers.ScalarHandler;import com.xbmu.bean.Kind;import com.xbmu.dao.KindDao;import com.xbmu.util.DBCPUtil;public class KindDaoImpl implements KindDao {QueryRunner qr = new QueryRunner(DBCPUtil.getDataSource());public List<Kind> findAll() {try {String sql = "select * from kind";List<Kind> kinds = qr.query(sql, new BeanListHandler<Kind>(Kind.class));return kinds;} catch (SQLException e) {throw new RuntimeException(e);}}/** * 添加种类: * 遇到问题:需求,想将添加的新数据的id返回, * 使用insert into kind (kind_name,kind_desc) values(?,?);select @@identity as kind_id;语句 * */public void save(Kind kind) {try {String sql = "insert into kind (kind_name,kind_desc) values(?,?)";qr.update(sql, kind.getKind_name(),kind.getKind_desc());String sql2 = "select @@identity as kind_id";//ScalarHandler 的参数为空或null时,返回第一行第一列的数据 //ScalarHandler 的参数可以是列的索引(从1开始)或列名 Object kind_id = qr.query(sql2, new ScalarHandler(1));//因为kind_id在数据库中定义为int型,上面语句返回后为BigInteger型,kind.setKind_id(Integer.valueOf(kind_id.toString()));//容易发生类型转换异常} catch (SQLException e) {throw new RuntimeException(e);}}public Kind get(int kindId) {try {String sql = "select * from kind where kind_id=?";Kind kind = qr.query(sql, new BeanHandler<Kind>(Kind.class), kindId);return kind;} catch (SQLException e) {throw new RuntimeException(e);}}}AuctionUserDao.java
package com.xbmu.dao;import com.xbmu.bean.User;/** * 数据访问层,用户接口 * @author Administrator * */public interface AuctionUserDao {/** * 验证用户登录 * @param username 用户名 * @param pass 用户密码 * @return 验证成功,返回一个用户;否则返回null */User findUserByNameAndPass(String username, String pass);/** * 根据用户id查找用户 * @param userId 用户id * @return 用户对象 */User get(Integer userId);}AuctionUserDaoImpl.java
package com.xbmu.dao.impl;import java.sql.SQLException;import java.util.List;import org.apache.commons.dbutils.QueryRunner;import org.apache.commons.dbutils.handlers.BeanHandler;import org.apache.commons.dbutils.handlers.BeanListHandler;import com.xbmu.bean.User;import com.xbmu.dao.AuctionUserDao;import com.xbmu.util.DBCPUtil;public class AuctionUserDaoImpl implements AuctionUserDao {private QueryRunner qr = new QueryRunner(DBCPUtil.getDataSource());public User findUserByNameAndPass(String username, String pass) {String sql = "select * from auction_user where username=? and userpass=?";try {List<User> userList = qr.query(sql, new BeanListHandler<User>(User.class), username,pass);if (userList.size() == 1){return (User)userList.get(0);}return null;} catch (SQLException e) {throw new RuntimeException(e);}}public User get(Integer userId) {try {String sql = "select * from auction_user where user_id=?";User user = qr.query(sql, new BeanHandler<User>(User.class), userId);return user;} catch (SQLException e) {throw new RuntimeException(e);}}}StateDao.java
package com.xbmu.dao;import com.xbmu.bean.State;public interface StateDao {/** * 根据状态id查找State对象 * @param state_id 状态id * @return 返回State对象 */State get(int state_id);}StateDaoImpl.java
package com.xbmu.dao.impl;import java.sql.SQLException;import org.apache.commons.dbutils.QueryRunner;import org.apache.commons.dbutils.handlers.BeanHandler;import com.xbmu.bean.State;import com.xbmu.dao.StateDao;import com.xbmu.util.DBCPUtil;public class StateDaoImpl implements StateDao {private QueryRunner qr = new QueryRunner(DBCPUtil.getDataSource());public State get(int state_id) {try {// 1表示拍卖中String sql = "select * from state where state_id=1";State state = qr.query(sql, new BeanHandler<State>(State.class));return state;} catch (SQLException e) {throw new RuntimeException(e);}}}ItemDao.java
package com.xbmu.dao;import java.util.List;import com.xbmu.bean.Item;/** * 物品接口 * @author Administrator * */public interface ItemDao{/** * 根据产品分类,获取当前拍卖的全部商品 * @param kindId 种类id; * @return 该类的全部产品 */List<Item> findItemByKind(Integer kindId);/** * 根据所有者查找处于拍卖中的物品 * @param useId 所有者Id; * @return 指定用户处于拍卖中的全部物品 */List<Item> findItemByOwner(Integer userId);/** * 根据赢取者查找物品 * @param userId 赢取者Id; * @return 指定用户赢取的全部物品 */List<Item> findItemByWiner(Integer userId);/** * 根据物品状态查找物品 * @param stateId 状态Id; * @return 该状态下的全部物品 */List<Item> findItemByState(Integer stateId);/** * 添加物品 * @param item 物品对象 */void save(Item item);}ItemDaoImpl.java
package com.xbmu.dao.impl;import java.sql.SQLException;import java.util.List;import org.apache.commons.dbutils.QueryRunner;import org.apache.commons.dbutils.handlers.BeanHandler;import org.apache.commons.dbutils.handlers.BeanListHandler;import org.apache.commons.dbutils.handlers.ScalarHandler;import com.xbmu.bean.Item;import com.xbmu.bean.Kind;import com.xbmu.bean.State;import com.xbmu.bean.User;import com.xbmu.dao.ItemDao;import com.xbmu.util.DBCPUtil;public class ItemDaoImpl implements ItemDao {QueryRunner qr = new QueryRunner(DBCPUtil.getDataSource());/** * 根据物品状态查找物品 * * @param stateId * 状态id; * @return 该状态下的全部物品 */public List<Item> findItemByState(Integer stateId) {try {String sql = "select * from item where state_id = ?";List<Item> itemList = qr.query(sql, new BeanListHandler<Item>(Item.class), stateId);// 遍历物品,设置种类,赢取者,拥有者的属性。for (Item item : itemList) {// 设置种类String kindSql = "select * from kind where kind_id = (select kind_id from item where state_id=?)";Kind kind = qr.query(kindSql,new BeanHandler<Kind>(Kind.class), stateId);item.setKind(kind);// 设置拥有者用户String ownerSql = "select * from auction_user where user_id = (select owner_id from item where state_id=?)";User owner = qr.query(ownerSql, new BeanHandler<User>(User.class), stateId);item.setOwner(owner);// 设置赢取者用户String winerSql = "select * from auction_user where user_id = (select winer_id from item where state_id=?)";User winer = qr.query(winerSql, new BeanHandler<User>(User.class), stateId);item.setWiner(winer);}return itemList;} catch (SQLException e) {throw new RuntimeException(e);}}/** * 根据所有者查找处于拍卖中的物品 * * @param userId * 所有者id; * @return 指定用户处于拍卖中的全部物品 */public List<Item> findItemByOwner(Integer userId) {try {String sql = "select * from item where owner_id=? and state_id=1";List<Item> items = qr.query(sql, new BeanListHandler<Item>(Item.class), userId);// 设置物品拥有者,物品状态,物品种类for (Item item : items) {// 设置拥有者String ownerSql = "select * from auction_user where user_id=any(select owner_id from item where owner_id=? and state_id=1)";User owner = qr.query(ownerSql, new BeanHandler<User>(User.class), userId);item.setOwner(owner);// 设置物品状态String stateSql = "select * from state where state_id=1";State state = qr.query(stateSql, new BeanHandler<State>(State.class));item.setItemState(state);// 设置物品种类String kindSql = "select * from kind where kind_id = any(select kind_id from item where owner_id=?)";Kind kind = qr.query(kindSql,new BeanHandler<Kind>(Kind.class), userId);item.setKind(kind);}return items;} catch (SQLException e) {throw new RuntimeException(e);}}public void save(Item item) {try {String sql = "insert into item(item_name,item_desc,item_remark,init_price,max_price,kind_id,addtime,endtime,owner_id,state_id) " +//"values(?,?,?,?,?,?,?,?,?,?)";qr.update(sql, item.getItem_name(), item.getItem_desc(), item.getItem_remark(), item.getInit_price(),item.getMax_price(), item.getKind().getKind_id(), item.getAddtime(), item.getEndtime(), item.getOwner().getUser_id(), item.getItemState().getState_id());String sql2 = "select @@identity as item_id";Object item_id = qr.query(sql2, new ScalarHandler(1));item.setItem_id(Integer.valueOf(item_id.toString()));} catch (SQLException e) {throw new RuntimeException(e);}}public List<Item> findItemByKind(Integer kindId) {// TODO Auto-generated method stubreturn null;}public List<Item> findItemByWiner(Integer userId) {// TODO Auto-generated method stubreturn null;}}ViewOwnerItemServlet.java
package com.xbmu.web.controller;import java.io.IOException;import java.util.List;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.json.JSONArray;import com.xbmu.business.ItemBean;import com.xbmu.service.BussinessService;import com.xbmu.service.impl.BussinessServiceImpl;/** * 查看自己拍卖的物品 * @author Administrator * */@WebServlet(urlPatterns = "/android/viewOwnerItem.jsp")public class ViewOwnerItemServlet extends HttpServlet {public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {String mode = request.getParameter("mode");// 获取userIdInteger userId = (Integer) request.getSession(true).getAttribute("userId");BussinessService service = new BussinessServiceImpl();List<ItemBean> items = service.getItemsByOwner(userId);if ("android".equals(mode)) {JSONArray jsonArray = new JSONArray(items);response.getWriter().println(jsonArray.toString());} else if ("web".equals(mode)) {request.setAttribute("items", items);request.getRequestDispatcher("/manage/viewOwnerItem.jsp").forward(request, response);}}public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {doGet(request, response);}}AddItemServlet.java
package com.xbmu.web.controller;import java.io.IOException;import java.util.List;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import com.xbmu.bean.Item;import com.xbmu.business.KindBean;import com.xbmu.service.BussinessService;import com.xbmu.service.impl.BussinessServiceImpl;/** * 添加物品 * * @author Administrator * */@WebServlet(urlPatterns = "/android/addItem.jsp")public class AddItemServlet extends HttpServlet {// 获取业务逻辑对象BussinessService service = new BussinessServiceImpl();public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {String mode = request.getParameter("mode");String op = request.getParameter("op");if("android".equals(mode)){int itemId = addItem(request);// 添加成功if (itemId > 0) {response.getWriter().println("恭喜您,物品添加成功!");} else {response.getWriter().println("对不起,物品添加失败!");}}else if("web".equals(mode)){if ("showAddItemUI".equals(op)) {showAddItemUI(request,response);} else if ("addItem".equals(op)) {int itemId = addItem(request);response.getWriter().write("添加物品成功。2秒后自动转向添加页面");response.setHeader("Refresh", "2;URL=" + request.getContextPath()+ "/servlet/ViewOwnerItemServlet?mode=web");}}}private int addItem(HttpServletRequest request) {// 获取userIdInteger userId = (Integer) request.getSession(true).getAttribute("userId");// 解析请求参数String itemName = request.getParameter("itemName");String itemDesc = request.getParameter("itemDesc");String itemRemark = request.getParameter("itemRemark");String initPrice = request.getParameter("initPrice");String kindId = request.getParameter("kindId");String avail = request.getParameter("availTime");System.out.println(itemName+","+itemDesc+","+itemRemark+","+initPrice+","+kindId+","+avail);Item item = new Item(itemName, itemRemark, itemDesc,Double.parseDouble(initPrice));int itemId = service.addItem(item, Integer.parseInt(avail),Integer.parseInt(kindId), userId);return itemId;}/** * 显示添加物品的UI界面 * @param request * @param response */private void showAddItemUI(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {List<KindBean> kinds = service.getAllKind();request.setAttribute("kinds", kinds);request.getRequestDispatcher("/manage/addItem.jsp").forward(request, response);}public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {doGet(request, response);}}viewOwnerItem.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><%@ include file="/manage/header.jsp"%><br /><table width="80%" align="center" cellpadding="0" cellspacing="1" ><tr><td colspan="4" >自己拍卖的物品</td> </tr><tr height="30"><th>物品名称</th><th>物品种类</th><th>物品备注</th><th>起拍价格</th><th>最高价格</th><th>起拍时间</th><th>结束时间</th></tr><c:forEach items="${items}" var="i" varStatus="vs"><tr height="24" class="${vs.index%2==0?'odd':'even' }"><td nowrap="nowrap">${i.name}</td><td nowrap="nowrap">${i.kind}</td><td nowrap="nowrap">${i.remark}</td><td nowrap="nowrap">${i.initPrice}</td><td nowrap="nowrap">${i.maxPrice}</td><td nowrap="nowrap">${i.addTime}</td><td nowrap="nowrap">${i.endTime}</td></tr></c:forEach></table></body></html>addItem.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><%@ include file="/manage/header.jsp"%><br/> <form action="${pageContext.request.contextPath}/servlet/AddItemServlet?mode=web&op=addItem" method="post" > <h2 align="center">添加新物品</h2> <table border="1" width="438" align="center"> <tr> <td>物品名称</td> <td> <input type="text" name="itemName"/> </td> </tr> <tr> <td>物品描述</td> <td> <textarea rows="5" cols="45" name="itemDesc"></textarea> </td> </tr> <tr> <td>物品备注</td> <td> <input type="text" name="itemRemark"/> </td> </tr> <tr> <td>起拍价格</td> <td> <input type="text" name="initPrice"/> </td> </tr> <tr> <td>有效时间</td> <td> <select name="availTime"> <option value="1">一天</option> <option value="2">二天</option> <option value="3">三天</option> <option value="4">四天</option> <option value="5">五天</option> </select>( </td> </tr> <tr> <td>物品种类</td> <td> <select name="kindId"> <c:forEach items="${kinds}" var="k"> <option value="${k.id }">${k.kindName}</option> </c:forEach> </select> </td> </tr> <tr> <td colspan="2"> <input type="submit" value="添加"/> </td> </tr> </table> </body></html>遇到的问题:
Subquery returns more than 1 row查询结果多于一行
解决方法:
select kind_id from item where owner_id=?)因为这条语句可能查询出多条数据。
原来sql:select * from kind where kind_id =(select kind_id from item where owner_id=?)
改为sql:select * from kind where kind_id = any(select kind_id from item where owner_id=?)
客户端代码:
ManageItem.java
package com.xbmu.auction.activity;import android.app.Fragment;import android.content.Intent;import android.os.Bundle;import com.xbmu.auction.Callbacks;import com.xbmu.auction.FragmentActivity;import com.xbmu.auction.fragment.ManageItemFragment;/** * 管理拍卖物品 * @author Administrator * */public class ManageItem extends FragmentActivity implements Callbacks{@Overrideprotected Fragment getFragment() {return new ManageItemFragment();}@Overridepublic void onItemSelected(Integer id, Bundle bundle) {Intent intent = new Intent(this, AddItem.class);startActivity(intent);}}ManageItemFragment.java
package com.xbmu.auction.fragment;import org.json.JSONArray;import org.json.JSONException;import org.json.JSONObject;import android.app.Activity;import android.app.Fragment;import android.os.Bundle;import android.view.LayoutInflater;import android.view.View;import android.view.View.OnClickListener;import android.view.ViewGroup;import android.widget.AdapterView;import android.widget.AdapterView.OnItemClickListener;import android.widget.Button;import android.widget.ListView;import android.widget.TextView;import com.xbmu.auction.Callbacks;import com.xbmu.auction.R;import com.xbmu.auction.adapter.JSONArrayAdapter;import com.xbmu.auction.listener.HomeListener;import com.xbmu.auction.util.DialogUtil;import com.xbmu.auction.util.HttpUtil;public class ManageItemFragment extends Fragment{public static final int ADD_ITEM = 0x1006;;Button bnHome, bnAdd;ListView itemList;Callbacks mCallbacks;@Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){View rootView = inflater.inflate(R.layout.manage_item, container , false);bnHome = (Button) rootView.findViewById(R.id.bn_home);bnAdd = (Button) rootView.findViewById(R.id.bnAdd);itemList = (ListView) rootView.findViewById(R.id.itemList);// 为返回按钮的单击事件绑定事件监听器bnHome.setOnClickListener(new HomeListener(getActivity()));bnAdd.setOnClickListener(new OnClickListener(){@Overridepublic void onClick(View source){mCallbacks.onItemSelected(ADD_ITEM , null);}});// 定义发送请求的URLString url = HttpUtil.BASE_URL + "viewOwnerItem.jsp"+"?mode=android";try{// 向指定URL发送请求JSONArray jsonArray = new JSONArray(HttpUtil.getRequest(url));// 将服务器响应包装成AdapterJSONArrayAdapter adapter = new JSONArrayAdapter(getActivity(), jsonArray, "name", true);itemList.setAdapter(adapter);}catch (Exception e){DialogUtil.showDialog(getActivity(), "服务器响应异常,请稍后再试!", false);e.printStackTrace();}itemList.setOnItemClickListener(new OnItemClickListener(){@Overridepublic void onItemClick(AdapterView<?> parent, View view,int position, long id){viewItemInBid(position); }});return rootView;}// 当该Fragment被添加、显示到Activity时,回调该方法@Overridepublic void onAttach(Activity activity){super.onAttach(activity);// 如果Activity没有实现Callbacks接口,抛出异常if (!(activity instanceof Callbacks)){throw new IllegalStateException("ManagerItemFragment所在的Activity必须实现Callbacks接口!");}// 把该Activity当成Callbacks对象mCallbacks = (Callbacks) activity;}// 当该Fragment从它所属的Activity中被删除时回调该方法@Overridepublic void onDetach(){super.onDetach();// 将mCallbacks赋为null。mCallbacks = null;}private void viewItemInBid(int position){// 加载detail_in_bid.xml界面布局代表的视图View detailView = getActivity().getLayoutInflater().inflate(R.layout.detail_in_bid, null);// 获取detail_in_bid.xml界面中的文本框TextView itemName = (TextView) detailView.findViewById(R.id.itemName);TextView itemKind = (TextView) detailView.findViewById(R.id.itemKind);TextView maxPrice = (TextView) detailView.findViewById(R.id.maxPrice);TextView initPrice = (TextView) detailView.findViewById(R.id.initPrice);TextView endTime = (TextView) detailView.findViewById(R.id.endTime);TextView itemRemark = (TextView) detailView.findViewById(R.id.itemRemark);// 获取被单击列表项所包装的JSONObjectJSONObject jsonObj = (JSONObject) itemList.getAdapter().getItem(position);System.out.println("查询拍卖物品:"+jsonObj.toString());try{// 通过文本框显示物品详情itemName.setText(jsonObj.getString("name"));itemKind.setText(jsonObj.getString("kind"));maxPrice.setText(jsonObj.getString("maxPrice"));itemRemark.setText(jsonObj.getString("desc"));initPrice.setText(jsonObj.getString("initPrice"));endTime.setText(jsonObj.getString("endTime"));}catch (JSONException e){e.printStackTrace();}DialogUtil.showDialog(getActivity(), detailView);}}manage_item.xml
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" android:orientation="vertical" > <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="@dimen/sub_title_margin" android:gravity="center" android:orientation="horizontal" > <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="center" android:orientation="vertical" android:paddingLeft="12dp" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/manage_item" android:textSize="@dimen/label_font_size" /> <!-- 添加物品的按钮 --> <Button android:id="@+id/bnAdd" android:layout_width="85dp" android:layout_height="30dp" android:background="@drawable/add_item" /> </LinearLayout> <Button android:id="@+id/bn_home" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="@dimen/label_font_size" android:background="@drawable/home" /> </LinearLayout> <!-- 显示物品列表的ListView --> <ListView android:id="@+id/itemList" android:layout_width="match_parent" android:layout_height="match_parent" /></LinearLayout>detail_in_bid.xml
<?xml version="1.0" encoding="utf-8"?><TableLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:stretchColumns="1" > <TableRow> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/item_name" android:textSize="@dimen/label_font_size" /> <TextView android:id="@+id/itemName" style="@style/tv_show" android:layout_width="match_parent" android:layout_height="wrap_content" /> </TableRow> <TableRow> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/item_kind" android:textSize="@dimen/label_font_size" /> <TextView android:id="@+id/itemKind" style="@style/tv_show" android:layout_width="match_parent" android:layout_height="wrap_content" /> </TableRow> <TableRow> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/win_price" android:textSize="@dimen/label_font_size" /> <TextView android:id="@+id/maxPrice" style="@style/tv_show" android:layout_width="match_parent" android:layout_height="wrap_content" /> </TableRow> <TableRow> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/init_price" android:textSize="@dimen/label_font_size" /> <TextView android:id="@+id/initPrice" style="@style/tv_show" android:layout_width="match_parent" android:layout_height="wrap_content" /> </TableRow> <TableRow> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/end_time" android:textSize="@dimen/label_font_size" /> <TextView android:id="@+id/endTime" style="@style/tv_show" android:layout_width="match_parent" android:layout_height="wrap_content" /> </TableRow> <TableRow> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/remark" android:textSize="@dimen/label_font_size" /> <TextView android:id="@+id/itemRemark" style="@style/tv_show" android:layout_width="match_parent" android:layout_height="wrap_content" /> </TableRow></TableLayout>AddItem.java
package com.xbmu.auction.activity;import android.app.Fragment;import com.xbmu.auction.FragmentActivity;import com.xbmu.auction.fragment.AddItemFragment;public class AddItem extends FragmentActivity {@Overrideprotected Fragment getFragment() {return new AddItemFragment();}}AddItemFragment.java
package com.xbmu.auction.fragment;import java.util.HashMap;import java.util.Map;import org.json.JSONArray;import org.json.JSONObject;import android.app.Fragment;import android.os.Bundle;import android.text.TextUtils;import android.view.LayoutInflater;import android.view.View;import android.view.View.OnClickListener;import android.view.ViewGroup;import android.widget.Button;import android.widget.EditText;import android.widget.Spinner;import com.xbmu.auction.R;import com.xbmu.auction.adapter.JSONArrayAdapter;import com.xbmu.auction.listener.HomeListener;import com.xbmu.auction.util.DialogUtil;import com.xbmu.auction.util.HttpUtil;public class AddItemFragment extends Fragment {private EditText itemName;private EditText itemDesc;private EditText itemRemark;private EditText initPrice;private Spinner availTime;private Spinner itemKind;private Button bnAdd;private Button bnCancel;@Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {View rootView = inflater.inflate(R.layout.add_item, container, false);itemName = (EditText) rootView.findViewById(R.id.itemName);itemDesc = (EditText) rootView.findViewById(R.id.itemDesc);itemRemark = (EditText) rootView.findViewById(R.id.itemRemark);initPrice = (EditText) rootView.findViewById(R.id.initPrice);availTime = (Spinner) rootView.findViewById(R.id.availTime);itemKind = (Spinner) rootView.findViewById(R.id.itemKind);JSONArray jsonArray = null;//定义发送请求的地址String url = HttpUtil.BASE_URL+"viewKind.jsp?mode=android";try {jsonArray = new JSONArray(HttpUtil.getRequest(url));} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}//将JSONArray包装成AdapterJSONArrayAdapter adapter = new JSONArrayAdapter(getActivity(), jsonArray, "kindName", false);//显示物品种类列表itemKind.setAdapter(adapter);//获取界面上的两个按钮bnAdd = (Button) rootView.findViewById(R.id.bnAdd);bnCancel = (Button) rootView.findViewById(R.id.bnCancel);bnCancel.setOnClickListener(new HomeListener(getActivity()));bnAdd.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {//执行输入校验if(validate()){//获取用户输入的物品名,物品描述等信息String name = itemName.getText().toString().trim();String desc = itemDesc.getText().toString().trim();String remark = itemRemark.getText().toString().trim();String price = initPrice.getText().toString().trim();JSONObject kind = (JSONObject) itemKind.getSelectedItem();int avail = availTime.getSelectedItemPosition();//TODO:根据用户选择有效时间选项,指定实际的有效时间try {//添加物品String result = addItem(name,desc,remark,price,kind.getInt("id"),avail);//显示对话框DialogUtil.showDialog(getActivity(), result, true);} catch (Exception e) {DialogUtil.showDialog(getActivity(), "服务器响应异常,请稍后再试!", false);e.printStackTrace();}}}});return rootView;}protected String addItem(String name, String desc, String remark,String price, int kindId, int avail) throws Exception {//使用Map封装请求参数Map<String, String> map = new HashMap<String, String>();map.put("itemName", name);map.put("itemDesc", desc);map.put("itemRemark", remark);map.put("initPrice", price);map.put("kindId", kindId+"");map.put("availTime", avail+"");//定义发送方请求的URLString url = HttpUtil.BASE_URL+"addItem.jsp?mode=android";//发送请求return HttpUtil.postRequest(url, map);}/**对用户输入的物品名、起拍价格进行校验*/protected boolean validate() {String name = itemName.getText().toString().trim();if(TextUtils.isEmpty(name)){DialogUtil.showDialog(getActivity(), "物品名称是必填项!", false);return false;}String price = initPrice.getText().toString().trim();if(TextUtils.isEmpty(price)){DialogUtil.showDialog(getActivity(), "棋牌价格是必填项!", false);return false;}try {//尝试把起拍价格转换为浮点数Double.parseDouble(price);} catch (NumberFormatException e) {e.printStackTrace();DialogUtil.showDialog(getActivity(), "起拍价格必须是数值", false);return false;}return true;}}add_item.xml
<?xml version="1.0" encoding="utf-8"?><TableLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:stretchColumns="1" > <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center" android:padding="@dimen/title_padding" android:text="@string/add_item_title" android:textSize="@dimen/label_font_size" /> <!-- 输入物品名称的行 --> <TableRow> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/item_name" android:textSize="@dimen/label_font_size" /> <EditText android:id="@+id/itemName" android:layout_width="match_parent" android:layout_height="wrap_content" android:inputType="text" /> </TableRow> <!-- 输入物品描述的行 --> <TableRow> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/item_desc" android:textSize="@dimen/label_font_size" /> <EditText android:id="@+id/itemDesc" android:layout_width="match_parent" android:layout_height="wrap_content" android:inputType="text" /> </TableRow> <!-- 输入物品备注的行 --> <TableRow> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/remark" android:textSize="@dimen/label_font_size" /> <EditText android:id="@+id/itemRemark" android:layout_width="match_parent" android:layout_height="wrap_content" android:inputType="text" /> </TableRow> <!-- 输入起拍价格的行 --> <TableRow> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/init_price" android:textSize="@dimen/label_font_size" /> <EditText android:id="@+id/initPrice" android:layout_width="match_parent" android:layout_height="wrap_content" android:inputType="numberDecimal" /> </TableRow> <!-- 选择有效时间的行 --> <TableRow> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/avail_time" android:textSize="@dimen/label_font_size" /> <Spinner android:id="@+id/availTime" android:layout_width="match_parent" android:layout_height="wrap_content" android:entries="@array/availTime" /> </TableRow> <!-- 选择选择物品种类的行 --> <TableRow> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/item_kind" android:textSize="@dimen/label_font_size" /> <Spinner android:id="@+id/itemKind" android:layout_width="match_parent" android:layout_height="wrap_content" /> </TableRow> <!-- 定义按钮的行 --> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center" > <Button android:id="@+id/bnAdd" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/add" /> <Button android:id="@+id/bnCancel" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/cancel" /> </LinearLayout></TableLayout>
运行效果:
这里为了录制快一点,我们随便输入数据(因为目前csdn上传gif格式动画,不能超过2M)
前四天所有访问地址整理(客户端的稍微要改动,这里就不该了):
服务端:登录界面:http://localhost:8080/AuctionServer/manage/login.jsp 登录表单action="http://localhost:8080/AuctionServer/servlet/LoginServlet?mode=web"查看流拍物品:http://localhost:8080/AuctionServer/servlet/ViewFailServlet?mode=web管理物品种类:1.查看物品种类:http://localhost:8080/AuctionServer/servlet/ViewKindServlet?mode=web2.添加物品种类:http://localhost:8080/AuctionServer/servlet/AddKindServlet?mode=web管理拍卖物品:1.查看自己拍卖的物品:http://localhost:8080/AuctionServer/servlet/ViewOwnerItemServlet?mode=web2.添加拍卖物品:http://localhost:8080/AuctionServer/servlet/AddItemServlet?mode=web&op=showAddItemUI客户端:登录访问地址:http://localhost:8080/AuctionServer/android/login.jsp?mode=android(http://localhost:8080/AuctionServer/servlet/LoginServlet?mode=android)查看流拍物品:http://localhost:8080/AuctionServer/android/viewFail.jsp?mode=android管理物品种类:1.查看物品种类:http://localhost:8080/AuctionServer/android/viewKind.jsp?mode=android2.添加物品种类:http://localhost:8080/AuctionServer/android/addKind.jsp?mode=android管理拍卖物品:1.查看自己拍卖的物品:http://localhost:8080/AuctionServer/android/viewOwnerItem.jsp?mode=android2.添加拍卖物品:http://localhost:8080/AuctionServer/android/addItem.jsp?mode=androi
- 电子拍卖系统开发第四天
- 电子拍卖系统开发第二天
- 电子拍卖系统开发第一天
- 电子拍卖系统开发第三天
- 电子拍卖系统开发第五天
- Android电子拍卖系统学习笔记
- Android电子拍卖系统总结二
- Android电子拍卖系统总结三
- Android电子拍卖系统总结四
- 拍卖系统需求分析
- 拍卖系统模块设计方案
- asp拍卖系统前台
- 拍卖后台管理系统
- 电子拍卖总结 hibernate+spring+dwr
- android实现手机拍卖系统
- 网络拍卖系统的设计
- 拍卖
- 从一个拍卖系统谈OO思想
- java 实现简单的日历查询
- iOS tabview 复用机制详解
- java.lang.IllegalThreadStateException: Thread already started
- UI基础整理-15
- Python学习笔记——基础篇(1): 变量及其类型
- 电子拍卖系统开发第四天
- Object-C--->Swift之(六)函数类型
- python爬hdu网页
- Educational Codeforces Round 6
- Linux 下 一些文件的权限
- [C++] 静态成员函数
- MFC---CFileDialog打开文件对话框
- tcp粘包和拆包、断包
- eclipse环境搭建之二:C++