Struts服务器端+Android客户端+json数据(一)

时间:2022-12-02 08:21:35

本文主要讲述的是用struts2搭建服务器,从数据库获取数据,客户端通过json解析获得数据的方法。
以下主要为服务器端的代码。

图书实体类:

public class Book {
    private int bookId;
    private String isbn;
    private String title;
    private String price;
    public int getBookId() {
        return bookId;
    }
    public void setBookId(int bookId) {
        this.bookId = bookId;
    }
    public String getIsbn() {
        return isbn;
    }
    public void setIsbn(String isbn) {
        this.isbn = isbn;
    }
    public String getTitle() {
        return title;
    }
    public void setTitle(String title) {
        this.title = title;
    }
    public String getPrice() {
        return price;
    }
    public void setPrice(String price) {
        this.price = price;
    }
}
public class BookManageMentActivityAction extends ActionSupport {
    List<Book> booksList=new ArrayList<Book>();
    BookService bs=new BookServiceImpl();
    HttpServletResponse response=ServletActionContext.getResponse();//响应客户端的请求,将数据发回去
    Book book;
    int bookId;
    //设置set\get方法,自动获值
    public int getBookId() {
        return bookId;
    }

    public void setBookId(int bookId) {
        this.bookId = bookId;
    }

    public void getBookList() {
        JSONArray jsonArray=new JSONArray();
        //调用业务逻辑层
        booksList=bs.getBookList();
        for(int i=0;i<booksList.size();i++) {
            book=new Book();
            book=booksList.get(i);
            JSONObject jsonObject=new JSONObject();
            jsonObject.put("bookId", book.getBookId());
            jsonObject.put("isbn", book.getIsbn());
            jsonObject.put("title", book.getTitle());
            jsonObject.put("price", book.getPrice());
            //这里的图片是直接放在了/WebContent/fileUpload目录下,没有保存到数据库中
            jsonObject.put("bookImage","/fileUpload/book"+i+".png");//书的封面
            jsonArray.add(jsonObject);
        }
        try {
            response.setCharacterEncoding("utf-8");
            response.getWriter().write(jsonArray.toString());
            response.getWriter().flush();
            response.getWriter().close();
        }catch(Exception e) {
            e.printStackTrace();
        }
    }

    public void deleteBook() {
        JSONObject jsonObject=new JSONObject();
        // deleteBook调用的BookServiceImpl.java中已写好的方法
        if(bs.deleteBook(bookId)!=0) {
            jsonObject.put("message", "删除成功");
        }else {
            jsonObject.put("message", "删除不成功");
        }
        try {
            //先以text的格式显示,
            response.setContentType("text/json;charset=utf-8");//设置客户端显示内容的方式
            response.setCharacterEncoding("utf-8");//网络中传输格式
            byte[] bytes=jsonObject.toString().getBytes("utf-8");
            response.setContentLength(bytes.length);
            response.getOutputStream().write(bytes);//write只能传输byte类型的数据
            response.getOutputStream().flush();
            response.getOutputStream().close();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

BookServiceImpl.java中得到图书列表和删除操作的代码如下:

public class BookServiceImpl implements BookService {
    DbConnection  db=new DbConnection();
    ResultSet rs=null;

    @Override
    public List<Book> getBookList() {
        // TODO Auto-generated method stub
        List<Book> books=new ArrayList();
        String strSql="select top 5 * from book_table";
        rs=db.executeQuery(strSql);
        try {
            while(rs.next()){
                Book book=new Book();
                book.setBookId(rs.getInt("bookId"));
                book.setIsbn(rs.getString("isbn"));
                book.setTitle(rs.getString("title"));
                book.setPrice(rs.getString("price"));
                books.add(book);
            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return books;
    }

    @Override
    public int deleteBook(int bookId) {
        // TODO Auto-generated method stub
        int bl=0;
        String strSql="delete from book_table where bookId="+bookId;
        bl=db.executeUpdate(strSql);
        return bl;
    }
}

配置struts.xml文件

    <action name="getBooks" class="jxnu.edu.cn.x3321.action.BookManageMentActivityAction" method="getBookList">
            <result type="json">
                <!-- 返回类型一定要设置成json,不设置返回页面 -->
            </result>
        </action>

        <action name="deleteBook" class="jxnu.edu.cn.x3321.action.BookManageMentActivityAction" method="deleteBook">
            <result type="json">
                <!-- 返回类型一定要设置成json,不设置返回页面 -->
            </result>
        </action>

数据库工具类:

public class DbConnection {
    private String driver="com.microsoft.sqlserver.jdbc.SQLServerDriver";
    //告诉Java数据库名字为什么什么
    private String url="jdbc:sqlserver://localhost:1433;DatabaseName=你的数据库的名字";//协议;库或服务器名称;服务器IP,端口
    //定义访问远程url的用户名
    private String userName="sa";//sql数据库的用户名
    private String passWord="1";//sql密码
    private Connection conn=null;
    private Statement stmt=null;
    private ResultSet rs=null;//存放返回的结果集
    public static void main(String arg[]) {
        DbConnection dc=new DbConnection();//构造函数加载驱动程序
        String sql="insert into book_table values('003','Python','45')";
        dc.executeUpdate(sql);
    }

    public DbConnection() {
        /* *(1)加载驱动程序 *构造函数在new时执行 */
        try {
            Class.forName(driver);//自动注册;需要把驱动的jar包导进来;需处理异常
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    //只进行删除、添加、修改
    public int executeUpdate(String sql) {
        int result=0;//不成功
        //(2)创建连接 getConnection(url,userName,passWord)
        try {
            conn=DriverManager.getConnection(url,userName,passWord);
            //(3)创建statement
            stmt=conn.createStatement();
            //(4)执行sql语句
            result=stmt.executeUpdate(sql);
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return result;
    }

    public ResultSet executeQuery(String sql){
        //(2)创建连接 getConnection(url,userName,passWord)
        try {
                conn=DriverManager.getConnection(url,userName,passWord);
                //(3)创建statement
                stmt=conn.createStatement();
                //(4)执行sql语句
                rs=stmt.executeQuery(sql);
            } catch (SQLException e) {
                e.printStackTrace();
            }
            return rs;
    }

    //关闭连接函数
    //配置文件连接词帮我们管理
    public boolean closeConnection(Connection conn) {
        boolean bl=false;//关闭成功
        if(conn!=null) {
            try {
                conn.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            bl=true;
        }else {
            bl=false;
        }
        return bl;
    }
}