Android Login and session-keeping solutions

Source: Internet
Author: User

The project did half the technical manager resign, leaving a mess. Web Basic has been done, Android app to write new, project development finished to do a summary, this thing has been done a long time ago.

The login interface is soon written, the user information after the login is cached and then the session

 /*** User Login * *@paramUser *@return     */@RequestMapping (Value= "Dologin") @ResponseBody Publicmap dologin (user user, HttpServletRequest request) {map result=Maps.newhashmap (); Try{loginresult flag=frontuserutils.dologin (user, request); if(Flag = =Loginresult. Login successful) {Map<string, object> map =NewHashmap<>(); String[] Propertys=Newstring[]{"name", "Photo", "Singleid"};  for(String property:propertys) {Map.put (property, Reflections.invokegetter (Frontuserutils.getuserb                Ysession (), property)); } result.put ("Flag", 1); Result.put ("User", map); returnresult; } Else if(Flag = =loginresult. User is locked out) {result.put ("Flag", 0); Result.put ("MSG", "The user is locked out, please contact the administrator!" "); returnresult; } Else if(Flag = =Loginresult. Login failed) {Result.put ("Flag", 0); Result.put ("MSG", "Incorrect account or password!" "); returnresult; }        } Catch(Exception e) {result.put ("Flag", 0); Result.put ("MSG", "Operation failed!" ");        E.printstacktrace (); }        returnresult; }
/

But after the successful login, and then call other needs to obtain the login user information when the time found in the session did not, Ah, obviously self-test is OK, ah, I do not know why,

Technical Manager also ran, do not know how the matter ah, how the whole, I go to ask Android, he also does not understand Ah, I also go.

Then debug test it, with a browser not so Ah, the session is the same. Test it and print the SessionID in the background:

Browser Access interface:

Analog Android Access interface:

Each time a new session has been generated, so do not ah, every request to generate a new session, how do I cache your login user information ah.

And try to figure it out. Two Solutions

Scenario 1: Custom Identity mode (token), similar to your own simulation session

  After the user logs in, a unique identity is generated within the system, and the identity is returned to the client. The identity is saved for 15 days, if the user logs on at another terminal, or if the 15-day timeout in the server does not have a business, the terminal session will be notified to time out and log back on.

  The background code is not affixed, using the UUID generated by a string, as the user's login identity, the user information is written to the cache, similar to key:user storage.

When the user requests the other interface, it will be intercepted by one of my interceptors, and the user will be removed from the system if it finds that the query is not based on a string query .

Interceptors:

 Public classLogininterceptorImplementsHandlerinterceptor {@Override Public BooleanPrehandle (HttpServletRequest httpservletrequest, HttpServletResponse httpservletresponse, Object o)throwsException {User User=Frontuserutils.getuser (); if(User = =NULL|| User.getid () = =NULL|| User.getid (). Equals ("") {Returnjson (httpservletresponse); return false; } Else {            return true; }} @Override Public voidPosthandle (HttpServletRequest httpservletrequest, HttpServletResponse httpservletresponse, Object o, ModelAndView Modelandview)throwsException {} @Override Public voidAftercompletion (HttpServletRequest httpservletrequest, HttpServletResponse httpservletresponse, Object o, Exception E )throwsException {e.notifyall (); }    Private voidReturnjson (httpservletresponse response)throwsException {printwriter writer=NULL; Response.setcharacterencoding ("UTF-8"); Response.setcontenttype ("Text/html; Charset=utf-8 "); Try{map Map=NewHashMap (); Map.put ("Flag", 0); Map.put ("MSG", "Login session has expired, please re-login!" "); Jsonobject Jsonobject=jsonobject.fromobject (map); Writer=Response.getwriter ();        Writer.print (Jsonobject); } Catch(IOException e) {}finally {            if(Writer! =NULL) Writer.close (); }    }}

This write, sacrificing a part of the system performance, to achieve a long connection between Android and the server, because the basic interception of all interfaces, each time to determine whether to log on, or login time-out.

Scenario 2: Or use SessionID, in fact, both ways are similar, but I still recommend this, the first kind of flowers at the same time too many users, too many sessions, may lead to other problems.

Web browser to keep the session, because there is a session, different servers in the browser when the request will determine whether it is the first request, if it is the first time to return a parameter Set-cookie, the General browser support itself to save this data, This data is also the browser and server to maintain the identity of the session;

For example, Baidu as an example:

Requesting the same server again, the browser will take these values out of the cookie and load it into the browser's request.

If the browser does not disable cookies, the browser will save the data returned by the server to the cookie, the session and cookie is not clear, to check the information.

How to access Android

Although Android can use many network frameworks to access, but I do not know well, plus the company's Android development is not very understanding,

I think he's using httpclient similar way to access, I thank a code to simulate the next Android request, to get the data returned by the server, see if can get to Set-cookie;

public class Mainactivity {public    static final String login_url= "Http://192.168.0.112:8080/login/doLogin? Loginname=18866601116&password=123456zxc ";    /**     * Android Login Test     * @param args     * @throws Exception *     /public    static void Main (string[] args) throws Excep tion {        url url=new url (login_url);        HttpURLConnection con= (httpurlconnection) url.openconnection ();        Con.setrequestmethod ("GET");        String Cookiestring=con.getheaderfield ("Set-cookie");        System.out.print (cookiestring);    }}
Console output

Oh, yes. Let Android first request the server again when the SessionID save it, cache to the phone,

Then, when requesting the background, the saved cookie is placed in the HttpPost request so that when the server is accessed, the server will be considered the same user. That is to say, keep this conversation.

In fact, the principle of the two methods are similar, if there is a better solution, you can also tell me, learn.

Android Login and session-keeping solutions

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.