JavaWeb into the world of technology 2: JSP and Servlet once and now

This series of articles will arrange to me on GitHub's "Java Interview Guide" warehouse, more exciting content please go to my warehouse View

https://github.com/h2pl/Java-Tutorial

Like it under the trouble spots Star Kazakhstan

Article first appeared in my personal blog:

www.how2playlife.com

This article is a micro-channel public number [of] Java technology rivers and lakes "into JavaWeb technology world" in which a Part of this article from the network, to the subject of this article speaks clear and thorough, and I think a lot of good integration of technology blog content, which cited a number of good blog posts, if infringement, please contact the author.

This blog series will show you how to from entry to advanced, from servlet to the frame, and then from ssm SpringBoot, step by step JavaWeb learn the basics and get started actual combat, and then to understand the technical components of the project JavaWeb often used, including log component, Maven, Junit, and much more, in order to make you a more complete understanding of the entire JavaWeb technology system, to form their own intellectual framework. In order to summarize and test your learning outcomes, this series will provide every knowledge point corresponding interview questions and suggested answers.

If you have any suggestions for this series of articles, or have any questions, you can also concerned about the number of public rivers and lakes [] Java technology to contact the author, you are welcome to participate in the creation and revision of this blog series.

As an extension jsp Servlet technology, often someone will jsp and Servlet confused. In this paper, we will bring the difference between servlet and jsp, and we want to help.

The difference between the servlet and jsp

1, Servlet output HTML content can be dynamically by HttpServletResponse object in Java code.

2, JSP embedded Java code in a static HTML content, then the Java code generated HTML content to be dynamically executed after.

jsp servlet and their characteristics

1, Servlet although well organized business logic code, but Java source file, because it is generating dynamic HTML content string concatenation by the way, so it is easy to lead to code maintenance problems, poor readability.

2, JSP Servlet although avoid the disadvantages in terms of generating HTML content, but mixed with a large number of complex business logic in HTML.

Two-pronged approach by MVC

JSP and Servlet has its own application environment, then there is no way to let them play to their advantage? The answer is Ken there, MVC pattern can be the perfect solution to this problem.

MVC model is Model-View-Controller for short, is a software engineering mode software architecture is divided into three basic parts, namely: Model (the Model), view (View) and a controller (the Controller):

Controller-- responsible for forwarding the request to process the request

View-- responsible for interface display

Prepared Model-- business functions (e.g., algorithm), database design and implement a data access operation

In the software system JSP / Servlet development, the three sections is described as follows:

229cf9ff5b1729eaf408fac56238eeb3_hd

1, Web browser sends an HTTP request to the server, then Controller (Servlet) acquires and processes (e.g. parameter analysis, request forwarding)

2, Controller (Servlet) call the core business logic --Model part, get results

3, Controller (Servlet) to the logic processing result View (JSP), the output dynamic HTML content

4, dynamically generated HTML content back to the browser display

MVC model has a great advantage in Web development, it is perfect to avoid the JSP and Servlet own shortcomings, let Servlet only responsible for business logic, without generating the HTML code; while the JSP will not be filled with a lot of business code , this can greatly improve the readability and maintainability of the code.

JavaWeb Basics

First, what Servlet that?

Java  the Servlet is a program running on the Web server or application server, which is a HTTP server and the request from the Web browser or other HTTP client database intermediate layer or between applications.

The use of Servlet, you can collect user input from a Web form, showing records from a database or other source, you can also create dynamic web pages.

Java  procedures normally Servlet using CGI (Common Gateway Interface, common gateway interface) can be implemented to achieve the same purpose. But compared to CGI, Servlet has the following advantages:

  • 1, significantly better performance.
  • 2, Servlet execution within the address space of the Web server. So that it is not necessary to create a separate process to handle each client request.
  • 3, Servlet is a platform-independent, because they are written in Java.
  • 4, Java Security Manager on the server to perform a series of restrictions to protect the resources on the server computer. Therefore, Servlet is credible.
  • 5, all of the features of the Java class libraries are available for Servlet. It can interact through sockets and RMI mechanism and applets, database or other software.

Two, Servlet life cycle

Servlet life cycle can be defined as the entire process from creation to destruction. The following is the procedure to follow Servlet:

  • 1, Servlet is initialized by calling the init () method.
  • 2, Servlet call service () method to process client requests.
  • 3, Servlet by calling destroy () method is terminated (end).
  • 4, finally, Servlet is garbage collected by the JVM's garbage collector.

init () method

The init method is designed to call only once. It is called when you first create a Servlet, it is no longer called upon each subsequent user request. Therefore, it is used for one-time initialization, like the init method of Applet.

When the Servlet to create a user corresponding to the first call to the Servlet URL, but you can also specify the Servlet is loaded when the server is first started.

service () method

service () method is the main method performs the actual task. Servlet container (ie, Web server) calls the service () method to handle requests from the client (browser), and to write the formatted response back to the client.

Each time the server receives a request Servlet, the server will generate a new thread and call service. service () method checks the type of HTTP request (GET, POST, PUT, DELETE, etc.), and calls doGet, doPost, doPut, doDelete the like at the appropriate time.

 destroy () method

destroy () method is invoked only once, to be called at the end of the Servlet life cycle. destroy () method allows you to turn off the Servlet database connection, stop the background thread, list, or click on the Cookie counter is written to disk, and perform other similar clean-up activities.

After calling destroy () method, servlet object is marked as garbage collection.

 Examples

After performing:

After continued requests:

Visible only when ready request service () method to perform!

Related interview questions

How to understand single instance of multi-threaded Servlet? **

Different users also issued a request for the same business (such as registration), and that this time there is a container produced several servlet instance it?

The answer is: only one servlet instance . A servlet is loaded when the memory is first accessed and instantiated. A request to share the same service instance of the servlet. Different service request is typically correspond to different servlet.

As the Servlet / JSP is the default, so when writing code requires very careful consideration to security issues multi-threaded multi-threaded execution mode.

JSP's existing multithreading issues:

When a client first requests a JSP file, the server to the JSP compiled into a CLASS file, and create an instance of the class, and then create a thread processing CLIENT-side requests. If there are multiple clients simultaneously request the JSP file, the server creates multiple threads. Each client request corresponding to a thread. Multi-threaded execution can greatly reduce the demand on system resources, and improve concurrency and system response time.

JSP possible variables used are described below:

Examples of variables : instance variable is allocated in the heap, and belongs to all the threads share the instance, it is not thread safe.

JSP系统提供的8个类变量

JSP中用到的OUT,REQUEST,RESPONSE,SESSION,CONFIG,PAGE,PAGECONXT是线程安全的(因为每个线程对应的request,respone对象都是不一样的,不存在共享问题),APPLICATION在整个系统内被使用,所以不是线程安全的。

局部变量: 局部变量在堆栈中分配,因为每个线程都有它自己的堆栈空间,所以是线程安全的

静态类: 静态类不用被实例化,就可直接使用,也不是线程安全的

外部资源: 在程序中可能会有多个线程或进程同时操作同一个资源(如:多个线程或进程同时对一个文件进行写操作).此时也要注意同步问题.

Servlet单实例多线程机制:

Servlet采用多线程来处理多个请求同时访问。servlet依赖于一个线程池来服务请求。线程池实际上是一系列的工作者线程集合。Servlet使用一个调度线程来管理工作者线程。

当容器收到一个Servlet请求,调度线程从线程池中选出一个工作者线程,将请求传递给该工作者线程,然后由该线程来执行Servlet的service方法。

当这个线程正在执行的时候,容器收到另外一个请求,调度线程同样从线程池中选出另一个工作者线程来服务新的请求,容器并不关心这个请求是否访问的是同一个Servlet.当容器同时收到对同一个Servlet的多个请求的时候,那么这个Servlet的service()方法将在多线程中并发执行。

Servlet容器默认采用单实例多线程的方式来处理请求,这样减少产生Servlet实例的开销,提升了对请求的响应时间,对于Tomcat可以在server.xml中通过 元素设置线程池中线程的数目。 

如何开发线程安全的Servlet

1、实现 SingleThreadModel 接口

该接口指定了系统如何处理对同一个Servlet的调用。如果一个Servlet被这个接口指定,那么在这个Servlet中的service方法将不会有两个线程被同时执行,当然也就不存在线程安全的问题。这种方法只要将前面的Concurrent Test类的类头定义更改为:

Public class Concurrent Test extends HttpServlet implements SingleThreadModel { 
………… 
}  

同步对共享数据的操作

使用synchronized 关键字能保证一次只有一个线程可以访问被保护的区段

避免使用实例变量

本实例中的线程安全问题是由实例变量造成的,只要在Servlet里面的任何方法里面都不使用实例变量,那么该Servlet就是线程安全的。

1) Struts2的Action是原型,非单实例的;会对每一个请求,产生一个Action的实例来处理

Struts1 Action是单实例的

mvc的controller也是如此。因此开发时要求必须是线程安全的,因为仅有Action的一个实例来处理所有的请求。单例策略限制了Struts1 Action能作的事,并且要在开发时特别小心。Action资源必须是线程安全的或同步的。

2) Struts1的Action,Spring的Ioc容器管理的bean 默认是单实例的.

Spring的Ioc容器管理的bean 默认是单实例的。

Struts2 Action对象为每一个请求产生一个实例,因此没有线程安全问题。(实际上,servlet容器给每个请求产生许多可丢弃的对象,并且不会导致性能和垃圾回收问题)。

当Spring管理Struts2的Action时,bean默认是单实例的,可以通过配置参数将其设置为原型。(scope="prototype )

五、servlet与jsp的区别

1.jsp经编译后就变成了Servlet.(JSP的本质就是Servlet,JVM只能识别java的类,不能识别JSP的代码,Web容器将JSP的代码编译成JVM能够识别的java类)

2.jsp更擅长表现于页面显示,servlet更擅长于逻辑控制.

3.Servlet中没有内置对象,内置对象都是必须通过HttpServletRequest对象,HttpServletResponse对象以及HttpServlet对象得到.Jsp是Servlet的一种简化,使用Jsp只需要完成程序员需要输出到客户端的内容,Jsp中的Java脚本如何镶嵌到一个类中,由Jsp容器完成。而Servlet则是个完整的Java类,这个类的Service方法用于生成对客户端的响应。

4.对于静态HTML标签,Servlet都必须使用页面输出流逐行输出

参考文章

https://www.w3cschool.cn/servlet/servlet-sxoy2p19.html
https://blog.csdn.net/qq_19782019/article/details/80292110
https://blog.csdn.net/qiuhuang_123/article/details/83617647
https://blog.csdn.net/zt15732625878/article/details/79951933
https://blog.csdn.net/android_hl/article/details/53228348

微信公众号

个人公众号:黄小斜

黄小斜是跨考软件工程的 985 硕士,自学 Java 两年,拿到了 BAT 等近十家大厂 offer,从技术小白成长为阿里工程师。

JAVA authors focus on the back-end technology stack, keen to share programmers dry, learning experience, job experience and life program is currently small yellow diagonal CSDN blog a million + views, fans know almost 2W +, the whole network has 10W + reader .

Huang is a little oblique slash youth, adhere to the study and writing, believe in the power of lifelong learning, hope and more programmers make friends, progress and grow together!

Original eBook:
public attention after [number] Huang oblique reply [original] to collect my original e-book e-book "Programmer's rookie practice Manual: From white to Alibaba Java technology engineer"

Programmers 3T Technology Learning Resources: Some programmers learning resources spree technology, the number of public attention, background replies keyword "data" can get free no routine.

PubMed review the information:
Computer PubMed spree, are some of the review materials for my own use when PubMed review, including public courses and professional video review, recommend it to everyone here, the number of public attention, background replies keyword "PubMed" that is, available free of charge.

No public technology: Java technology rivers and lakes

If you want to focus on my real time updated articles and dry sharing, you can focus on my public number of rivers and lakes] [Java technology Java, a technical engineer Ali station, the author Huang oblique, focused Java related technologies: SSM, SpringBoot , MySQL, distributed, middleware, cluster, Linux, network, multi-threaded, occasionally speaking point Docker, ELK, as well as dry goods and technology to share the learning experience, committed to the full Java stack development!

Java engineers required Learning Resources: Some Java engineers common learning resources, the number of public attention, background replies keyword "Java" to get free no routine.

My public number

Guess you like

Origin www.cnblogs.com/AliCoder/p/11707342.html