Android Backend Server build-up

Source: Internet
Author: User
Tags string format

Always do Android front-end, today suddenly whim want to build a backstage play. Usually need what kind of interface directly out of the interface documents thrown to the back of the brothers, they never worry about their internal implementation problems. Today, with a curious mind to build a Java compiler environment in the background server. I heard that using PHP to build the majority of servers, but we are big Android is the most familiar or Java, so I began to build this server. Very simple...

First I downloaded a myelipse should be for us to develop Android Eclipse cannot create Web project otherwise you go to download a plugin also line, download good later create Web project will generate a directory, then right click on your project to choose MyEclipse --Add structs capabilities ... Select 2.1 Finish OK this will create a successful project, the following I put out my project tree for your reference (thanks to yayun0516, his blog has given me a lot of help, but there are some deficiencies I have been corrected below)

Configure Structs.xml below

<?XML version= "1.0" encoding= "UTF-8"?><!DOCTYPE struts Public "-//apache software foundation//dtd struts Configuration 2.1//en" "http://struts.apache.org/ Dtds/struts-2.1.dtd "><Struts>    < Packagename= "Struts2"extends= "Struts-default"namespace="/">        <Actionname= "Getjson"class= "Com.shao.action.JSONAction"Method= "JSON">            <resultname= "Success">index.jsp</result>        </Action>    </ Package></Struts>    

Only this one needs to be configured, and the others will be generated automatically when you add a struct. Create type file below

 PackageCom.shao.domain; Public classMusic {PrivateInteger ID; PrivateString name; PrivateString time; PrivateString author;  PublicInteger getId () {returnID; }         Public voidsetId (Integer id) { This. ID =ID; }         PublicString GetName () {returnname; }         Public voidsetName (String name) { This. Name =name; }         PublicString GetTime () {returnTime ; }         Public voidsettime (String time) { This. Time =Time ; }         PublicString Getauthor () {returnauthor; }         Public voidSetauthor (String author) { This. Author =author; }     }   

Then create a method to jsonaction the JSON:

 Packagecom.shao.action;Importjava.io.IOException;Importjava.io.UnsupportedEncodingException;ImportJava.net.URLDecoder;Importjava.util.ArrayList;Importjava.util.List;Importjavax.servlet.http.HttpServletRequest;ImportJavax.servlet.http.HttpServletResponse;ImportOrg.apache.struts2.interceptor.ServletRequestAware;ImportOrg.apache.struts2.interceptor.ServletResponseAware;ImportCom.google.gson.Gson;ImportCom.opensymphony.xwork2.ActionSupport;ImportCom.shao.domain.Music; Public classJsonactionextendsActionsupportImplementsServletrequestaware, Servletresponseaware {/**       *        */    Private Static Final LongSerialversionuid = -3604892179657815531l; PrivateHttpServletRequest request; Privatehttpservletresponse response; PrivateString format;  PublicString GetFormat () {returnformat; }     Public voidsetformat (String format) { This. Format =format; } @Override Public voidsetservletrequest (HttpServletRequest request) { This. Request =request; } @Override Public voidSetservletresponse (httpservletresponse response) { This. Response =response; }     Public voidjson () {List<Music> list =NewArraylist<music>(); Gson Gson=NewGson (); Music M1=NewMusic (); M1.setid (1); M1.setauthor (Week); M1.setname (Grandma); M1.settime ("04:04");        List.add (M1); Music m2=NewMusic (); M2.setid (2); M2.setauthor ("Jay Chou"); M2.setname ("Orcs."); M2.settime ("04:05");        List.add (m2); Music M3=NewMusic (); M3.setid (3); M3.setauthor ("Jay Chou"); M3.setname (Ukulele); M3.settime ("02:55");        List.add (m3); Java.lang.reflect.Type Type=NewCom.google.gson.reflect.typetoken<list<music>>() {}.gettype ();//Specify TypeString Beanlisttojson = Gson.tojson (list, type);//list converted to JSON stringSystem.out.println ("gson-->" +Beanlisttojson); Try{Response.setcontenttype ("Application/json; CHARSET=GBK "); Response.setcharacterencoding ("UTF-8");  This. Response.getwriter (). write (Beanlisttojson); } Catch(IOException e) {e.printstacktrace (); }    }}
Response.setcontenttype ("Application/json; CHARSET=GBK "); Be sure to note that if you do not add this sentence will be in your request server data, Chinese garbled phenomenon, while in index.jsp added contenttype=" text/html; CHARSET=GBK "
And don't forget to import the Gson package.
That's it, that's it. The server is finished, run as MyEclipse Service application after the success will pop up a box that says this is my JSP page. That means you've successfully created the server.
Below open http://localhost:8080/Test2/getjson.action below is the content returned by the server.


Basically this is the case, and do not understand can ask me. The following is the Android side, more simple.
Create our project and then join the Xutils and Gson packages.

This is a new project, in Activity_main.xml I added an ID to that TextView
It is then implemented in Mainactivity as follows:
 PackageCom.example.test2;Importcom.lidroid.xutils.HttpUtils;Importcom.lidroid.xutils.exception.HttpException;ImportCom.lidroid.xutils.http.ResponseInfo;ImportCom.lidroid.xutils.http.callback.RequestCallBack;ImportCom.lidroid.xutils.http.client.HttpRequest.HttpMethod;Importandroid.support.v7.app.ActionBarActivity;ImportAndroid.os.Bundle;ImportAndroid.util.Log;ImportAndroid.view.Menu;ImportAndroid.view.MenuItem;ImportAndroid.view.View;ImportAndroid.widget.TextView; Public classMainactivityextendsactionbaractivity {@Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);        Setcontentview (R.layout.activity_main); FinalTextView Text =(TextView) Findviewbyid (R.id.text); Httputils httputils=Newhttputils (); Httputils.send (Httpmethod.post,"Http://192.168.199.171:8080/Test2/getjson.action",NewRequestcallback<string>() {             Public voidonfailure (HttpException arg0, String arg1) {LOG.D ("=====================onfailure", arg1+ ";" +arg0.tostring ()); }             Public voidOnsuccess (responseinfo<string>arg0) {LOG.D ("=====================onsuccess", Arg0.result);            Text.settext (Arg0.result);    }                            }); } @Override Public BooleanOncreateoptionsmenu (Menu menu) {//inflate the menu; This adds items to the action bar if it is present.getmenuinflater (). Inflate (R.menu.main, menu); return true; } @Override Public Booleanonoptionsitemselected (MenuItem item) {//Handle Action Bar item clicks here. The Action Bar would//automatically handle clicks on the Home/up button, so long//As you specify a the parent activity in Androidmanifest.xml.        intID =Item.getitemid (); if(id = =r.id.action_settings) {            return true; }        return Super. onoptionsitemselected (item); }}

This is the case with the entire Android, let's run it. The data just now appears on the TextView.

In fact the entire code content is very simple, the main difficult place is in the environment to build, we practice it, the entire code is I ran down, so the code is not a problem, if you run not successful on more research environment to build.

Share this, you can learn more about this in the past, even if not to do background development, but also to learn more about, reduce the cost of communication.

Android Backend Server build-up

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.