The implementation of Java Web back-end registration interface from zero development of App II __java

Source: Internet
Author: User
Tags java web

Today we are going to complete the design of the interface in the previous blog, linked to the design of a Java web back-end registration interface from zero development. The general design of the previous article, the client incoming username, password, nickname, and then the server to verify, depending on the situation to return different results.

First, according to the request sample from the request interface written in the previous section, our server side needs to read the result of the request from the request, the sample requested is {s:{"uname" =xxx, "Upwd" =xxx, "Nkname" =xxx}}, but if we each receive a request, All need to get the jsonobject of S, and then go one by one to parse, this is too painful, and do too much repetition code. So, we can put JSON parsing into the parent class.

As we know, each request in the Java Web is mapped to the service () method in the corresponding HttpServlet class object, and in the HttpServlet Service () method, the source of the request will invoke its own different methods to handle, depending on the requested type. For example, if the request type is get, call your own Doget () method, and call your own Dopost () method if the request type is post. So, we can overwrite the HttpServlet service () method and make JSON parsing in it. We use the JSON parsing is Alibaba open source Fastjson.

The following is the source code for Baseservlet:

/**
 * All HttpServlet base classes will remove the encrypted string from the request and decrypt it (not yet decrypted)
 * @author Liuheng */Public
class Baseservlet extends HttpServlet {
	
	
	//requested JSON
	protected jsonobject Requestjson;
	
	@Override
	protected void Service (HttpServletRequest req, HttpServletResponse resp) throws Servletexception, IOException {
		
		String securitystring = Req.getparameter ("s");
		SYSTEM.OUT.PRINTLN ("Obtained encryption string is" + securitystring);
		
		Requestjson = Json.parseobject (Urldecoder.decode (securitystring, "UTF8"));
		
		Super.service (req, resp);
	}
As we can see, we directly parse the string of S into Jsonobject, and the class can be used. It should be noted that all of our requests use post, so subclasses only need to copy the Dopost () method.

Get the request parameters, you should do the corresponding logical processing, such as to determine whether there is a duplicate user name, whether there is a duplicate nickname, when there is no judgment, to write, this time if the write failed, you also need to return the failed flag bit. We collectively refer to this kind of logical processing class as the service class.

Just one service class is not enough, we also need to do database access to the DAO class, DAO mode is one of the standard Java EE design patterns. Developers use this pattern to separate the underlying data access operations from the high-level business logic, that is, we use the DAO class to encapsulate the code that accesses the database, and we can call the DAO class directly to get the object we need without considering the implementation within the database.

The entity classes are:

public class User extends IdEntity {
	private String name;
	private String password;
	Private String nickname;
	Private String token;
	
	
	
	
	Public String GetName () {return
		name;
	}
	public void SetName (String name) {
		this.name = name;
	}
	Public String GetPassword () {return
		password;
	}
	public void SetPassword (String password) {
		this.password = password;
	}
	Public String Getnickname () {return
		nickname;
	}
	public void Setnickname (String nickname) {
		this.nickname = nickname;
	}
	Public String GetToken () {return
		token;
	}
	public void Settoken (String token) {
		This.token = token;
	}
	
	
	
}
The Userdao interface is:

Public interface Userdao {/** * saves user to database * * @param connection * @param user/public void Save (Connect

	Ion connection, user user) throws SQLException;  /** * Query The database if there is a corresponding userName, if any, return the corresponding ID, no, return 0 * * @param connection * * @param userName * @return * * * public int

	Queryusername (Connection Connection, String userName) throws SQLException; /** * Password is correct based on the user querying the corresponding ID in the database. If correct, return the corresponding ID, otherwise return 0 * * @param connection * @param user * @return * @throws SQLException/public int QUERYP

	Assword (Connection Connection, int ID, String password) throws SQLException; /** * Update Token * * @param connection * @param userId * @param token * @throws SQLException */PU for user with specified ID
	
	Blic void Updatetoken (Connection Connection, int userId, String token) throws SQLException; /** * Obtains the user's ID according to token, if not, returns 0 * @param connection * @param token * @throws SQLException/public int Getuseri D (Connection Connection, String token) throws SQLexception;
 }
The corresponding implementation classes are:

public class Userdaoimplement extends Basedaoimplement implements Userdao {@Override public void Save (Connection Conne  ction, user user) throws SQLException {PreparedStatement statement = connection. Preparecall ("INSERT INTO Tal_user

		(name,password,nickname) VALUES (?,?,?) ");
		Statement.setstring (1, User.getname ());
		Statement.setstring (2, User.getpassword ());

		Statement.setstring (3, User.getnickname ());
	Statement.execute (); public int Queryusername (Connection Connection, String userName) throws SQLException {PreparedStatement statement

		= Connection.preparecall ("select * from tal_user where name =?");
		
		Statement.setstring (1, userName);
		ResultSet set = Statement.executequery ();
		Next is not NULL, indicating that the database contains this field, then the ID if (Set.next ()) {return set.getint ("id") of this data is returned;
		else {return 0; @Override public int Querypassword (Connection Connection, int ID, String password) throws SQLException {PREPA Redstatement statement = Connection.preparecall ("SELECT * from tal_user where id =?"

		and password =? ");
		Statement.setint (1, id);

		Statement.setstring (2, password);
		ResultSet set = Statement.executequery ();
		Next is not NULL, indicating that the database contains this field, then the ID if (Set.next ()) {return set.getint ("id") of this data is returned;
		else {return 0; @Override public void Updatetoken (Connection Connection, int userId, String token) throws SQLException {Prepar Edstatement statement = connection.preparecall ("update tal_user set token =?

		WHERE id =? ");
		Statement.setstring (1, token);

		Statement.setint (2, userId);
	Statement.execute (); @Override public int GetUserID (Connection Connection, String token) throws SQLException {PreparedStatement Stateme
		
		NT = Connection.preparecall ("select * from tal_user where token =?");
		Statement.setstring (1, token);
		
		Statement.executequery ();
		ResultSet set = Statement.executequery ();
		if (Set.next ()) {return set.getint ("id");
		else {return 0;
 }
	}

}
Once the DAO class is written, we can write the logical service class, for example, if we need to determine if there is a corresponding username, we should call the Queryusername () method of the DAO class and, if returned to 0, have the same username.

Below is the Loginservice class source code:

public class Loginservice {private Userdao Muserdao = new Userdaoimplement ();

	private static final int result_null_username = 1,result_wrong_password = 2;
		Public Loginresult Login (string userName, String passWord) {Connection Connection = null;
		
		Loginresult result = new Loginresult ();
		
		Connection = Connectionfactory.getinstance (). MakeConnection ();
			try {//1, first determine if there is a corresponding username int id = muserdao.queryusername (connection, userName);
				if (id = = 0) {result.setcode (result_null_username);
			return result;
			}//2, in determining whether the password is correct int userId = Muserdao.querypassword (connection, ID, PassWord);
				if (userId = = 0) {result.setcode (Result_wrong_password);
			return result;
			}//3, set the corresponding token long currenttime = System.currenttimemillis ();
			
			String token = userid+ "_" +currenttime;
			Muserdao.updatetoken (connection, userId, token);
			Result.setcode (0);
			
			Result.settoken (token);
		return result; catch (SQLException e) {E.priNtstacktrace ();
			Result.setcode (100);
		return result;
 }	
	}
	
}
After writing the Loginservice class, our service-side code is nearing completion, and all we need to do is write a baseservlet subclass and then make a copy of the Onpost () method, get the requested arguments, and call the Loginservice class to get the returned arguments. After wrapping, use Fastjson to parse back into JSON.

The following is the source code for the Loginservlet class:

@WebServlet ("/login") public class Loginservlet extends Baseservlet {private static final long Serialversionuid = 72453

	61420327420429L; 
		
		@Override protected void DoPost (HttpServletRequest req, HttpServletResponse resp) throws Servletexception, IOException {
		String userName = requestjson.getstring ("uname");

		String PassWord = requestjson.getstring ("Upwd");

		SYSTEM.OUT.PRINTLN ("The requested UserName is + userName +" \ n The requested PassWord is "+ PassWord");
		Loginservice service = new Loginservice ();

		Loginresult Loginresult = Service.login (UserName, PassWord);
		map<string, object> map = new hashmap<> ();
		Map.put ("Result", Loginresult.getcode ());
			If successful, also need to add token if (loginresult.getcode () = = 0) {map<string, object> datamap = new hashmap<> ();
			
			Datamap.put ("token", Loginresult.gettoken ());
		Map.put ("Data", Datamap);
		String result = json.tojsonstring (map);
		
		SYSTEM.OUT.PRINTLN ("The result is" +result);
		PrintWriter printwriter = Resp.getwriter (); PrinTwriter.write (result);
	Printwriter.close (); }

}
Above wrote the landing interface to achieve most of the analysis, but also some source code did not post, you can access this link: server-side code GitHub address to get and run the server-side source. In addition, the Android side of the code also wrote a login, registration interface, landing functions have been achieved. The address is the Android-side code GitHub address. Welcome to All Star.


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.