Java + MyEclipse + Tomcat (2) Configure Servlet and simple form submission, myeclipseservlet

Source: Internet
Author: User

Java + MyEclipse + Tomcat (2) Configure Servlet and simple form submission, myeclipseservlet

Servlet is the foundation in Java EE application programming, JSP is based on Servlet, and other Web frameworks such as Struts, WebWork, and Spring MVC are Servlet-based. This article describes how to configure Servlet in MyEclipse and Tomcat and how to simply implement the form submission function.
For help, refer to the Java EE enterprise-level application development instance tutorial.
Java + MyEclipse + Tomcat (1) configuration process and introduction to jsp website development

1. Servlet Programming

1. Basic Web Knowledge
Before talking about Servlet, you should first understand the basic Web knowledge. The World Wide Web (World Wide Web) is a collection of all documents on the Internet. The main types of Web documents are HTML Web pages, CSS, JavaScript, dynamic Web pages, images, sounds, and videos.
The Web documents are stored on the Web Site, and the Web Site resides on the Web server. A Web Server is a software system that provides Web document management and request services. Common Web server software includes Apache, IIS, WebLogic, and Tomcat. Each server has a unique IP address, and the Web server has a service port. The default value is port 80 or port 8080.
All Web documents have a unique address, which is located in the URL format:
Protocol: // ip address: Port/site name/directory/file name
The protocols include HTTP, HTTPS, and FTP. The default port can be omitted based on different protocols. HTTP/HTTPS is port 80, and FTP is port 21. Example:
Http: // 210.30.108.30: 8080/test/admin/login. jsp
After the Web server receives the request, it locates the corresponding document based on the URL and processes the document according to the document type. The document is sent to the client over the network, usually in a browser, users can view or download the requested documents. The Web works in Request/Response mode, that is, the browser uses a URL to Request Web documents, and the Web server receives and processes requests, after processing, the response content is sent to the browser.
Web request methods include GET, POST, PUT, DELETE, and HEAD. The GET request directly returns the request documentation and transmits parameters in the URL. the post request saves the data transmitted to the Web server to the data stream, which can only be implemented through form submission. As follows:

Get requests: http: // localhost: 8080/web01/main. do? Id = 1 & password = 123456POST request: <form action = "add. do "method =" post "> <input type =" text "name =" username "> <input type =" submit "value =" submit "> </form>

You should be familiar with this knowledge, so I will not introduce it any more. The Servlet will be described as soon as a form is introduced.

2. What is Servlet?
At the early stage of Sun's formulation of Java EE specifications, Servlet was introduced to implement dynamic Web, which is used to replace the bulky CGI (General Gateway Interface) and implement the dynamic Web Technology for Java programming, it laid the foundation for Java EE. Later, to further simplify the generation of dynamic Web pages and compete with Microsoft's ASP (Active X service system page) technology, Sun introduced the JSP specification, web page programming is further simplified. However, JSP is not as convenient and standardized as Servlet in HTTP request processing. Servlet is firmly occupied in today's MVC Web development. Currently, popular Web frameworks are basically based on Servlet technologies, such as Struts, WebWork, and Spring MVC. Only by mastering Servlet can we truly grasp the core and essence of Java Web programming.
So what exactly is Servlet?
Servlet is a class that runs in a Web container. It can process HTTP requests of Web customers and generate HTTP responses.
Servlet is a Web component defined in Java EE specifications and runs in Web containers. The Web container is responsible for managing the Servlet declaration cycle, including creating and destroying Servlet objects. You cannot directly create Servlet objects or call Servlet methods. You can call Servlet methods by sending HTTP requests to the Web server. This is an important difference between Servlet and common Java classes.
Sun provides all Servlet interfaces and classes in the following two packages:
1. javax. servlet contains common Web component interfaces and classes that support all protocols
2. javax. servlet. http contains interfaces and classes that support the HTTP protocol.
Servlet can complete all functions of Web components, as follows:
1. Receive HTTP requests
2. GET request information, including request header and request parameter data
3. Call other Java methods to complete specific business functions
4. Generate HTTP response, including HTML and non-HTML response
5. Redirect to other Web components, including redirection and forwarding
Two servlets and Java I/O packages need to be introduced:

import java.io.*;import javax.servlet.*;import javax.servlet.http.*;
The Servlet that receives the HTTP request and responds to the HTTP request must inherit javax. servlet. http. HttpServlet. The Servlet class is defined as follows:
Public class LoginAction extends HttpServlet {}
Every Servlet generally needs to override the doGet and doPost methods. When a user uses the GET method to request a Servlet, the Web Container calls the doGet method to process the request. When the user uses the POST method to request a Servlet, the Web Container uses the doPost method.

The Servlet is shown in the lifecycle sequence diagram, including the loading class and instantiation stage, initialization stage, request processing stage, and destruction stage.

Ii. Configure Servlet

As a Web component, Servlet can process HTTP requests and responses. Therefore, it requires a unique URL address. However, because the Servlet is a Java file, the URL request access address can be obtained without being directly stored in the Web directory like JSP. Servlet must be configured and mapped in the Web configuration file/WEB-INF/web. xml to respond to HTTP requests.
1. Servlet Declaration
Its task is to notify the Web Container Servlet to exist. The declaration syntax is as follows:

  <servlet>  <servlet-name>HomePageAction</servlet-name>  <servlet-class>servlet.HomePageAction</servlet-class>  </servlet>

<Servlet-name> declares the Servlet name, which is generally the same as the Servlet class name. It must be unique in a web. xml file. <Servlet-class> specify the full name of the Servlet, that is, the package name. type. The Web container loads the class file to the content according to this definition, and then calls the default constructor to create the Servlet object.
Servlet initial parameters, such as the database Driver, URL, account, and password, can be read in the Servlet. The following defines an initial parameter, that is, the JDBC Driver of the database.

  <servlet>  <servlet-name>HomePageAction</servlet-name>  <servlet-class>servlet.HomePageAction</servlet-class>  <init-param><param-name>driveName</param-name> <param-value>sun.jdbc.odbc.JdbcOdbcDriver</param-value>  </init-param>  </servlet>

In Servlet, you can get the defined initialization parameters through ServletConfig. The code for obtaining the above defined parameters is as follows:

Private Connection cn = null; // define the database Connection object private String driverName = null; // database drive // obtain the initial parameter driverName = config defined by Servlet. getInitParameter ("driverName"); // connect to the database Class according to the initial Servlet parameters. forName (driverName); cn = DriverManager. getConnection ("jdbc: odbc: cityoa ");
Config is the attribute variable of the ServletConfig type defined in Servlet, and its instance is obtained by the init method. You can directly modify the configuration file to connect to different databases without modifying or re-compiling the code.

2. Servlet ing
Any Web document requires a URL address on the Internet to be accessed by the request. The Servlet cannot be directly stored in the Web Publishing directory like JSP. Therefore, the Servlet needs to map the URL address separately. Perform Servlet URL ing in WEB-INF/web. xml.

  <servlet-mapping>  <servlet-name>HomePageAction</servlet-name>  <url-pattern>/loginAction.do</url-pattern>  </servlet-mapping>
The above code is absolute address ing and can only be mapped to one address. The Servlet-name must be consistent with the Servlet declaration. The URL format is as follows:/directory/file name. extension. The method for matching directory mode ing is as follows. You can request multiple URLs.
  <servlet-mapping>  <servlet-name>MainAction</servlet-name>  <url-pattern>/main/*</url-pattern>  </servlet-mapping>
Any URL starting with/main can request this Servlet. As follows:
Http: // localhost: 8080/web01/main/login. jsp
Http: // localhost: 8080/web01/main/info/add. do
You can also use the matching extension ing mode or respond to requests with multiple addresses.
  <servlet-mapping>  <servlet-name>MainAction</servlet-name>  <url-pattern>*.action</url-pattern>  </servlet-mapping>
Any request with the extension of action in the preceding configuration can be responded by the Servlet. For example:
Http: // localhost: 8080/web01/login. action
Http: // localhost: 8080/web01/main/info/add. action
Note: you cannot mix two matching modes. Otherwise, an error occurs in ing, such as/main/*. action.

Iii. Simple Form submission

Create a Web Project named TestServlet. Shows the project structure:


Create an imagesfolder under the webrootfolder and upload the image logo.jpg. Create a new style.css file with the following code:
.main {width: 1024px;text-align:left;}.font {font-family: "Trebuchet MS";font-size: 14px;font-weight: bold;color: #FFFFFF;}.div {margin: 0px;padding: 0px;width: 1014px;}.tdBgColor{background-color:#6b1101;}a{font-family: "Trebuchet MS";font-size: 14px;font-weight: bold;color: #FFFFFF;line-height:50px;text-decoration:none;}a.hover{font-family: "Trebuchet MS";font-size:14px;font-weight: bold;color:#0000FF;line-height:50px;text-decoration:underline;padding-bottom:1px;}a.visited{font-family: "Trebuchet MS";font-size:14px;font-weight: bold;color:#000066;line-height:50px;text-decoration:none;}a.active{font-family: "Trebuchet MS";font-size:14px;font-weight: bold;color:#0000FF;line-height:50px;text-decoration:none;padding-bottom:1px;}
Modify the index. jsp homepage with the following code:
<% @ Page language = "java" import = "java. util. * "pageEncoding =" UTF-8 "%> <% String path = request. getContextPath (); String basePath = request. getScheme () + ": //" + request. getServerName () + ":" + request. getServerPort () + path + "/"; %> <! Doctype html public "-// W3C // dtd html 4.01 Transitional // EN"> Run the Web site and click Run As = MyEclipse Server Application. :



In this case, enter the user name and password for logon, as shown in:

Create a folder Servlet in src and create the HomePageAction. java file. The Code is as follows:
Package servlet; import java. io. IOException; import java. SQL. *; // import the database to process all the databases import javax. servlet. servletConfig; import javax. servlet. servletException; import javax. servlet. http. httpServlet; import javax. servlet. http. httpServletRequest; import javax. servlet. http. httpServletResponse; import javax. swing. JOptionPane; // user logon process Servlet system logon homepage Processing Form public class HomePageAction extends HttpServlet {private Connection Cn = null; // define the database connection object private String driverName = null; // database drive private String url = null; // database Address URL // initialization method, get the database connection object public void init (ServletConfig config) throws ServletException {super. init (config); driverName = config. getInitParameter ("driverName"); url = config. getInitParameter ("url"); try {Class. forName (driverName); cn = DriverManager. getConnection (url);} catch (Exception e) {System. out. println ("database connection error:" + e. GetMessage () ;}}// public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// obtain the data submitted by the user registry ticket String userid = request. getParameter ("userid"); String password = request. getParameter ("password"); // if the Logon account is null, the registration page is automatically displayed if (userid = null | userid. trim (). length () = 0) {response. sendRedirect ("index. jsp "); JOptionPane. showMessageDialog (null, "User name or Password can't be empty! ");} // Determines whether the logon password is null. if (password = null | password. trim (). length () = 0) {response. sendRedirect ("index. jsp "); JOptionPane. showMessageDialog (null, "User name or password can't be empty! ");} // Query the database and jump to the logon main interface try {// query the database operation // jump to the main interface response. sendRedirect ("success. jsp ");} catch (Exception e) {System. out. println ("error:" + e. getMessage (); response. sendRedirect ("index. jsp ") ;}}// method for processing POST requests public void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {doGet (request, response );} // destroy method public void destroy () {super. destroy (); try {cn. close ();} catch (Exception e) {System. out. println ("database disconnection error:" + e. getMessage ());}}}
Configure the Servlet in the WEB-INF folder web. xml file as follows:
<? Xml version = "1.0" encoding = "UTF-8"?> <Web-app version = "3.0" 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_3_0.xsd"> <display-name> </display-name> <welcome-file-list> <welcome-file> index. jsp </welcome-file> </welcome-file-list> <! -- Configure Servlet --> <servlet-name> HomePageAction </servlet-name> <servlet-class> servlet. homePageAction </servlet-class> <init-param> <param-name> driveName </param-name> <param-value> sun. jdbc. odbc. jdbc0dbcDriver </param-value> </init-param> <param-name> url </param-name> <param-value> jdbc: odbc: cityoa </param-value> </init-param> </servlet> <servlet-mapping> <servlet-name> HomePageAction </servlet-name> <url-pattern>/ loginAction. do </url-pattern> </servlet-mapping> </web-app>
Create a new success. java file and go to the displayed page.
<% @ Page language = "java" import = "java. util. * "pageEncoding =" UTF-8 "%> <% String path = request. getContextPath (); String basePath = request. getScheme () + ": //" + request. getServerName () + ":" + request. getServerPort () + path + "/"; %> <! Doctype html public "-// W3C // dtd html 4.01 Transitional // EN"> Shows the display effect:



In this case, the Servlet configuration is successful, and the form jump function is also implemented. You may encounter the following error:

The solution is as follows:
Finally, I hope this article will be helpful to you. The next article will introduce a classic website model of the JSP website and related knowledge about MyEclipse database configuration. If there are deficiencies or errors in the article, please try again!
(By: Eastmount http://blog.csdn.net/eastmount)

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.