Compared with ASP and PHP, Servlet/JSP has a high execution efficiency due to its multi-threaded operation.
Servlet/JSP is executed in multi-thread mode by default.
Servlet is a single instance,
Form. jsp
<Body>
<Form action = "HelloServlet">
Username: <input type = "text" name = "username"> <br>
<Input type = "submit" value = "submit">
</Form>
</Body>
HelloServlet. java
Import java. io. IOException;
Import javax. servlet. ServletException;
Import javax. servlet. http. HttpServlet;
Import javax. servlet. http. HttpServletRequest;
Import javax. servlet. http. HttpServletResponse;
Public class HelloServlet extends HttpServlet
{
Private String username;
@ Override
Protected void doGet (HttpServletRequest req, HttpServletResponse resp)
Throws ServletException, IOException
{
This. username = req. getParameter ("username ");
// Perform background business processing
Try
{
Thread. sleep (10000 );
}
Catch (Exception e)
{
E. printStackTrace ();
}
Req. setAttribute ("username", this. username );
Req. getRequestDispatcher ("hello. jsp"). forward (req, resp );
}
}
Hello. jsp
<Body>
Username: <% = request. getAttribute ("username") %>
</Body>
If you start two browsers at the same time, the two results will be the same.
After submitting the form for the first user, go to the server side, get the username member variable, and then go to hello. jsp. this is also true for the second browser, because the Servlet is single-instance and has only one member variable,
In this way, when multiple users access a Servlet at the same time, they will access the member variables in the only Servlet instance. If they write data to the Servlet, the Servlet multithreading problem will occur. Therefore, on the hello. jsp page, the user name of the second browser overwrites the user name of the first browser, so that the two pages are displayed the same.
To avoid this problem, you need to change the member variable to a local variable.
If you change the hello. jsp page
Hello. jsp
<Body>
Username: <% = request. getParameter ("username") %>
</Body>
The displayed results are different because two requests are forwarded, and two corresponding processes are performed.
Note: If you want to write a variable, you 'd better define it as a local variable rather than a member variable. (Solution for multi-thread synchronization ).
Similarities and differences between Servlet and JSP
Similarities: dynamic web pages can be generated.
JSP is good at creating web pages and generating dynamic web pages, which is intuitive. The disadvantage of JSP is that it is not easy to track and troubleshoot.
Servlet is pure java code and is good at processing processes and business logic. The disadvantage of Servlet is that it is not intuitive to generate dynamic web pages.