zoukankan      html  css  js  c++  java
  • Android与Struts2、Hibernate打造社交平台

    从数据库查找并返回Json数组

    package com.bq;
    
    import java.util.List;
    
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import net.sf.json.JSONArray;
    
    import org.apache.struts2.interceptor.ServletRequestAware;
    import org.apache.struts2.interceptor.ServletResponseAware;
    import org.hibernate.Query;
    import org.hibernate.SessionFactory;
    import org.hibernate.cfg.Configuration;
    import org.hibernate.classic.Session;
    
    import com.opensymphony.xwork2.ActionSupport;
    
    public class QueryThing extends ActionSupport implements ServletRequestAware,ServletResponseAware{
        Configuration cfg = new Configuration();
        SessionFactory sf = cfg.configure().buildSessionFactory();
        Session s = null;
        List<Thing> list = null;
        HttpServletRequest request;
        HttpServletResponse response;
        public List<Thing> getList() {
            return list;
        }
    
        public void setList(List<Thing> list) {
            this.list = list;
        }
    
        public void show() throws Exception {
            try {
                 this.response.setContentType("text/json;charset=gb2312");
                 this.response.setCharacterEncoding("gb2312");
                s = sf.openSession();
                Query query = s.createQuery("from Thing");
                list = query.list();
                for (int i = 0; i < list.size(); i++) {
                    Thing t = (Thing) list.get(i);
                    System.out.println(t.getContent());
                }
                //如何list转为json数组
                JSONArray jsonArray = JSONArray.fromObject(list);
                String json = jsonArray.toString();
                byte[] jsonBytes = json.getBytes("gb2312");
                 response.setContentLength(jsonBytes.length);
                 response.getOutputStream().write(jsonBytes);
                 response.getOutputStream().flush();
                 response.getOutputStream().close();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                s.close();
                sf.close();
            }
        }
        public void setServletRequest(HttpServletRequest request) {
            this.request = request;
        }
    
        public void setServletResponse(HttpServletResponse response) {
            this.response = response;
        }
    
    }

    Android解析JsonArray和JsonObject

    package com.bq.xiaoyuanqxing;
    
    import java.util.ArrayList;
    
    import org.json.JSONArray;
    import org.json.JSONException;
    import org.json.JSONObject;
    
    public class JsonUnit {
        private ArrayList<Thing> list;
        private Client client;
        
        public Client getClient() {
            return client;
        }
        public void setClient(Client client) {
            this.client = client;
        }
        public ArrayList<Thing> getList() {
            return list;
        }
        public void setList(ArrayList<Thing> list) {
            this.list = list;
        }
        public JsonUnit(){
            list = new ArrayList<Thing>();
        }
        public void parse(String string) {
            try {
                JSONArray array = new JSONArray(string);
                for (int i = 0; i < array.length(); i++) {
                    JSONObject temp = (JSONObject) array.get(i);
                    String content = temp.getString("content");
                    String date = temp.getString("date");
                    String id=String.valueOf(temp.getInt("id"));
                    String publish_id=String.valueOf(temp.getInt("publish_id"));
                    Thing t=new Thing(id,content,date,publish_id);
                    list.add(t);
                }            
    
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        public void jiexi(String string){
            try {
                JSONObject json=new JSONObject(string);
                String id=String.valueOf(json.getInt("id"));
                String client_name=json.getString("client_name");
                String address=json.getString("address");
                String phone=json.getString("phone");
                client=new Client(id,client_name,address,phone);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    通讯中用get参数传递中文,客户端

    package com.bq.xiaoyuanqxing;
    
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.io.UnsupportedEncodingException;
    import java.net.URLEncoder;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    import java.util.TimeZone;
    
    import org.apache.http.HttpEntity;
    import org.apache.http.HttpResponse;
    import org.apache.http.HttpStatus;
    import org.apache.http.client.ClientProtocolException;
    import org.apache.http.client.HttpClient;
    import org.apache.http.client.methods.HttpGet;
    import org.apache.http.impl.client.DefaultHttpClient;
    
    import android.app.Activity;
    import android.os.Bundle;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.Toast;
    
    public class Add extends Activity {
        private String urlAddress="http://10.22.48.229:8080/Qserver/add.action";
        private EditText news;
        private EditText num;
        private String content;
        private String number;
        private Button save_btn;
        private String date;
        private String p_id;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            // TODO Auto-generated method stub
            super.onCreate(savedInstanceState);
            setContentView(R.layout.adduser);
            p_id=getIntent().getStringExtra("p_id");
            news=(EditText) findViewById(R.id.news);
            num=(EditText) findViewById(R.id.num);
            save_btn=(Button) findViewById(R.id.save);
            TimeZone tz = TimeZone.getTimeZone("ETC/GMT-8");TimeZone.setDefault(tz);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd/HH:mm");
            date=sdf.format(new Date());
            save_btn.setOnClickListener(new MyOnClickListener());        
        }
        class MyOnClickListener implements OnClickListener{
            @Override
            public void onClick(View v) {
                content=news.getText().toString();
                number=num.getText().toString();
                String s=doGet(content,date,number,p_id);
                if(s!=""){
            Toast.makeText(getApplicationContext(), "新鲜事已添加", Toast.LENGTH_SHORT).show();
                }
            }
            
        }
    public String doGet(String content,String date,String number,String publish_id){
            try {
                content=URLEncoder.encode(content,"utf-8");
                System.out.println(content);
            } catch (UnsupportedEncodingException e1) {
                e1.printStackTrace();
            }
            String getUrl = urlAddress + "?content="+content+"&date="+date+"&publish_id="+publish_id+"&number="+number;
            HttpGet httpGet = new HttpGet(getUrl);
            HttpClient hc = new DefaultHttpClient();
            try {
                HttpResponse ht = hc.execute(httpGet);
                if(ht.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
                    HttpEntity he = ht.getEntity();
                    InputStream is = he.getContent();
                    BufferedReader br = new BufferedReader(new InputStreamReader(is,"GB2312"));
                    String response = "";
                    String readLine = null;
                    while((readLine =br.readLine()) != null){
                        response = response + readLine;
                    }
                    is.close();
                    br.close();
                    System.out.println("========="+response);
                    return response;
                }else{
                    System.out.println(ht.getStatusLine().getStatusCode());
                    System.out.println("出现了错误");
                    return "error";
                }
            } catch (ClientProtocolException e) {
                e.printStackTrace();
                return "exception";
            } catch (IOException e) {
                e.printStackTrace();
                return "exception";
            }    
        }
        
    }

    服务器端相应程序

    package com.bq;
    
    import java.io.UnsupportedEncodingException;
    import java.net.URLEncoder;
    
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import net.sf.json.JSONArray;
    
    import org.apache.struts2.interceptor.ServletRequestAware;
    import org.apache.struts2.interceptor.ServletResponseAware;
    import org.hibernate.SessionFactory;
    import org.hibernate.Transaction;
    import org.hibernate.cfg.Configuration;
    import org.hibernate.classic.Session;
    
    import com.opensymphony.xwork2.ActionSupport;
    
    public class Add extends ActionSupport implements ServletRequestAware,ServletResponseAware{
        Configuration cfg = new Configuration();
        SessionFactory sf = cfg.configure().buildSessionFactory();
        Session s = null;
        private int id;
        private String content;
        private String date;
        private int publish_id;
        private int number;
        public int getId() {
            return id;
        }
    
        public void setId(int id) {
            this.id = id;
        }
    
        public String getContent() {
            return content;
        }
    
        public void setContent(String content) {
            this.content = content;
        }
    
        public String getDate() {
            return date;
        }
    
        public void setDate(String date) {
            this.date = date;
        }
    
        public int getPublish_id() {
            return publish_id;
        }
    
        public void setPublish_id(int publish_id) {
            this.publish_id = publish_id;
        }
    
        public int getNumber() {
            return number;
        }
    
        public void setNumber(int number) {
            this.number = number;
        }
        HttpServletRequest request;
        HttpServletResponse response;
        public void setServletRequest(HttpServletRequest request) {
            this.request = request;
        }
    
        public void setServletResponse(HttpServletResponse response) {
            this.response = response;
        }
        public void add(){
            try {
            content = new String(content.getBytes("ISO-8859-1"), "utf-8");
            } catch (UnsupportedEncodingException e1) {
                e1.printStackTrace();
            }
            Thing t=new Thing(getContent(),getDate(),getPublish_id(),getNumber());
            try {
                this.response.setContentType("text/json;charset=gb2312");
                this.response.setCharacterEncoding("gb2312");
                s = sf.openSession();
                Transaction tran=s.beginTransaction();
                s.save(t);
                tran.commit();
            String json=t.toString();
            byte[] jsonBytes = json.getBytes("gb2312");
            response.setContentLength(jsonBytes.length);
            response.getOutputStream().write(jsonBytes);
            response.getOutputStream().flush();
            response.getOutputStream().close();
            System.out.println(t.toString());
                
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                s.close();
                sf.close();
            }
        }
    }

    给ListView每个Item设置为一个对象

    maplist= new ArrayList<HashMap<String, String>>();
            jsonUnit.parse(getContent());
            ArrayList<Thing> list=jsonUnit.getList();
            for(int i=0;i<list.size();i++){
                HashMap<String,String> map=new HashMap<String, String>();
                Thing thing=list.get(i);
                map.put("id",thing.getId());
                map.put("content",thing.getContent());
                map.put("date",thing.getDate());
                map.put("publish_id",thing.getPublish_id());
                System.out.println("Activity中显示"+thing.getContent());
                maplist.add(map);            
            }

    菜单的创建与点击

    @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            menu.add(0, 1, 1, "发布");
            return true;
        }
        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            if (item.getItemId() ==1) {
            Intent intent=new Intent(Show.this,Add.class);
            intent.putExtra("p_id", p_id);
            startActivity(intent);
            }
            return true;
            
        }

    通过id参数查找数据库

    package com.bq;
    
    import java.util.List;
    
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import net.sf.json.JSONArray;
    
    import org.apache.struts2.interceptor.ServletRequestAware;
    import org.apache.struts2.interceptor.ServletResponseAware;
    import org.hibernate.Query;
    import org.hibernate.SessionFactory;
    import org.hibernate.cfg.Configuration;
    import org.hibernate.classic.Session;
    
    import com.opensymphony.xwork2.ActionSupport;
    
    public class QueryByID extends ActionSupport implements ServletRequestAware,ServletResponseAware{
        Configuration cfg = new Configuration();
        SessionFactory sf = cfg.configure().buildSessionFactory();
        Session s = null;
        List<Thing> list = null;
        HttpServletRequest request;
        HttpServletResponse response;
        private int id;
        public int getId() {
            return id;
        }
    
        public void setId(int id) {
            this.id = id;
        }
    
        public List<Thing> getList() {
            return list;
        }
    
        public void setList(List<Thing> list) {
            this.list = list;
        }
    
        public void show() throws Exception {
            try {
                 this.response.setContentType("text/json;charset=gb2312");
                 this.response.setCharacterEncoding("gb2312");
                s = sf.openSession();
                Query query = s.createQuery("from Thing where publish_id="+id);
                list = query.list();
                for (int i = 0; i < list.size(); i++) {
                    Thing t = (Thing) list.get(i);
                    System.out.println(t.getContent());
                }
                //如何list转为json数组
                JSONArray jsonArray = JSONArray.fromObject(list);
                String json = jsonArray.toString();
                byte[] jsonBytes = json.getBytes("gb2312");
                 response.setContentLength(jsonBytes.length);
                 response.getOutputStream().write(jsonBytes);
                 response.getOutputStream().flush();
                 response.getOutputStream().close();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                s.close();
                sf.close();
            }
        }
        public void setServletRequest(HttpServletRequest request) {
            this.request = request;
        }
    
        public void setServletResponse(HttpServletResponse response) {
            this.response = response;
        }
    
    }

    利用JqueryMobile来创建注册页面

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
    <!DOCTYPE html PUBLIC "" "">
    <HTML><HEAD>
    <META content="IE=10.000" http-equiv="X-UA-Compatible">
         
    <META charset="GB2312">     
    <META name="viewport" content="width=device-width, initial-scale=1">
     <TITLE>注册</TITLE>        
       <LINK href="lib/jquery.mobile-1.2.0.min.css" rel="stylesheet">
        <LINK href="lib/mobile.css" rel="stylesheet">     
    <SCRIPT src="lib/jquery-1.6.4.min.js"></SCRIPT>
    <SCRIPT src="lib/jquery.mobile-1.2.0.min.js"></SCRIPT>
    <META name="GENERATOR" content="MSHTML 10.00.9200.16576"></HEAD> 
    <BODY>
    <DIV data-role="page">
    <DIV data-role="header" data-position="inline"> 
    <H1>注册</H1></DIV>
    <DIV data-role="content">
    <FORM action="http://10.22.48.229:8080/Qserver/register.action" method="POST">
    <INPUT name="from_mobile" type="hidden" value="1">    
    <INPUT name="goto_page" type="hidden" value="/regok">
    <INPUT name="error_page" 
    type="hidden" value="/reg"> 
    <LABEL for="login_nameLabel" >用户名:</LABEL><BR>
    <INPUT name="client_name" class="ui-input-text ui-body-null ui-corner-all ui-shadow-inset ui-body-c" id="login_name" type="text"><BR> 
    <LABEL for="login_tel">手机:</LABEL><BR>
    <INPUT name="phone" class="ui-input-text ui-body-null ui-corner-all ui-shadow-inset ui-body-c" id="tel" type="tel"><BR>
    <LABEL for="login_pwordLabe" >密码:</LABEL><BR>
    <INPUT name="password" class="ui-input-text ui-body-null ui-corner-all ui-shadow-inset ui-body-c" id="login_pword" type="password"><BR>
    <LABEL>地址:</LABEL><BR>
    <INPUT name="address" class="ui-input-text ui-body-null ui-corner-all ui-shadow-inset ui-body-c" id="login_address" type="text"><BR> 
    <BUTTON type="submit" data-theme="b" data-inline="true">注册新用户</BUTTON>
    <HR>
    </FORM>
    </DIV>
    <DIV class="footer-docs" data-role="footer" data-theme="c">
    <P>&nbsp;2012~2013  白强</P>
    </DIV>
    </BODY>
    </HTML>

    还有一些其他问题,但是主要的就是这样的了

  • 相关阅读:
    IE hack [if IE]解决IE CSS 兼容问题
    jQuery重要插件、JS辅助工具
    几个jQueryUI框架
    推荐书籍
    Win7下用原生的ie6调试网页
    Code First :使用Entity. Framework编程(3)
    Code First :使用Entity. Framework编程(6)
    JSON数据格式转换
    Code First :使用Entity. Framework编程(5)
    Code First :使用Entity. Framework编程(4)
  • 原文地址:https://www.cnblogs.com/bq12345/p/3175624.html
Copyright © 2011-2022 走看看