Simple Servlet Program For Database Connection PoolingA Simple Servlet Example – (write, deploy, run) By mkyong | December. deploy and run a simple servlet in web container. \Program Files\Java\j2ee\lib\javaee. Servlets Database Access. Learning Java Servlets in simple and easy steps using this. Here is an example which shows how to access TEST database using Servlet. A Simple Servlet Example – (write, deploy, run)By mkyong | December 1, 2. Updated : August 3. Viewed : 1. 79,4. Talking about the web technology, Java developers will keep talking about how powerful the Spring , Struts, Wicket, JSF…. When talking about the deployment, they will say using Ant script or Maven to build or deploy. Ironically, without the IDE or technology help, many Java developers do not know either how to create a simple servlet and deploy it , nor about writing the deployment descriptor.
The products database used in this example is very simple. /* The main servlet class makes the database connection. // The database connection is created in. 13.2 A Simple Servlet with GlassFish, Connector/J and MySQL. This section describes a simple servlet that can be. the connection with the database is as. Connect to MYSQL with servlet. Posted by: Mads Kristensen (). I want to connect my servlet to a MYSQL database. Connection con = DriverManager.getConnection. With simple configurations we can create a Database Connection Pool that is maintained by the Container itself. Most of the servlet containers such as Tomcat and JBoss. This is a simple JSP program to connect to MSSQL database. This is a simple JSP program to connect to. connection with mysql in servlet file.so i have. Nowadays , too many Java developers tight coupling with latest technology, do they know loose coupling is a good design for scalability : )? All the lasted technology is come from “Servlet” as foundation, you can not go far without it. Here’s a quick guide to write, deploy and run a simple servlet in web container, without any IDE help. Build the directory folder as following. Create a Java file named “Servlet. Demo. 1. java”, put in the “projectname/src/com/mkyong/” folder. IOException. import java. Print. Writer. import javax. Http. Servlet. import javax. Http. Servlet. Request. Http. Servlet. Response. Servlet. Demo. 1 extends Http. Servlet{. public void do. Ge(Http. Servlet. Request request, Http. Servlet. Response response). IOException{. Print. Writer out = response. Writer(). out. println("< html> "). Hello Servlet Get< /h. Create a deployment descriptor named web. UTF- 8"?>. < web- app version="2. XMLSchema- instance". Location="http: //java. Servlet Name For Demo. Servlet. Demo. 1< /servlet- class>. Servlet Name For Demo. Demo. 1< /url- pattern>. P. S servlet- name is the alias name for the Servlet. Demo. 1 class. P. S url- pattern is the url path you type in browser address bar. From the project directory “projectname”, compile it with following command. Servlet. Demo. 1. C: \Program Files\Java\j. The “javaee. jar” is required for http servlet , this library is packed with J2. EE SDK. In addition, all compiled classes will put in “classes” folder automatically. Build the directory folder in Tomcat. WEB- INF (Do not change this folder name). Copy all required files to Tomcat\WEB- INF folder– “Servlet. Demo. 1. java” to “Tomcat\WEN- INF\classes\com\mkyong”– “web. Tomcat\WEN- INF\”. WEB- INF. \- -web. New file]. \- -classes. Servlet. Demo. 1. New file]. 7) Start Tomcat. Done ~ Launch your browser and type “http: //localhost: 8. Demo. 1”P. S Once the the servlet class is updated, Tomcat have to restart to take effect. Java Servlets and Access Databases. Java Servlets, Access Databases, and. Stand Alone Server. Stand Alone Server. A free stand alone server can be downloaded from the Apache open software. It is Tomcat 4. 0. Directions for installation can be found at http: //archive. Using- Tomcat. html. Make sure that you download the regular version, not the LE version. The latter requires an XML parser and doesnt work without it. The directions at coreservlets also tell you which directories to use. Java servlets. The html files should be placed. ROOT subfolder of the Apache folder. The servlets. ROOT/WEB- INF/classes folder. If. Access Databases. Microsoft Access is a widely used personal computer database. In it, you can create linked tables that consist of rows and columns. The columns have field names such as Product. Name and Quantity. The. Note that there should not. The products database used in this example is very simple. It. Product. Table, which is shown below. The. Product. Id, Product. Name, Price, and Quantity. There. However, it is enough to demonstrate. To connect to the database using a Java servlet, you must first register. In Windows 9. 8 this is done. Settings/Control Panel/Data Sources (ODBC). In Windows. XP, you will find this same file in Settings/Control Panel/Administrative. Tools. Select Add/Microsoft Access Driver (*. Browse to find the location of your database. The connection is done with a jdbc- odbc bridge. Jdbc stands for. Java database connectivity API (application programmer interface), while. O in Odbc stands for Open. Odbc is a protocol from Microsoft. X/Open SQL specification. In a Java servlet. Connection object. The lines of code required are. Class. for. Name ("sun. Jdbc. Odbc. Driver"). Connection con = Driver. Manager. get. Connection ("jdbc: odbc: products"). The Connection and Driver. Manager objects are contained in the sql package. SQL stands for Structured Query Language. SQL is the standard way. It is not case sensitive, so you can. Some. examples are Select, Insert, Delete, and Update. You can also modify. Where or Set. An example. Select * From Product. Table Where Product. Id. This says to select all (*) the records from the Product. Table that. have the given Product. Id. Another example is. Update Product. Table Set Quantity = 'new. Quantity'. Where Product. Id = 'order. Id'. This statement updates the Quantity field in the record in Product. Table. that has order. Id as its Product. Id. HTML Forms. The interface to a servlet is an html (hypertext markup language) form. A simple example is. Order Form< /title> < /head>. Enter the id. of the product and the quantity desired.< /h. Make. Order. DB/" >. Id. < br> < input name="quantity" type="text" value="" size = 1. Quantity. < p> < input type="submit">. The form has a head and a body, both enclosed by appropriate tags. The head for this example only contains the title. The title should be. In the form, all. This begins with some information for. This tells the client what to do with the form. Here it explains that product information should be entered into the text. These are defined between the form tags. The method. If you are using servlets the "post" method. The action value is more complicated. It has to tell the form. In this. case, the servlet is on the same computer as the html form, so it is accessed. The remainder of the action string says. Make. Order. DB. The classes for this servlet. Make. Order. DB. It is accessed from your browser using http: //localhost/Make. Order. DB. html. The remainder of the form is filled by three input tags, the first two. Submit button. The form. Both input tags contain name fields. These names are used by the. The URL string. that is created when the Submit button is clicked looks like the following. Make. Order. DB/? HX4. 56. V& quantity=3. This string begins with the address found in the action string. It then is followed by the values submitted for the id and quantity separated. The names of the text fields are listed in order. These become parameters for the servlet. In general, the URL string is coded with all spaces replaced by the. Letters. and digits are not changed, but a number of other characters are replaced. For example, the at sign (@) is replaced by %4. Java Servlets. Java servlets are used to process the parameters sent by the form. The servlet that processes the form above first looks in the database to. If this is found, it then checks. If so, it uses the price stored with the product. In this case the servlet will send back. It also updates the quantity. If the quantity is larger than the amount in stock a different message. We are sorry, but that item is out of stock. An actual e- commerce web site would certainly have a much more elaborate. The main class of a servlet extends the Http. Servlet class. This. SUN. To make things easier for you, it can also be found in. Documents directory of the website found at http: //csis. You can download it from there and store it with the other . You also have to tell the IDE you use to look there for this file. In JCreator, first click on Configure, then on Options , and then on Profiles. You should see the version of JDK that you are using listed there. Click on it and then on Edit. When you see the next window, click. Add and then Add Package Browse until you find the lib subdirectory. This will tell the compiler where. Http. Servlet classes needed to compile a servlet. The Http. Servlet classes are a part of javax, extended java. So. Like any import statements, these go at the beginning of the file. You need further import statements as well, such as import java. Servlets look much like applets at the beginning. A servlet class. Http. Servlet where an applet class extends Applet. An example. Make. Order. DB extends Http. Servlet. The principle methods in a servlet class are do. Get and do. Post. They both have the same parameters, Http. Servlet. Request and Http. Servlet. Response. The do. Get will usually look like the method below. Get (Http. Servlet. Request request. Http. Servlet. Response response). Number. Format. Exception nfexp). Number format exception"); }. IOException ioexp) {out. IO exception"); }. Get. Catching the IOException is required. The Number. Format. Exception. All parameters are sent to the servlet as Strings. Servlets can instantiate other classes and use their public methods. They can read and write to files, query databases, store data in arrays. But displaying results requires the servlet. This is the. response. Typically the servlet gets an instance of the Print. Writer. class, often called out. Print. Writer out = response. Writer (). Strings are written to out using println, just like with System. For example. out. The total bill is " +. Notice the html tags inside the string, < h. All tags and other data that are to be displayed by the clients browser. As usual, make sure that the quotation. Sample Java Servlet. The following Java servlet can be used with the stand alone server and. This is an example of a Java servlet that connects with an Access. It is called by a web page with a form. ID and the quantity to be purchased. The ID is sent to the database, which then returns the record with the. ID. The quantity on hand is then checked against the quantity. If there is enough of the product in the database, the order. The bill is then displayed for the client. If. Out of Stock message is sent back. The main servlet class makes the database connection, gets the order. Make. Order extends Http. Servlet. private Connection con. Print. Writer out. The database connection is created in the. Name is a static method that forces the use of the jdbc- odbc bridge.. Class. for. Name ("sun. Jdbc. Odbc. Driver"). Driver. Manager. get. Connection ("jdbc: odbc: products"). SQLException ex) {out. SQL Exception.< /h. Class. Not. Found. Exception. cex) {out. Class Not Found Exception.< /h. The do. Get method is used to get the order. Get (Http. Servlet. Request request. Http. Servlet. Response response). Writer (). Order order = new Order (con, out). Data. From. Client (request). Order (). } catch (IOException. IO Exception.< /h. Servlet. Exception. Servlet Exception.< /h. Exception. e){out. Database connection exception.< /h. Database connection exception.< /h. The servlet will send an html response page to. This method creates the header for that page. Header (String title). DOCTYPE HTML PUBLIC '- //W3. C//DTD HTML 4. 0 Transitional//EN'> "). HTML> "). ("< head> "). Header. // The end of the html page consists only of. Foot () {out. println ("< /body> < /html> "). Make. Order. /* The Product class is used to store and process all information about. It has instance fields for all the fields in a. There are methods to get and display a product. String product. Name. String get. Product. Name. () {return product. Name; }. protected double get. Price. () {return price; }. Quantity. () {return quantity; }. The Order class sends. The database then responds with a Result. Set. The method, get. Product, extracts the individual fields from one record. Product (Result. Set. Print. Writer out). Id = rs. get. String ("Product. Id"). product. Name = rs. String ("Product. Name"). price = rs. Double ("Price"). Int ("Quantity"). Exception ex){out. Connection Error.< /h. Product. // This method creates. Product. (Print. Writer out). Product Name: " + product. Name ). out. println ("< br> Product Id: " + product. Id). out. println ("< br> Product Price: " + price ). Product Quantity: " + quantity + "< /h. Product. }// class Product. The Order class processes the data sent in by the client. It. The query is then submitted. The Result. Set is then used to get and display the. If there is sufficient quantity, the order is processed. This is then returned to the client. Connection con. private Print. Writer out. private Product product. String order. Id. Ordered, quanitity. In. Stock. Order (Connection con, Print. Writer out). this. The servlet request is used to get the data. Data. From. Client (Http.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. Archives
September 2016
Categories |