Java Web Development (ii) interface development

Source: Internet
Author: User
Tags object object tojson

Java Web Development (a) environment building explains how to build a basic project, if you do not understand, you can go to see! Today we will look at the development of interfaces, and intend to use older or more primitive methods to implement the interface.

I. Database design.

I'm going to do a simple student information management system, the database name is Students_manage, and first design a student table, the table named student.

1. Open the Sqlyong tool, if you have not created a connection, you can click New, enter a name, click OK,

2. Then select in the saved connection, just new connection, just need to enter in the Password input box, install the Database settings password, click Connect, other default,


If all is OK, then the following interface will appear, which means the connection is successful!


3. After successful connection, first create database, left blank area, right mouse button, create database, enter database name Students_manage, other default,


Click Create, and then in the list of databases on the left there will be one more Students_manage database.


4. Once the database is created, we can create a database table, select the Tables folder in the Students_manage database, create a table on the right, enter a table field, type, set the primary key, be empty, etc.


Click the Create TABLE button and you will see a student table in the Tables folder,


5. Double-click the Student table, the table will open, we need to give the table, first initialize some data, click on the table data, and then insert the data, click Save.


There are 2 records in this table.

The simple design of the database is almost there, and then we need to develop the interface!

Two. Interface project development.

The data format returned by the interface is JSON, and if you are unfamiliar with JSON, you can first look at the JSON usage and JSON parsing of the article.

1. Create a new project. That's not much to say! If this piece is not yet understood, please read this article, Java Web Development (a) environment.

2. Design the JSON data.

2.1. The JSON data format returned by the interface is as follows:

(1). Returns the object,

{"Code": "", "MSG": "", "Time": 1464937933230, "Object": {}}
(2). Returns an array,

{"Code": "", "MSG": "", "Time": 1464937933230, "items": [{},{}]}
The design is now returned to the above two formats. If you have pagination, you can add it. Here's a look at the code and instructions.

(1). Build, Abstractjsonobject (the base class for JSON data), specifically implemented as follows:

public class Abstractjsonobject {        //codeprivate string code;//msgprivate string msg;private Long time = new Date (). Get Time ();p ublic String GetCode () {return code;} public void Setcode (String code) {this.code = code;} /** * @return The time */public Long GetTime () {return time;} /** * @param time * The time to            set */public void SetTime (Long time) {this.time = time;} Public String getmsg () {return msg;} public void Setmsg (String msg) {this.msg = msg;} public void SetContent (string code, String msg) {This.code = Code;this.msg = msg;} public void Setstatusobject (Statusobject statusobject) {This.code = Statusobject.getcode (); this.msg = Statusobject.getmsg ();}}
Where Statusobject is a state object that encapsulates the status Code (code) and status information (MSG), implemented as follows:

/** * Status Object */public class Statusobject {//Status code private string code;//state information private string msg;public statusobject (string cod E, String msg) {super (); This.code = Code;this.msg = msg;} Public String GetCode () {return code;} public void Setcode (String code) {this.code = code;} Public String getmsg () {return msg;} public void Setmsg (String msg) {this.msg = msg;}}
(2). Create a JSON object class, Singleobject, code:

public class Singleobject extends Abstractjsonobject {Private Object Object;public object GetObject () {return object;} public void SetObject (Object object) {This.object = object;}}
(3). Create a JSON array class, ListObject, code:

public class ListObject extends Abstractjsonobject {//List object private list<?> items;public list<?> GetItems () {R Eturn items;} public void Setitems (list<?> items) {this.items = items;}}
After the steps above, the JSON data format we need has been created, and then we need to parse the JSON data, which I have chosen to download in the Jackjson,jackjson library. After downloading the Jackson Library, import three packages into the project's Lib, as shown in:

(4). Jackjsonutils generate JSON data and parse JSON data, code:

public class Jackjsonutils {static Objectmapper objectmapper;/** * Parse JSON *  * @param content * @param valueType * @ret Urn */public static <T> T Fromjson (String content, class<t> valueType) {if (Objectmapper = = null) {Objectmappe R = new Objectmapper ();} try {return Objectmapper.readvalue (content, ValueType),} catch (Exception e) {e.printstacktrace ();} return null;} /** * Generate JSON *  * @param object * @return */public static String ToJson (Object object) {if (Objectmapper = = null) {Obje Ctmapper = new Objectmapper ();} try {return objectmapper.writevalueasstring (object),} catch (Exception e) {e.printstacktrace ();} return null;}}
At this point, the JSON data design is OK! Isn't it that hard to imagine? Maybe, it's really that simple! Next, is the development of the interface.

3. Interface development.

This article developed the interface using the old servlet implementation, about the servlet, please find the data yourself, there is not much to say (in fact, I also smattering)

3.1. Create a class that inherits from HttpServlet, such as studentinq, right mouse button, new--select Servlet, as shown in the Servlet name, click Finish button, OK!

At this point you will find that the package has more than one STUDENTINQ class, specific code:

public class Studentinq extends HttpServlet {private static final long Serialversionuid = 1l;/** * @see httpservlet#httpse Rvlet () */public studentsinq () {super ();//TODO auto-generated Constructor stub}/** * @see Httpservlet#doget ( HttpServletRequest request, HttpServletResponse *      response) */protected void doget (HttpServletRequest request, HttpServletResponse response) throws Servletexception, IOException {//TODO auto-generated method stub}/** * @see Httpserv Let#dopost (httpservletrequest request, HttpServletResponse *      response) */protected void DoPost ( HttpServletRequest request, HttpServletResponse response) throws Servletexception, IOException {//TODO auto-generated Method Stubdoget (Request, Response);}}
Implement the Doget () and Dopost methods of HttpServlet, where only doget () is implemented for simplicity.

PS: If you are more careful, you will find in the Web. xml file a few more lines of code, as follows: (Web. XML is a very important configuration file in the network program, more specific, detailed query related documents)


You can see that we just created the servlet, which is shown in this XML file. We will use this configuration list when we call the interface later.

3.2. Interface implementation.

We will simply implement a student query interface! Invokes the query interface to return all student information in the database.

(1). Create a new interface Studentservice, code:

Public interface Studentservice {public list<students> getallstudents ();}
(2). Implement the interface, Studentserviceimpl code:

public class Studentserviceimpl implements studentservice{@Overridepublic list<students> getallstudents () {// TODO auto-generated Method Stubreturn studentbusiness.getallstudents ();}}
Among them, Studentbusiness provides a way to obtain student information from a database. The database operations are described below. Next, we implement the servlet's Doget (), Specific code:

list<students> list = Studentbusiness.getallstudents (); ListObject listobject=new ListObject (); Listobject.setitems (list); Listobject.setstatusobject (STATUSHOUSE.COMMON_STATUS_OK); String responsetext = Jackjsonutils.tojson (ListObject); Responseutils.renderjson (response, responsetext);
Where Responseutils is writing the returned JSON data to response.

At this point, the interface returned data has been successful! There is currently no database connected, so the next step is to work with the database.

4. Database operations.

At the beginning of the article, we have created the database as well as the table and added several test data. Data is available, we need to get it in the project, so how to do it?

(1). Database connection.

We connect the MySQL database, we need to import the Mysql-connector.jar,jar package download link to download the good jar, import into the Lib directory.

(2). Establish the DBHelper connection database and close the connection:

public class DBHelper {public static final String URL = "Jdbc:mysql://localhost:3306/students_manage";      public static final String name = "Com.mysql.jdbc.Driver";      public static final String user = "* * *";      public static final String password = "******";        public Connection conn = null;      public PreparedStatement PST = NULL;        Public dbhelper (String sql) {          try {              class.forname (name);//            conn = drivermanager.getconnection (URL, user, password);//            PST = conn.preparestatement (SQL),//        } catch (Exception e) {              e.printstacktrace ()}      } Public        void Close () {          try {              this.conn.close ();              This.pst.close ();          } catch (SQLException e) {              e.printstacktrace ();}}  }
This code is very simple, do not need to say more!

This step, we are connected to the database, the connection is successful, you can use the data in the table!

Three. Run.

After a few steps above, we have roughly completed a simple interface development using Servlets, and then it's time to get excited and run!

PS: Before running, you need to add a index.jsp,index.jsp code in WebContent:

<%@ page language= "java" contenttype= "text/html; Charset=iso-8859-1 "    pageencoding=" Iso-8859-1 "%><! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd" >

(1). On the project, right-click->run as->run to Server.


if everything is normal, (If you create a index.jsp, you will see a JSP page; If you do not create a index.jsp, a 404 interface may be displayed)


(2). we enter ' HTTP://LOCALHOST:8080/MSERVER/STUDENTINQ ' in the browser, and if everything is OK, it will show:

or enter the IP address of the computer in the browser, for example ' Http://192.168.1.133:8080/mServer/StudentInq ',


See this interface, psychological suddenly, tears!!

Four. Summary.

Such a long space finally realized the simple interface development, not easy AH! Let's summarize the implementation of the interface development steps:

(1). database table design;

(2). JSON data design;

(3). Interface implementation.

After summing up, is not feeling very simple! From then on, I can develop the interface!

Finally, the example.


Java Web Development (ii) interface development

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.