java web初级面试题
Java Web Application is used to create dynamic websites. Java provides support for web application through Servlets and JSPs. We can create a website with static HTML pages but when we want information to be dynamic, we need web application.
Java Web Application用于创建动态网站。 Java通过Servlet和JSP为Web应用程序提供支持。 我们可以使用静态HTML页面创建一个网站,但是当我们希望信息是动态的时,我们需要Web应用程序。
The aim of this article is to provide basic details of different components in Web Application and how can we use Servlet and JSP to create our first java web application.
本文的目的是提供Web应用程序中不同组件的基本细节,以及如何使用Servlet和JSP创建我们的第一个Java Web应用程序。
Web Server is a software that can process the client request and send the response back to the client. For example, Apache is one of the most widely used web servers. Web Server runs on some physical machine and listens to client request on a specific port.
Web服务器是一种可以处理客户端请求并将响应发送回客户端的软件。 例如,Apache是使用最广泛的Web服务器之一。 Web Server在某些物理计算机上运行,并在特定端口上侦听客户端请求。
A web client is a software that helps in communicating with the server. Some of the most widely used web clients are Firefox, Google Chrome, Safari, etc. When we request something from the server (through URL), the web client takes care of creating a request and sending it to the server and then parsing the server response and present it to the user.
Web客户端是一种有助于与服务器通信的软件。 一些使用最广泛的Web客户端是Firefox,Google Chrome,Safari等。当我们从服务器(通过URL)请求某些内容时,Web客户端会负责创建请求并将其发送到服务器,然后解析服务器响应并将其呈现给用户。
Web Server and Web Client are two separate softwares, so there should be some common language for communication. HTML is the common language between server and client and stands for HyperText Markup Language.
Web服务器和Web客户端是两个单独的软件,因此应该使用某种通用语言进行通信。 HTML是服务器和客户机之间的共同的语言和代表H yper T外部中号 arkup 大号 anguage。
Web server and client needs a common communication protocol, HTTP (HyperText Transfer Protocol) is the communication protocol between server and client. HTTP runs on top of TCP/IP communication protocol.
Web服务器和客户端都需要一个公共通信协议,HTTP(H yper T外部贸易交接P rotocol)是通信服务器和客户机之间的协议。 HTTP在TCP / IP通信协议之上运行。
Some of the important parts of the HTTP Request are:
HTTP请求的一些重要部分是:
Sample HTTP Request:
样本HTTP请求:
GET /FirstServletProject/jsps/hello.jsp HTTP/1.1
Host: localhost:8080
Cache-Control: no-cache
Some of the important parts of HTTP Response are:
HTTP响应的一些重要部分是:
Sample HTTP Response:
示例HTTP响应:
200 OK
Date: Wed, 07 Aug 2013 19:55:50 GMT
Server: Apache-Coyote/1.1
Content-Length: 309
Content-Type: text/html;charset=US-ASCII
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "https://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Hello</title>
</head>
<body>
<h2>Hi There!</h2>
<br>
<h3>Date=Wed Aug 07 12:57:55 PDT 2013
</h3>
</body>
</html>
MIME Type or Content Type: If you see above sample HTTP response header, it contains tag “Content-Type”. It’s also called MIME type and server sends it to the client to let them know the kind of data it’s sending. It helps the client in rendering the data for the user. Some of the most used mime types are text/html, text/xml, application/xml etc.
MIME类型或内容类型 :如果您在上面的示例HTTP响应标头中看到,它包含标记“ Content-Type”。 这也称为MIME类型,服务器将其发送给客户端,以让他们知道其发送的数据的类型。 它有助于客户端为用户呈现数据。 一些最常用的mime类型是text / html,text / xml,application / xml等。
URL is the acronym of Universal Resource Locator and it’s used to locate the server and resource. Every resource on the web has its own unique address. Let’s see parts of the URL with an example.
URL是Universal Resource Locator的首字母缩写,用于查找服务器和资源。 网络上的每个资源都有其自己的唯一地址。 让我们看一个示例中的URL部分。
https://localhost:8080/FirstServletProject/jsps/hello.jsp
https:// localhost:8080 / FirstServletProject / jsps / hello.jsp
https:// – This is the first part of URL and provides the communication protocol to be used in server-client communication.
https:// –这是URL的第一部分,提供了服务器-客户端通信中使用的通信协议。
localhost – The unique address of the server, most of the times it’s the hostname of the server that maps to unique IP address. Sometimes multiple hostnames point to same IP addresses and web server virtual host takes care of sending a request to the particular server instance.
本地主机 –服务器的唯一地址,大多数情况下,它是映射到唯一IP地址的服务器的主机名。 有时,多个主机名指向相同的IP地址,并且Web服务器虚拟主机负责将请求发送到特定服务器实例。
8080 – This is the port on which server is listening, it’s optional and if we don’t provide it in URL then request goes to the default port of the protocol. Port numbers 0 to 1023 are reserved ports for well-known services, for example, 80 for HTTP, 443 for HTTPS, 21 for FTP, etc.
8080 –这是服务器正在侦听的端口,它是可选的,如果我们未在URL中提供它,则请求将转到协议的默认端口。 端口号0到1023是众所周知的服务的保留端口,例如,HTTP为80,HTTPS为443,FTP为21等。
FirstServletProject/jsps/hello.jsp – Resource requested from server. It can be static html, pdf, JSP, servlets, PHP etc.
FirstServletProject / jsps / hello.jsp –服务器请求的资源。 它可以是静态html,pdf,JSP,servlet,PHP等。
Web servers are good for static contents HTML pages but they don’t know how to generate dynamic content or how to save data into databases, so we need another tool that we can use to generate dynamic content. There are several programming languages for dynamic content like PHP, Python, Ruby on Rails, Java Servlets and JSPs.
Web服务器适用于静态内容HTML页面,但是它们不知道如何生成动态内容或如何将数据保存到数据库中,因此我们需要另一个可用于生成动态内容的工具。 有几种用于动态内容的编程语言,例如PHP,Python,Ruby on Rails,Java Servlet和JSP。
Java Servlet and JSPs are server-side technologies to extend the capability of web servers by providing support for dynamic response and data persistence.
Java 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.
我们将使用“ Java EE开发人员的Eclipse IDE”来创建我们的第一个servlet应用程序。 由于Servlet是一种服务器端技术,因此我们需要一个支持Servlet技术的Web容器,因此我们将使用Apache Tomcat服务器。 设置非常容易,我将这部分留给自己。
For ease of development, we can add configure Tomcat with Eclipse, it helps in easy deployment and running applications.
为了便于开发,我们可以添加带有Eclipse的配置Tomcat,它有助于轻松部署和运行应用程序。
Go to Eclipse Preference and select Server Runtime Environments and select the version of your tomcat server, mine is Tomcat 7.
转到Eclipse Preference,然后选择Server Runtime Environments,然后选择您的tomcat服务器的版本,我的是Tomcat 7。
Provide the apache tomcat directory location and JRE information to add the runtime environment.
提供apache tomcat目录位置和JRE信息以添加运行时环境。
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.
注意 :如果“服务器”选项卡不可见,则可以选择“窗口”>“显示视图”>“服务器”,以便在Eclipse窗口中可见。 尝试停止并启动服务器,以确保其正常运行。 如果您已经从终端启动了服务器,那么您将不得不从终端停止它,然后从Eclipse启动它,否则它将无法正常工作。
Now we are ready with our setup to create the first servlet and run it on tomcat server.
现在我们准备好创建第一个servlet并在tomcat服务器上运行它的设置。
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.
选择“文件”>“新建”>“动态Web项目”,并使用下图提供运行时作为我们在上一步中添加的服务器,模块版本为3.0,以使用Servlet 3.0规范创建Servlet。
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.
现在选择File> New> Servlet并使用下图创建我们的第一个Servlet。 同样,我们可以单击完成,也可以通过下一步按钮检查其他选项。
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.
当我们单击Finish按钮时,它会生成我们的Servlet框架代码,因此我们无需键入所有不同的方法并在Servlet中导入,从而节省了时间。
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.
现在,我们将在doGet()方法中添加一些带有动态数据代码HTML,这些代码将被HTTP GET请求调用。 我们的第一个servlet如下所示。
package com.journaldev.first;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class FirstServlet
*/
@WebServlet(description = "My First Servlet", urlPatterns = { "/FirstServlet" , "/FirstServlet.do"}, initParams = {@WebInitParam(name="id",value="1"),@WebInitParam(name="name",value="pankaj")})
public class FirstServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public static final String HTML_START="<html><body>";
public static final String HTML_END="</body></html>";
/**
* @see HttpServlet#HttpServlet()
*/
public FirstServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
Date date = new Date();
out.println(HTML_START + "<h2>Hi There!</h2><br/><h3>Date="+date +"</h3>"+HTML_END);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
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.
在Servlet 3之前,我们需要在Web应用程序部署描述符中提供url模式信息,但是Servlet 3.0使用易于理解的Java注释 ,并且出错的机会更少。
Now chose Run > Run on Server option from servlet editor window and use below images for the options.
现在,从Servlet编辑器窗口中选择“运行”>“在服务器上运行”选项,并使用以下图像作为选项。
After clicking finish, the browser will open in Eclipse and we get following HTML page.
单击完成后,浏览器将在Eclipse中打开,然后出现以下HTML页面。
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.
您可以刷新它以检查Date是否是动态的并保持不变,也可以在Eclipse之外的任何其他浏览器中将其打开。
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.
因此,servlet用于生成HTML并作为响应发送它,如果您研究doGet()实现,则实际上是在响应PrintWriter对象中编写HTML文档时创建它,并在需要的地方添加动态信息。
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的主要原因。
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.
JSP还是服务器端技术,就像HTML一样,具有附加功能,可以在需要的地方添加动态内容。
JSP非常适合表示,因为它很容易编写,因为它就像HTML。 这是我们的第一个JSP程序,它执行与上述servlet相同的操作。
<%@page import="java.util.Date"%>
<%@ page language="java" contentType="text/html; charset=US-ASCII"
pageEncoding="US-ASCII"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "https://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Hello</title>
</head>
<body>
<h2>Hi There!</h2>
<br>
<h3>Date=<%= new Date() %>
</h3>
</body>
</html>
If we run above JSP, we get output like below image.
如果我们在JSP之上运行,我们将得到下图所示的输出。
The final project hierarchy looks like below image in Eclipse.
最终的项目层次结构类似于Eclipse中的下图。
We will look into Servlets and JSPs in more detail in future posts but before concluding this post, we should have a good understanding of some of the aspects of Java web applications.
在以后的文章中,我们将更详细地研究Servlet和JSP,但是在结束本文之前,我们应该对Java Web应用程序的某些方面有充分的了解。
Tomcat is a web container, when a request is made from Client to web server, it passes the request to web container and it’s web container job to find the correct resource to handle the request (servlet or JSP) and then use the response from the resource to generate the response and provide it to web server. Then the webserver sends the response back to the client.
Tomcat是一个Web容器,当从客户端向Web服务器发出请求时,它会将请求传递到Web容器,并且它是Web容器的工作,以找到正确的资源来处理该请求(servlet或JSP),然后使用来自服务器的响应。资源来生成响应并将其提供给Web服务器。 然后,网络服务器将响应发送回客户端。
When web container gets the request and if it’s for servlet then container creates two Objects HTTPServletRequest and HTTPServletResponse. Then it finds the correct servlet based on the URL and creates a thread for the request. Then it invokes the servlet service() method and based on the HTTP method service() method invokes doGet() or doPost() methods. Servlet methods generate the dynamic page and write it to the response. Once servlet thread is complete, the container converts the response to HTTP response and send it back to the client.
当Web容器获取请求时(如果它是针对Servlet的),则容器将创建两个对象HTTPServletRequest和HTTPServletResponse。 然后,它根据URL找到正确的servlet,并为请求创建一个线程。 然后,它调用servlet service()方法,并基于HTTP方法service()方法调用doGet()或doPost()方法。 Servlet方法生成动态页面并将其写入响应。 Servlet线程完成后,容器会将响应转换为HTTP响应,然后将其发送回客户端。
Some of the important work done by web container are:
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.
Java Web应用程序打包为Web存档(WAR),并且具有定义的结构。 您可以将上述动态Web项目导出为WAR文件,并将其解压缩以检查层次结构。 就像下面的图片一样。
web.xml file is the deployment descriptor of the web application and contains a mapping for servlets (prior to 3.0), welcome pages, security configurations, session timeout settings, etc.
web.xml文件是Web应用程序的部署描述符,包含Servlet(3.0之前),欢迎页面,安全性配置,会话超时设置等的映射。
Thats all for the java web application startup tutorial, we will explore Servlets and JSPs more in future posts.
以上就是Java Web应用程序启动教程的全部内容,我们将在以后的文章中进一步探讨Servlet和JSP。
Update: Next tutorial in this series is Java Servlets Tutorial
更新 :本系列的下一个教程是Java Servlets教程
翻译自: https://www.journaldev.com/1854/java-web-application-tutorial-for-beginners
java web初级面试题