用于在 Java 中编写 Web 应用程序的不同技术如何协同工作? [英] How do the different technologies used for programming webapplications in Java work together?

查看:21
本文介绍了用于在 Java 中编写 Web 应用程序的不同技术如何协同工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 Java 开发一个网络应用程序.但我很困惑所有这些不同的技术是什么以及它们如何协同工作:

  • HTTP
  • HTML
  • CSS
  • Javascript
  • jQuery
  • 网络容器
  • Servlet
  • JSP
  • JSTL
  • 表达语言 (EL)

在网络上可以找到大量关于这些主题的资源,每个资源看起来都需要阅读几本书才能理解.您能否解释一下这些技术,以便我在开始开发 Web 应用程序时对它们有一个基本的了解?

解决方案

请注意,此说明的目的是提供一个大致的了解,而不是检查每个主题的所有细节.有经验的用户肯定会发现看起来太笼统"的点,但我们不要混淆新用户.每个主题中都提供了进一步阅读的链接.

让我们从基本的基础知识开始.您需要了解网页如何进入您的计算机才能了解以下所有技术.

HTTP

HTTP 代表 超文本传输​​协议.它描述了浏览器如何与网络服务器通信以检索其内容(网页).网页存储在服务器上,浏览器需要一种方法来告诉服务器它想要获取哪个网页.另一方面,服务器需要告诉浏览器是否找到了请求的资源,并将此信息发送给浏览器.

  1. 浏览器向服务器发送请求.请求由几个部分组成:
    • 网址,例如https://stackoverflow.com/questions/ask",因此服务器知道要传送哪个页面.
    • HTTP 方法.最常见的是get,表示浏览器想要检索信息(例如单个页面,或网络搜索)和post,表示浏览器推送一些信息到网络服务器,就像论坛帖子一样.Post 通常会更改服务器上的某些内容(例如论坛中的新帖子),而 get 不会.
    • 请求正文,可以包含例如文本框的文本、要上传的图像等.
  2. 服务器发回一个响应,这是浏览器请求的响应.它包括:
    • HTTP 状态代码.这是一个显示请求结果的三位数字.最常见的是正常 (2xx)、重定向 (3xx)、客户端错误 (4xx) 和服务器错误 (5xx).重定向状态代码是将浏览器重定向到另一个页面的最佳方式.
    • 响应正文,其中包含网页(如果有).

HTML

HTML 代表 超文本标记语言并呈现内容.HTML 文本从服务器发送到客户端(即浏览器)并由浏览器呈现以显示给用户.示例 HTML:

<头><title>我的第一个网页</title><身体><p>你好世界!</p>

由于 HTML 多年来不断改进,因此重要每个 HTML 页面的第一行都包含 DOCTYPE 声明.它告诉浏览器应该如何呈现不同的标签(如

).渲染过程由浏览器完成.由本地计算机上的浏览器完成的一切都称为客户端.记住这个词!

CSS

表示层叠样式表.这为网页添加了样式,例如颜色、字体大小、元素位置等.CSS 定义通常保存在单独的文件中以提高可维护性.样式的呈现也在客户端完成.

JavaScript

不,这与 Java 无关.重复:没什么.执行的是一种完全不同的编程语言通过客户端的浏览器.使用 JavaScript,您可以将编程逻辑包含到您的网页中并执行诸如:

  • 验证用户输入
  • 精美的幻灯片
  • 甚至是编程游戏!

您需要注意,可以在浏览器中关闭 JavaScript,然后不会执行任何 JavaScript 代码.所以你不应该依赖于你的 web 应用程序的 JavaScript 的可用性(除非你必须,比如游戏).JavaScript 可能会被滥用于重定向(您应该在其中使用 HTTP 状态代码)或元素样式(为此使用 CSS).因此,在使用 Javascript 执行某些操作之前,请检查是否可以通过其他方式实现.甚至下拉菜单也可以仅使用 HTML 和 CSS!

jQuery

jQuery 只不过是一个用 JavaScript 编写的库.当你想让你的 JavaScript 跨浏览器兼容时,它会变得很方便,因为不同的浏览器在它们的 JavaScript 实现上有一些细微的差异.它对于选择页面的某些元素effects 等等.它仍然是JavaScript,所以它运行在客户端.>

网络容器

这是一个位于您的服务器上并在服务器端运行的软件.您的网络应用程序通常放置在 网络容器中.它是客户端请求和您的 web 应用程序之间的接口,并做了一些事情来使编程 web 应用程序更加舒适.例如,Apache Tomcat 是一个 Web 容器.

小服务程序

现在我们进入 Java 世界.Servlets 是 Web 应用程序的一部分,它位于 Web 容器内的服务器上,它们运行在服务器端.Servlet 是处理来自客户端的请求并返回响应的 Java 类.典型的 HTTP Servlet 如下所示:

public class HelloWorld extends HttpServlet {public void doGet(HttpServletRequest request,HttpServletResponse 响应)抛出 ServletException,IOException {PrintWriter out = response.getWriter();out.println("");out.println("");out.println("");out.println("");out.println("</head>");out.println("");out.println("<p>Hello World!</p>");out.println("</body>");out.println("</html>");}}

HttpServlet 类有多个 doXxx 方法,每个 HTTP 方法一个,可以由开发人员覆盖.在这里,doGet 被覆盖,这意味着当一个 GET 请求被发送到这个 servlet 时,这个代码被执行.该方法获取请求和响应作为参数,HttpServletRequestHttpServletResponse.

要通过 URL 访问该 Servlet,web.xml 必须配置:

<servlet-name>HelloWorld</servlet-name><servlet-class>com.example.HelloWorld</servlet-class></servlet><servlet-mapping><servlet-name>HelloWorld</servlet-name><url-pattern>/hello</url-pattern></servlet-mapping>

现在,客户端可以使用 GET 和 /hello 作为 URL 向我们的 servlet 发出请求.例如,如果我们的网络应用程序在 www.example.com 上运行,则使用 GET 的正确 URL 将是 http://www.example.com/hello.

JSP

代表 Java 服务器页面.如您所见,使用 Servlet 向客户端发送响应相当不方便.一些聪明人提出了这样的想法:如果我们可以将 Java 代码添加到 HTML 页面会怎样?"嗯,这就是 JSP:

<头><title>Hello JSP</title><身体><%for(int i=0; i<10; i++){out.print("循环数" + i);}%>

事实上,JSP 被翻译成 Java Servlet 代码(由 Web 容器)和编译.真的!这不是魔法.这意味着,它们只不过是 Servlet!这是上述 JSP 的等效 Servlet 代码:

public class ServletAbc extends GenericServlet {公共无效服务(ServletRequest req,ServletResponse res)抛出 ServletException,IOException{PrintWriter out = res.getWriter();out.println("");out.println("");out.println("");out.println("<title>Hello JSP</title>");out.println("</head>");out.println("");for(int i=0; i<10; i++){out.print("循环数" + i);}out.println("</body>");out.println("</html>");}}

您会看到,在将响应发送到客户端之前,所有 Java 代码都在服务器端处理.

JSTL

代表 Java 标准标签库.顾名思义,它是一个您需要在您之前包含的库可以用.

带有 Java 代码的 JSP 仍然不是最好的解决方案.随着页面大小的增长,它变得非常不可读,降低了可维护性并且难以阅读.那么,如果我们可以只使用额外的标签来实现页面流、循环等,并让 Java 类来完成编程逻辑呢?欢迎使用标签库!

有很多标签库,JSTL 是基本"的,提供核心功能.这包括 if/else 构造、循环等.它包含在 JSP 中,翻译并编译为 Servlet,因此在服务器端上运行.

EL

表示 表达式语言,用于计算表达式和访问 Java 对象的值您已在 Java 类中创建.通常,您结合使用 Servlet、JSP、JSTL 和表达式语言:

  • 客户端请求到达 Servlet.Servlet 执行一些编程逻辑(如从数据库读取数据)并在请求中存储一些 Java 对象.之后,它将请求转发到服务器上的另一个资源,如 JSP.转发 发生在网络应用程序内部并且不是重定向.
  • JSP 使用 EL 访问请求中的 Java 对象,显示它们并将响应发送给客户端.

例如,这是您的 Servlet:

public class HelloWorld extends HttpServlet {public void doGet(HttpServletRequest request,HttpServletResponse 响应)抛出 ServletException,IOException {//访问数据库,在此处进行计算等String hello = "Hello world!";字符串 someBoolean = true;request.setAttribute("helloObject", 你好);request.setAttribute("myBoolean", 你好);RequestDispatcher dispatcher = request.getRequestDispatcher("/result.jsp);dispatcher.forward(请求,响应);}}

还有result.jsp:

<html xmlns:c="http://java.sun.com/jsp/jstl/core"><头><title>你好 EL</title><身体>${helloObject}<c:if test="${myBoolean}">表达是真实的.</c:if>

这将输出 Hello world!表达式为真..

注意事项

  • 我想我已经足够清楚地说明了什么在服务器端运行,什么在客户端运行.不要把它们混在一起.
  • 始终使用正确的工具完成正确的工作.HTML 用于内容,CSS 用于布局和样式,Javascript 用于客户端编程逻辑.如果不需要,请不要依赖 Javascript,有些用户已将其关闭.
  • 大多数其他技术(如 JSF)都是建立在现有技术之上的.了解它们的构建基础,以了解它们在何处运行(客户端、服务器)以及它们应该做什么.

I want to develop a webapplication using Java. But I am quite confused what all these different technologies are and how they work together:

  • HTTP
  • HTML
  • CSS
  • Javascript
  • jQuery
  • Web Container
  • Servlets
  • JSP
  • JSTL
  • Expression Language (EL)

There is a huge amount of resources which can be found on the web regarding these topics, and each of them looks like you need to read several books to understand them. Can you explain these technologies so that I have a basic understanding of them when starting to develop a webapplication?

解决方案

Note that the goal of this explanation is to give a general understanding, not to examine all the details of each topic. Experienced users will surely find points which seem to be "too general", but let's don't confuse new users. Links for further reading are provided in each topic.

Let's start with the fundamental basics. You need to know how a webpage comes to your computer in order to understand all the following technologies.

HTTP

HTTP stands for Hyper Text Transfer Protocol. It describes how the browser communicates with the webservers in order to retrieve their content (webpages). Webpages are stored on servers, and the browser needs a way to tell a server which webpage it would like to get. The server, on the other hand, needs to tell the browser if the requested resource was found or not and send this information to the browser.

  1. The browser sends a request to the server. The request consists of several parts:
    • The URL, e.g. "https://stackoverflow.com/questions/ask", so the server knows which page to deliver.
    • The HTTP method. Most common are get, which indicates that the browser wants to retrieve information (e.g. a single page, or a websearch), and post, which indicates that the browser pushes some information to the webserver, like a forum post. Post usually changes something on the server (like the new post in a forum), while get does not.
    • Request body, which can contain for example the text of a textbox, an image to be uploaded, etc.
  2. The server sends back a response, which is the answer of the browser's request. It consists of:
    • A HTTP status code. This is a three-digit-number which shows the result of the request. Most common are OK (2xx), REDIRECTION (3xx), CLIENT ERROR (4xx) and SERVER ERROR (5xx). Redirection status codes are the best way to redirect the browser to another page.
    • Response body, this contains the webpage (if any).

HTML

HTML stands for Hyper Text Markup Language and presents the content. HTML text is sent from the server to the client (which is, the browser) and is rendered by the browser to display it to the user. Example HTML:

<!DOCTYPE HTML>
<html>
    <head>
        <title>My first webpage</title>
    </head>
    <body>
        <p>Hello World!</p>
    </body>
</html>

Since HTML has improved over the years, it is important that the first line of each HTML page contains the DOCTYPE declaration. It tells the browser how the different tags (like <p>) should be rendered. The rendering process is done by the browser. Everything, that is done by the browser on the local computer, is called client-side. Remember that term!

CSS

Means Cascading Style Sheets. This adds style to a webpage, like colors, font sizes, positions of elements, etc. CSS definitions are often kept in separate files to improve maintainability. Rendering of styles is also done client-side.

JavaScript

No, this has nothing to do with Java. Repeat: nothing. It is a totally different programming language that is executed by the browser on client-side. With JavaScript, you can include programming logic to your webpage and do things like:

  • Validating user inputs
  • Fancy slideshows
  • Even programming games!

You need to be aware of that JavaScript can be turned off in the browser, and then no JavaScript code will be executed. So you should not rely on the availability of JavaScript for your webapplication (except you have to, like for a game). JavaScript can be abused for things like redirection (where you should use HTTP status codes) or styling of elements (use CSS for that). So before doing something with Javascript, check if it is possible somehow else. Even dropdown menus are possible with only HTML and CSS!

jQuery

jQuery is nothing else than a library written in JavaScript. It becomes handy when you want to make your JavaScript cross-browser compatible, because different browsers have some minor differences in their JavaScript implementations. It is also useful for selecting certain elements of a page, effects, etc. It is still JavaScript, so it runs on client-side.

Web Container

This is a software which is located on your server and runs on server-side. Your webapplications are usually placed in a web container. It is the interface between client requests and your webapplication and does several things to make programming webapplications more comfortable. For example, Apache Tomcat is a web container.

Servlets

Now we get to the Java world. Servlets are part of your webapplication which is located on a server inside a web container, they run on server-side. Servlets are Java classes which process the request from the client and send back a response. A typical HTTP Servlet looks like this:

public class HelloWorld extends HttpServlet {
    public void doGet(HttpServletRequest request,
                      HttpServletResponse response)
                      throws ServletException, IOException {
        PrintWriter out = response.getWriter();
        out.println("<!DOCTYPE HTML>");
        out.println("<html>");
        out.println("<head>");
        out.println("<title>Hi</title>");
        out.println("</head>");
        out.println("<body>");
        out.println("<p>Hello World!</p>");
        out.println("</body>");
        out.println("</html>");
    }
}

HttpServlet classes have several doXxx methods, one for each HTTP method, which can be overridden by the developer. Here, doGet is overridden, which means that this code is executed when a GET request is sent to this servlet. This method gets the request and response as parameters, HttpServletRequest and HttpServletResponse.

To make this Servlet accessible via a URL, the web.xml has to be configured:

<servlet>
    <servlet-name>HelloWorld</servlet-name>
    <servlet-class>com.example.HelloWorld</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>HelloWorld</servlet-name>
    <url-pattern>/hello</url-pattern>
</servlet-mapping>

Now, a client can make a request to our servlet using GET and /hello as URL. For example, if our webapplication runs on www.example.com, correct URL to be used would be http://www.example.com/hello using GET.

JSP

Stands for Java Server Pages. As you have seen, using Servlets to send responses to the client is rather unhandy. Some clever guys had the idea: "What if we could just add Java code to HTML pages?" Well, and that's what JSP is:

<!DOCTYPE HTML>
<html>
    <head>
        <title>Hello JSP</title>
    </head>
    <body>
        <%
            for(int i=0; i<10; i++){
                out.print("Loop number " + i);
            }
        %>          
    </body>
</html>

In fact, JSPs are translated to Java Servlet code (by the web container) and compiled. Really! It's no magic. That means, they are nothing else than Servlets! This is the equivalent Servlet code for the above JSP:

public class ServletAbc extends GenericServlet {
    public void service(ServletRequest req,ServletResponse res)
                        throws ServletException, IOException{
        PrintWriter out = res.getWriter();

        out.println("<!DOCTYPE HTML>");
        out.println("<html>");
        out.println("<head>");
        out.println("<title>Hello JSP</title>");
        out.println("</head>");
        out.println("<body>");
        for(int i=0; i<10; i++){
            out.print("Loop number " + i);
        }
        out.println("</body>");
        out.println("</html>");
    }
}

You see, all Java code is processed on server-side before the response is sent to the client.

JSTL

Stands for Java Standard Tag Library. Like the name says, it is a library which you need to include before you can use it.

JSPs with Java code are still not the best solution. It becomes very unreadable as the size of the pages grows, reduces maintainability and is difficult to read. So, what if we could just use additional tags to implement page flow, loops etc. and let Java classes do the programming logic? Welcome using tag libraries!

There are many tag libraries out there, and JSTL is the "basic" one, providing core functionality. This includes if/else constructs, loops, etc. It is included in JSPs, translated and compiled to Servlets and therefore runs on server-side.

EL

Means Expression Language and is used to evaluate expressions and to access values of Java objects you have created in Java classes. Usually, you combine Servlets, JSP, JSTL and Expression language:

  • A client request comes to a Servlet. The Servlet does some programming logic (like reading data from a Database) and stores some Java objects in the request. After that, it forwards the request to another resource on the server, like a JSP. Forwarding happens inside the webapplication and is not a redirect.
  • The JSP uses EL to access the Java objects in the request, displays them and sends the response to the client.

For example, this is your Servlet:

public class HelloWorld extends HttpServlet {
   public void doGet(HttpServletRequest request,
                     HttpServletResponse response)
                     throws ServletException, IOException {
      // access databases, do calculations etc. here
      String hello = "Hello world!";
      String someBoolean = true;
      request.setAttribute("helloObject", hello);
      request.setAttribute("myBoolean", hello);
      RequestDispatcher dispatcher = request.getRequestDispatcher("/result.jsp);
      dispatcher.forward(request, response);
   }
}

And the result.jsp:

<!DOCTYPE HTML>
<html xmlns:c="http://java.sun.com/jsp/jstl/core">
    <head>
        <title>Hello EL</title>
    </head>
    <body>
        ${helloObject}
        <c:if test="${myBoolean}">
            The expression is true.
        </c:if>
    </body>
</html>

This will output Hello world! The expression is true..

Things to keep in mind

  • I think I have shown clear enough what runs on server-side and what runs on client-side. Don't mix them up.
  • Always use the right tool for the right job. HTML for content, CSS for layout and style, Javascript for client-side programming logic. Don't rely on Javascript if you don't need it, some users have it turned off.
  • Most other technologies, like JSF, are built on top of existing technologies. Find out on what they are built on to understand where they are running (client, server) and what they are supposed to do.

这篇关于用于在 Java 中编写 Web 应用程序的不同技术如何协同工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆