HTML call servlet (1), html call servlet
1. Data forms on the page
Before using Servlet to process user requests, prepare a page to provide data forms. The data form is the <form>... </form>. When you click the Submit button to Submit a form, some variables (or fields) contained in the form are sent to the server for processing. Compile an HTML file with the following code:
Add.html
<! Doctype html public "-// W3C // dtd html 4.01 Transitional // EN"> 2. Add data
One of the advantages of Servlet is that it can easily obtain data in the form. Add the following code using JDBC technology in Servlet:
AddServlet. java
Package com.cn. add; import java. io. IOException; import java. io. printWriter; import java. SQL. connection; import java. SQL. driverManager; import java. SQL. preparedStatement; import java. SQL. SQLException; import javax. servlet. servletException; import javax. servlet. http. httpServlet; import javax. servlet. http. httpServletRequest; import javax. servlet. http. httpServletResponse; public class addServlet extends HttpServl Et {/*** Constructor of the object. */public addServlet () {super ();}/*** Destruction of the servlet. <br> */public void destroy () {super. destroy (); // Just puts "destroy" string in log // Put your code here}/*** The doGet method of the servlet. <br> ** This method is called when a form has its tag value method equals to get. ** @ param request the request send by the client to the ser Ver * @ param response the response send by the server to the client * @ throws ServletException if an error occurred * @ throws IOException if an error occurred */public void doGet (HttpServletRequest request, httpServletResponse response) throws ServletException, IOException {response. setContentType ("text/html; charset = gb2312"); PrintWriter out = response. getWriter (); this. doPost (request, response); Out. flush (); out. close ();}/*** The doPost method of the servlet. <br> ** This method is called when a form has its tag value method equals to post. ** @ param request the request send by the client to the server * @ param response the response send by the server to the client * @ throws ServletException if an error occurred * @ throws IOException if an error occurred */public void doPost (HttpS ErvletRequest request, HttpServletResponse response) throws ServletException, IOException {System. out. println ("Servlet !!! "); Response. setContentType ("text/html; charset = gb2312"); request. setCharacterEncoding ("gb2312"); PrintWriter out = response. getWriter (); String id = request. getParameter ("id"); // obtain the Department id String name = request. getParameter ("name"); // obtain the Department name String address = request. getParameter ("address"); // get the address of the Department int num = Integer. parseInt (request. getParameter ("num"); // obtain the department count Connection conn = null; // declare a Conne Ction object, used to connect to the database PreparedStatement pstmt = null; // declare the PreparedStatement object, used to insert data entries to the database try {// connect to the Database Class of the bank mode in the MySQL database. forName ("com. mysql. jdbc. driver "); System. out. println ("Driver created successfully! "); // Connect to the database conn = DriverManager. getConnection ("jdbc: mysql: // localhost: 3306/bank", "root", "1234"); System. out. println ("connected to the database! "); // SQL statement for data insertion String SQL =" INSERT INTO dept (id, d_name, address, empnumber) VALUES (?,?,?,?) "; Pstmt = conn. prepareStatement (SQL); // sets the data insertion sequence pstmt. setString (1, id); pstmt. setString (2, name); pstmt. setString (3, address); pstmt. setInt (4, num); int result = pstmt.exe cuteUpdate (); // judge the execution result if (result = 1) {out. print ("data inserted successfully! ");} Else {out. print (" failed to insert data! Please insert it again! ") ;}} Catch (ClassNotFoundException e) {// TODO Auto-generated catch block e. printStackTrace ();} catch (SQLException e) {// TODO Auto-generated catch block e. printStackTrace ();} out. flush (); out. close ();}/*** Initialization of the servlet. <br> ** @ throws ServletException if an error occurs */public void init () throws ServletException {// Put your code here }}
Web. xml
<?xml version="1.0" encoding="UTF-8"?><web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <servlet> <description>This is the description of my J2EE component</description> <display-name>This is the display name of my J2EE component</display-name> <servlet-name>addServlet</servlet-name> <servlet-class>com.cn.add.addServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>addServlet</servlet-name> <url-pattern>/servlet/addServlet</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list></web-app>
The overall file framework is as follows:
3. view a single piece of data
Generally, the id of a data record is unique. You can query a single record by id. The code for the HTML page is as follows:
ShowById.html
<! Doctype html public "-// W3C // dtd html 4.01 Transitional // EN">
Enter the id number on this page. When you click the search button, the queried Servlet is displayed, and the id-based Query operation is processed in the Servlet. The Servlet code for querying by id is as follows:
SearchEmployee. java
Package com.cn. query; import java. io. IOException; import java. io. printWriter; import java. SQL. connection; import java. SQL. driverManager; import java. SQL. preparedStatement; import java. SQL. resultSet; import java. SQL. SQLException; import javax. servlet. servletException; import javax. servlet. http. httpServlet; import javax. servlet. http. httpServletRequest; import javax. servlet. http. httpServletResponse; public class SearchEmployee extends HttpServlet {/*** Destruction of the servlet. <br> */public void destroy () {super. destroy (); // Just puts "destroy" string in log // Put your code here}/*** The doGet method of the servlet. <br> ** This method is called when a form has its tag value method equals to get. ** @ param request the request send by the client to the server * @ param response the response Nd by the server to the client * @ throws ServletException if an error occurred * @ throws IOException if an error occurred */public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {response. setContentType ("text/html; charset = gb2312"); request. setCharacterEncoding ("gb2312"); PrintWriter out = response. getWriter (); String id = request. getPara Meter ("id"); // obtain the Department id Connection conn = null; // declare a Connection object to connect to the database PreparedStatement pstmt = null; ResultSet rs = null; try {Class. forName ("com. mysql. jdbc. driver "); System. out. println ("Driver created successfully! "); // Connect to the database conn = DriverManager. getConnection ("jdbc: mysql: // localhost: 3306/bank", "root", "1234"); System. out. println ("connected to the database! "); String SQL =" SELECT * FROM dept WHERE id =? "; Pstmt = conn. prepareStatement (SQL); pstmt. setString (1, id); rs = pstmt.exe cuteQuery ();} catch (ClassNotFoundException e) {// TODO Auto-generated catch block e. printStackTrace ();} catch (SQLException e) {// TODO Auto-generated catch block e. printStackTrace ();} try {while (rs. next () {out. print ("Department No.:" + rs. getString (1) + "\ n"); out. print ("department name:" + rs. getString (2) + "\ n"); out. print ("Department address:" + rs. getString (3) + "\ n"); out. print ("department count:" + rs. getString (4) + "\ n") ;}} catch (SQLException e) {// TODO Auto-generated catch block e. printStackTrace ();} out. flush (); out. close ();}/*** The doPost method of the servlet. <br> ** This method is called when a form has its tag value method equals to post. ** @ param request the request send by the client to the server * @ param response the response send by the server to the client * @ throws ServletException if an error occurred * @ throws IOException if an error occurred */public void doPost (HttpServletRequest request, httpServletResponse response) throws ServletException, IOException {response. setContentType ("text/html; charset = gb2312"); request. setCharacterEncoding ("gb2312"); PrintWriter out = response. getWriter (); this. doGet (request, response); out. flush (); out. close ();}/*** Initialization of the servlet. <br> ** @ throws ServletException if an error occurs */public void init () throws ServletException {// Put your code here }}
The directory structure is as follows:
4. display all data in a table
The Servlet code for displaying all data information in the table is as follows:
DeptList. java
Package com.cn. query; import java. io. IOException; import java. io. printWriter; import java. SQL. connection; import java. SQL. driverManager; import java. SQL. resultSet; import java. SQL. SQLException; import java. SQL. statement; import javax. servlet. servletException; import javax. servlet. http. httpServlet; import javax. servlet. http. httpServletRequest; import javax. servlet. http. httpServletResponse; public class DeptList extends HttpServlet {/*** The doGet method of the servlet. <br> ** This method is called when a form has its tag value method equals to get. ** @ param request the request send by the client to the server * @ param response the response send by the server to the client * @ throws ServletException if an error occurred * @ throws IOException if an error occurred */public void doGet (HttpServletRequest request, httpServletResponse response) throws ServletException, IOException {response. setContentType ("text/html; charset = gb2312"); request. setCharacterEncoding ("gb2312"); PrintWriter out = response. getWriter (); Connection conn = null; Statement stmt = null; ResultSet rs = null; try {Class. forName ("com. mysql. jdbc. driver "); conn = DriverManager. getConnection ("jdbc: mysql: // localhost: 3306/bank", "root", "1234"); stmt = conn. createStatement (); rs = stmt.exe cuteQuery ("SELECT * FROM dept"); // display all information in the table out on the page. println ("