Java Web Application 用于创建动态网站. Java 通过 Servlets 和 JSPs 支持 Web 应用程序. 我们可以创建具有静态 HTML 页面的网站,但当我们想要信息动态时,我们需要 Web 应用程序。
Java Web 应用程序
本文的目的是提供Web应用程序中的不同组件的基本细节,以及我们如何使用Servlet和JSP来创建我们的第一个JavaWeb应用程序。
网站服务器和客户端
Web 服务器是一个软件,可以处理客户端请求,并将响应发送回客户端,例如,Apache是最广泛使用的 Web 服务器之一。Web 服务器在某些物理机器上运行,并在特定端口上听取客户端请求。Web 客户端是一个软件,有助于与服务器进行通信。一些最广泛使用的 Web 客户端是Firefox、Google Chrome、Safari等。当我们从服务器(通过 URL)请求某些东西时,Web 客户端负责创建请求并将其发送到服务器,然后分析服务器的响应并向用户呈现。
HTML 和 HTTP
网页服务器和网页客户端是两个单独的软件,所以通信应该有一定的共同语言。HTML是服务器和客户端之间的通用语言,代表 HyperText Markup Language。网页服务器和客户端需要一个共同的通讯协议,HTTP(HyperText Transfer Ptocol)是服务器和客户端之间的通讯协议。
- HTTP方法 - 要执行的操作,通常是GET,POST,PUT等
- URL - 访问页面
- Form Parameters - 类似于Java方法中的参数,例如用户,登录页面的密码细节
示例 HTTP 请求:
1GET /FirstServletProject/jsps/hello.jsp HTTP/1.1
2Host: localhost:8080
3Cache-Control: no-cache
HTTP 响应的一些重要部分是:
- 状态代码 - 一个整数,表示请求是否成功或不成功.一些已知的状态代码是200成功,404未找到和403访问禁止
- 内容类型 - 文本,HTML,图像,PDF等也被称为MIME类型
- 内容 - 由客户端渲染并向用户显示的实际数据
示例 HTTP 响应:
1200 OK
2Date: Wed, 07 Aug 2013 19:55:50 GMT
3Server: Apache-Coyote/1.1
4Content-Length: 309
5Content-Type: text/html;charset=US-ASCII
6
7<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "https://www.w3.org/TR/html4/loose.dtd">
8<html>
9<head>
10<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
11<title>Hello</title>
12</head>
13<body>
14<h2>Hi There!</h2>
15<br>
16<h3>Date=Wed Aug 07 12:57:55 PDT 2013
17</h3>
18</body>
19</html>
MIME类型或内容类型:如果您看到上面的样本HTTP响应标题,它包含标签内容类型
。它也被称为MIME类型,服务器将其发送给客户端,让他们知道它正在发送的数据类型。
了解URL
URL是通用资源定位器的缩写,用于定位服务器和资源. 网上的每一个资源都有自己独特的地址. 举个例子看看URL的部分内容. ** https://localhost:8080/FirstServlet Project/jsps/hello.jsp** ** https://** - 这是URL的第一部分,提供用于服务器-客户端通信的通信协议. localhost - 服务器的独特地址,大多数时候是服务器的宿主名来将地图映射到独特的IP地址. 有时多个主机名会指向同一个IP地址,web服务器虚拟主机会注意向特定的服务器实例发送请求. 8080 - 这是服务器正在监听的端口,它是可选的,如果我们不以 URL 提供,那么请求就会去协议的默认端口. 0至1023号口为知名服务的预留口,例如:HTTP有80个,HTTP有443个,FTP有21个等. ** 第一服务项目/jsps/hello.jsp** - 从服务器请求资源。 它可以是静态html,pdf,JSP,服务器,PHP等.
为什么我们需要Servlet和JSP?
网页服务器适合静态内容的HTML页面,但他们不知道如何生成动态内容或如何将数据保存到数据库中,所以我们需要另一个工具,我们可以用来生成动态内容。有几个动态内容的编程语言,如PHP,Python,Ruby on Rails,Java Servlets和JSPs。
Java Web 开发
使用 Servlet 和 JSP 的首个 Web 应用
We will use "Eclipse IDE for Java EE Developers" for creating our first servlet application. Since servlet is a server-side technology, we will need a web container that supports Servlet technology, so we will use the Apache Tomcat server. It's very easy to set up and I am leaving that part to yourself. For ease of development, we can add configure Tomcat with Eclipse, it helps in easy deployment and running applications. Go to Eclipse Preference and select Server Runtime Environments and select the version of your tomcat server, mine is Tomcat 7. Provide the apache tomcat directory location and JRE information to add the runtime environment. Now go to the Servers view and create a new server like below image pointing to the above-added runtime environment.
Note: If Servers tab is not visible, then you can select Window > Show View > Servers so that it will be visible in Eclipse window. Try stopping and starting the server to make sure it's working fine. If you have already started the server from the terminal, then you will have to stop it from the terminal and then start it from Eclipse else it won't work perfectly. Now we are ready with our setup to create the first servlet and run it on tomcat server. Select File > New > Dynamic Web Project and use below image to provide runtime as the server we added in last step and module version as 3.0 to create our servlet using Servlet 3.0 specs.
You can directly click the Finish button to create the project or you can click on Next buttons to check for other options. Now select File > New > Servlet and use below image to create our first servlet. Again we can click finish or we can check other options through the next button.
When we click on the Finish button, it generates our Servlet skeleton code, so we don't need to type in all the different methods and imports in servlet and saves us time. Now we will add some HTML with dynamic data code in doGet() method that will be invoked for HTTP GET request. Our first servlet looks like below.
1package com.journaldev.first;
2
3import java.io.IOException;
4import java.io.PrintWriter;
5import java.util.Date;
6
7import javax.servlet.ServletException;
8import javax.servlet.annotation.WebInitParam;
9import javax.servlet.annotation.WebServlet;
10import javax.servlet.http.HttpServlet;
11import javax.servlet.http.HttpServletRequest;
12import javax.servlet.http.HttpServletResponse;
13
14/**
15 * Servlet implementation class FirstServlet
16 */
17@WebServlet(description = "My First Servlet", urlPatterns = { "/FirstServlet" , "/FirstServlet.do"}, initParams = {@WebInitParam(name="id",value="1"),@WebInitParam(name="name",value="pankaj")})
18public class FirstServlet extends HttpServlet {
19 private static final long serialVersionUID = 1L;
20 public static final String HTML_START="<html><body>";
21 public static final String HTML_END="</body></html>";
22
23 /**
24 * @see HttpServlet#HttpServlet()
25 */
26 public FirstServlet() {
27 super();
28 // TODO Auto-generated constructor stub
29 }
30
31 /**
32 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
33 */
34 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
35 PrintWriter out = response.getWriter();
36 Date date = new Date();
37 out.println(HTML_START + "<h2>Hi There!</h2><br/><h3>Date="+date +"</h3>"+HTML_END);
38 }
39
40 /**
41 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
42 */
43 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
44 // TODO Auto-generated method stub
45 }
46
47}
Before Servlet 3, we need to provide the url pattern information in web application deployment descriptor but servlet 3.0 uses java annotations that is easy to understand and chances of errors are less. Now chose Run > Run on Server option from servlet editor window and use below images for the options.
After clicking finish, the browser will open in Eclipse and we get following HTML page.
You can refresh it to check that Date is dynamic and keeps on changing, you can open it outside of Eclipse also in any other browser. So servlet is used to generate HTML and send it in response, if you will look into the doGet() implementation, we are actually creating an HTML document as writing it in response PrintWriter object and we are adding dynamic information where we need it. It's good for a start but if the response is huge with a lot of dynamic data, it's error-prone and hard to read and maintain. This is the primary reason for the introduction of JSPs. JSP is also server-side technology and it's like HTML with additional features to add dynamic content where we need it. JSPs are good for presentation because it's easy to write because it's like HTML. Here is our first JSP program that does the same thing as the above servlet.
1<%@page import="java.util.Date"%>
2<%@ page language="java" contentType="text/html; charset=US-ASCII"
3 pageEncoding="US-ASCII"%>
4<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "https://www.w3.org/TR/html4/loose.dtd">
5<html>
6<head>
7<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
8<title>Hello</title>
9</head>
10<body>
11<h2>Hi There!</h2>
12<br>
13<h3>Date=<%= new Date() %>
14</h3>
15</body>
16</html>
If we run above JSP, we get output like below image. The final project hierarchy looks like below image in Eclipse.
下载FirstServlet项目
(下载《Hello World Example Project》)
我们将在未来的帖子中更详细地研究Servlets和JSP,但在结束这篇文章之前,我们应该对JavaWeb应用程序的一些方面有很好的了解。
网站集装箱
Tomcat 是一个 Web 容器,当一个请求从客户端到 Web 服务器时,它将请求传递给 Web 容器,它是 Web 容器的工作,以找到正确的资源来处理请求(Servlet 或 JSP),然后使用资源的响应来生成响应,并将其提供给 Web 服务器。然后,Web 服务器将响应发送回客户端。当 Web 容器收到请求时,如果是服务器,则容器会创建两个 Objects HTTPServletRequest 和 HTTPServletResponse。然后它会找到基于 URL 的正确的服务器,并为请求创建一个线索。然后它会召唤服务器() 方法,并基于 HTTP 方法服务() 调用 doGet() 或 doPost() 方法
- ** 通信支助** -- -- 集装箱为网络服务器与服务器和联合战略计划之间的通信提供了方便的途径。 因为容器,我们不需要建立服务器套接字来收听网络服务器的任何请求,解析请求并生成响应. 所有这些重要而复杂的任务都是由集装箱完成的,我们只需要专注于我们的应用业务逻辑。 () ( )* ** 生命周期和资源管理** -- -- 集装箱负责管理服务器的生命周期。 容器要注意将伺服器装入内存,初始化伺服器,起用伺服器方法并销毁. 该容器还提供JNDI等功能,用于资源汇集和管理。 ( ( )* 多线程支持 - 容器为每一个向服务器提出的请求创建了新线程,当处理后线程会死. 因此,服务器不会为每个请求初始化并节省时间和内存. () ( )* JSP Support - JSP看起来不像普通的java课程,网络容器为JSP提供支持. 应用程序中的每个JSP都由容器编译并被转换为Servlet,然后容器像其他服务器一样管理它们. ( ( )* ** 杂项 任务** - Web容器管理资源池,进行内存优化,运行垃圾收集器,提供安全配置,支持多个应用程序,热部署等多个场景后任务,使我们的生活更加轻松. ( (英语)
网站应用程序目录结构
Java Web Applications are packaged as Web Archive (WAR) and it has a defined structure. You can export above dynamic web project as WAR file and unzip it to check the hierarchy. It will be something like below image.
部署描述
web.xml 文件是 Web 应用程序的部署描述器,包含服务器(之前为 3.0),欢迎页面,安全配置,会话时间设置等的映射,这就是 Java Web 应用程序启动教程,我们将在未来的帖子中更多地探索服务器和 JSP。 更新:本系列的下一个教程是 [Java Servlets 教程](/社区/教程/servlet-jsp-教程Java Servlet 教程与初学者的例子
)