Java Web development-Servlet and JSP basics-servletjsp

Source: Internet
Author: User

Java Web development-Servlet and JSP basics-servletjsp

I have not engaged in Java Web development for many years. These days are just the National Day holiday. I am also interested in looking back at the basics of Java Web development.

As we all know, Servlet is an important foundation for Java Web development. However, due to the tedious development of Servlet, the large amount of code and the difficulty in maintenance, artists cannot participate in interface design and development, so jsp was born. Jsp is an Important upgrade to the servlet development model. With jsp, Java Web development technology is widely used.

1. Servlet

In Java Web development, you can create a Servlet by creating a class inherited (derived) from the HttpServlet class.

For example:

@WebServlet(name="firstServlet",urlPatterns={"/firstServlet"})public class FirstServlet extends HttpServlet {/** * Constructor of the object. */public FirstServlet() {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 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");PrintWriter out = response.getWriter();out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");out.println("<HTML>");out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");out.println("  <BODY>");out.print("    This is ");out.print(this.getClass());out.println(", using the GET method");out.println("  </BODY>");out.println("</HTML>");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");PrintWriter out = response.getWriter();out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");out.println("<HTML>");out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");out.println("  <BODY>");out.print("    This is ");out.print(this.getClass());out.println(", using the POST method");out.println("  </BODY>");out.println("</HTML>");out.flush();out.close();}/** * Initialization of the servlet. <br> * * @throws ServletException if an error occurs */public void init() throws ServletException {// Put your code here}}
This code is automatically generated when a servlet is created in myeclipse. We can see that the FirstServlet class we created inherits from HttpServlet. In addition, it implements the doGet (method called during Get request), doPost (method called during Post request), init (initialization object), and destroy (destroy object ). It is worth noting that the Annotation method is used for modification, that is, @ WebServlet (name = "firstServlet", urlPatterns = {"/firstServlet "}). This is recommended by servlet3.0. The previous method was to add servlet and servlet-mapping configurations in web. xml. For example:

<Servlet> <servlet-name> firstServlet </servlet-name> <servlet-class> package name. firstServlet </servlet-class> </servlet> <servlet-mapping> <servlet-name> firstServlet </servlet-name> <url-pattern>/firstServlet </url-pattern> </servlet-mapping>

The preceding configuration must be described as follows:

1. Complete servlet class Name (package name. class Name) is required for the servlet-class node in the servlet)

2. The name of the servlet-name node under servlet-mapping must be the same as that of the servlet-name node under servlet.

3. Add "/" to the url under url-pattern "/"

Start tomcat and enter localhost: 8080/project name/firstServet in ie to view the page (Get request ). Port 8080 is the default port number set by tomcat. You can modify the port number in the server. xml file under tomcat/conf. For example, if we modify the default port number to 8088 and restart tomcat (load xml), the Access url is: localhost: 8088/project name/servlet ing urlpattern name.

 <Connector port="8088" protocol="HTTP/1.1" connectionTimeout="20000" redirectPort="8443" />
It should be noted that if we modify the code in the servlet, for example, re-output an html table and re-compile and deploy it to the tomcat web container for running, unlike jsp, jsp is instantly compiled.

The servlet contains a row of output content (out. the println method), so now it is basically not used to develop Java Web projects using pure servlet, but to use it as the mvc c (Controller, Controller.

Ii. jsp

It is precisely because the development of Java Web applications by pure servlet is very complicated and the cooperation between the artist and the programmer is not very good that jsp came into being. By embedding code on pages, tag libraries (such as JSTL and Java standard tag libraries), jsp can directly mix Java code into pages to simplify development. However, the nature of jsp is servlet. We can use a text editor (such as editplus and notepad ++) to open the classes file in the project directory under the tomcat/work directory, in fact, jsp is compiled to generate servlet files (a jsp generates a servlet ). There are also init, destroy, service (this is different from the previous Get, Post, Put, Delete requests) and other methods.

The following describes how to read data from the MySQL database through JDBC and display the data on the page, so that readers can quickly get started with jsp.

Development Environment:

1. MySQL5.7

2. MyEclipse 2014 and JDK7.0

After MySQL is installed, it comes with a MySQL Workbench tool that can be used to create a database.


Click OK. The following page is displayed.


Enter the password to log on to the console.


There is a default world Database, which can be used to perform operations such as Tables, Views, Stored Procedures, and Functions.

Of course, you can also use the command line to operate the database on the MySQL console.


We will use the world Database in MySQL to query the city table and display the data (only the first 10 data records are obtained due to the large data volume ).

Use SQL to query MySQL tools.


After the SQL statement test is passed, we can directly use it on the jsp page.

Complete MyJsp. jsp code:

<% @ Page language = "java" import = "java. util. * "pageEncoding =" UTF-8 "%> <% @ page import =" java. SQL. * "%> <% String path = request. getContextPath (); String basePath = request. getScheme () + ": //" + request. getServerName () + ":" + request. getServerPort () + path + "/"; %> <! Doctype html public "-// W3C // dtd html 4.01 Transitional // EN"> 

We can see that Java code is directly embedded in the jsp page. Since we are using JDBC query MySQL database, so we need to mysql-connector-java-5.1.9.jar this Jar package as the driver, directly put the Web Project under the WEB-INF/lib directory.

The result displayed in the browser is as follows:


As we wish, the first 10 pieces of data are displayed.

In fact, by comparing the above Page code, you will find that this method of page embedding code is very familiar. This method of embedded background code can be used in ASP and ASP. NET development, so the development idea can be applied to each other.

Due to the length of the article, this blog is here first. The next blog focuses on various details in jsp development.



What is the relationship between java web development and jsp?

Jsp is an advanced java application. To learn jsp, You can first understand the basic knowledge of html, and then learn about JDBC (Technology for connecting to databases ), then you can learn how to compile a simple dynamic web page in jsp.

Learning JavaWeb: Learning Servlet first or JSP first?

They're too complicated. Listen to me! Didn't you finish learning the Java basics? You just need to start reading this book. No matter what you talk about first, the book is gradual and easy to understand!

If you don't want to read a book, you can watch the video step by step! Come on!

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.