Java server provides external interface and Android server requests data

Source: Internet
Author: User

Explain how the Java server provides the interface to the mobile terminal, in what data format to provide, the mobile side is how to request the server, receive and parse the return data.

Service side: Or in the original S2SH framework of the project (build ssh detailed steps and related instructions), to join the servlet to provide interface to the terminal things.

Android: Use a network access framework okhttp to request data from the server.

Service side:

The servlet receives a GET, POST request from the mobile side and writes the data to be returned in JSON format after the corresponding logical processing.

Operations on the database the traditional servlet is JDBC, but the operation is too cumbersome to reuse hibernate in the project. So how do I use hibernate in a servlet?

The servlet is defined in Web. XML, with the new Classpathxmlapplicationcontext ("Applicationcontext.xml") in the Servlet class, and the Spring container is available, Hibernate can then be taken to manipulate the database.

ApplicationContext ac=New classpathxmlapplicationcontext ("Applicationcontext.xml"); Userdao Userdao= (Userdao) ac.getbean ("Userdao"); List<User> userlist=userdao.findall ();

When using JSON, you must import the jar:

Commons-beanutils-1.7.0.jar

Commons-collections-3.2.1.jar

Commons-httpclient-3.1.jar

Commons-lang-2.3.jar

Commons-logging-1.1.1.jar

Ezmorph-1.0.3.jar

Json-lib-2.2.3-jdk15.jar

Userservlet.java

 PackageJoanna.yan.servlet;Importjava.io.IOException;ImportJava.io.PrintWriter;Importjava.util.List;Importjavax.servlet.ServletException;ImportJavax.servlet.http.HttpServlet;Importjavax.servlet.http.HttpServletRequest;ImportJavax.servlet.http.HttpServletResponse;ImportJoanna.yan.dao.UserDAO;ImportJoanna.yan.entity.User;ImportNet.sf.json.JSONArray;ImportNet.sf.json.JSONObject;ImportOrg.springframework.context.ApplicationContext;ImportOrg.springframework.context.support.ClassPathXmlApplicationContext; Public classUserservletextendshttpservlet{@Overrideprotected voiddoget (httpservletrequest req, HttpServletResponse resp)throwsservletexception, IOException {doPost (req, resp); } @Overrideprotected voidDoPost (httpservletrequest req, HttpServletResponse resp)throwsservletexception, IOException {System.out.println ("Have been visited!" "); PrintWriter out=Resp.getwriter (); Jsonobject JSON=NewJsonobject (); Jsonobject Json1=NewJsonobject (); String msg= "Success"; intErrorcode=0; ApplicationContext AC=NewClasspathxmlapplicationcontext ("Applicationcontext.xml"); Try{Userdao Userdao= (Userdao) ac.getbean ("Userdao"); List<User> userlist=Userdao.findall (); if(Userlist.size () >0) {Jsonarray Jsonarray=NewJsonarray ();  for(User user:userlist) {json1.put ("id", User.getid ()); Json1.put ("Username", User.getusername ()); Json1.put ("Age", User.getusername ());                Jsonarray.add (Json1); } json.put ("Data", Jsonarray); }Else{msg= "No Data meets Requirements"; ErrorCode=1; Json.put ("Data", "" "); }        } Catch(Exception e) {e.printstacktrace (); Msg= "System Error"; ErrorCode= 10000; }finally{json.put ("Message", MSG); Json.put ("ErrorCode", errorcode);            Out.print (JSON);            Out.flush ();        Out.close (); }    }}

Configuring Userservlet in Web. xml

 <servlet>    <Servlet-name>Userservlet</Servlet-name>    <Servlet-class>Joanna.yan.servlet.UserServlet</Servlet-class>  </servlet>  <servlet-mapping>    <Servlet-name>Userservlet</Servlet-name>    <Url-pattern>/user</Url-pattern>  </servlet-mapping>

Android side:

Using okhttp, download Okhttp-2.7.0.jar and Okio-1.6.0.jar into Libs under the official website and add Build Path. Add Gson-2.2.4.jar to parse JSON data at the same time

Mainactivity.java

 Packagecom.example.commussh;Importjava.io.IOException;ImportJava.util.Map;Importandroid.app.Activity;ImportAndroid.os.Bundle;ImportAndroid.view.View;ImportAndroid.widget.Button;ImportAndroid.widget.TextView;ImportCom.google.gson.Gson;Importcom.squareup.okhttp.OkHttpClient;Importcom.squareup.okhttp.Request;ImportCom.squareup.okhttp.Response; Public classMainactivityextendsActivity {TextView tv_show;    Button Btn_search;    Okhttpclient client;    Gson Gson; Static classGist {Map<string, gistfile>files; }    Static classGistfile {String content; } @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);                Setcontentview (R.layout.activity_main); Client=Newokhttpclient (); Gson=NewGson (); Tv_show=(TextView) Findviewbyid (r.id.tv_show); Btn_search=(Button) Findviewbyid (R.id.btn_search); Btn_search.setonclicklistener (NewView.onclicklistener () {@Override Public voidOnClick (View v) {NewThread (NewRunnable () {@Override Public voidrun () {Request Request=Newrequest.builder (). URL ("Http://localhost:8080/SSH/user"). build ();                        Response Response; Try{Response=Client.newcall (Request). Execute (); if(!response.issuccessful ())Throw NewIOException ("Unexpected code:" +response); Gist Gist= Gson.fromjson (Response.body (). Charstream (), Gist.class);  for(Map.entry<string, gistfile>Entry:gist.files.entrySet ())                              {System.out.println (Entry.getkey ());                            System.out.println (Entry.getvalue (). content); }                        } Catch(IOException e) {e.printstacktrace ();            }}). Start ();    }        }); }}

Test results:

Source: Http://pan.baidu.com/s/1mgU7xKs Extract Code: pe9i

Java server provides external interface and Android server requests data

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.