Overview of Servlet Technology in web development technology, webservlet

Source: Internet
Author: User

Overview of Servlet Technology in web development technology, webservlet

1. What is servlet:
Servlet is a server-side java application.
It can directly output information like jsp

The servlet class must inherit the HttpServlet class. Otherwise, it cannot be called serlvet.

The servlet class is a java class, but it has its own rules.
Servlet must be registered in the web. xml file
When the server is started, you can load the servlet class according to these configurations .......


2. servlet functions:
C: Control Layer
Serlvet is mainly used for controlling forwarding and needs to be integrated into the MVC mode (routine)


3. servlet lifecycle:
Init
Service
Destroy

/*** Initialization of the servlet. <br> ** @ throws ServletException if an error occure * When the servlet is accessed for the first time, this method will be automatically called * this method is called Initialization Method * only once */public void init () throws ServletException {// Put your code hereSystem. out. println ("I am the init method ");}

/**
* Specific business methods
* This method will be called multiple times.
* This method is called every time you access the servlet.
* The service obtains your submission method based on request. getMethod, and then decides the call to doGet. doPost.
*/
Public void service (HttpServletRequest request, HttpServletResponse response)
Throws ServletException, IOException {
Super. service (request, response );
System. out. println ("I'm service ..................................... ");
}

/**
* Destruction of the servlet. <br>
* When the servlet is canceled
* This method is the destruction method.
* It is only automatically called once by the server.
*
*/
Public void destroy (){
Super. destroy (); // Just puts "destroy" string in log
// Put your code here
System. out. println ("destroy method called ..............");
}

 

 

4. steps required to define the servlet
A. Define A class that inherits HttpServlet
B. Rewrite the doGet and doPost methods.
C. Implement the doGet and doPost Logic
D. Define the servlet ing method in the web. xml deployment description file.


5. Set a welcome page for the web Application

<welcome-file-list><welcome-file>index.html</welcome-file><welcome-file>index.jsp</welcome-file></welcome-file-list>

 

If the first page cannot be found, it will be searched down in sequence

6. Relationship between requests and other classes

HttpSession session = request.getSession();session.setAttribute("username", "scott");ServletContext application = this.getServletContext();application.setAttribute("userlist", null);RequestDispatcher rd = request.getRequestDispatcher("C.jsp");rd.forward(request, response);

 

7. Use session in servlet

HttpSession ss = request.getSession();List list=new ArrayList();list.add("SMITH");list.add("ALLEN");ss.setAttribute("userlist", list);

 

 

 

8. servlet usage

Servlet can be accessed like jsp
A. You can directly enter an address in the address bar to access
Http: /localhost: 8088/myproject15/servlet/CServlet


B. hyperlink Mode
<A href = "servlet/CServlet? Username = zhangshan & pwd = 123456789 "> link </a>

C. include or forward labels
<Jsp: forward page = "servlet/CServlet? Username = wangwu & pwd = 123456 "> </jsp: forward>


D. javascript redirection
<Input type = "button" value = "click"
Onclick = "location. replace ('servlet/CServlet? Username = abcd & pwd = 123 '); ">

E. response redirection


9. Configure errorpage on the web Server

<error-page><error-code>500</error-code><location>/index.html</location></error-page><error-page><exception-type>java.lang.NullPointerException</exception-type><location>/index.html</location></error-page>

 


10. Configure session-config

<session-config><session-timeout>1</session-timeout></session-config>

 

The timeout time is measured in minutes.


11. Define initialization parameters for servlet
Use the getInitParameter () method to extract servlet initialization parameters.

Definition:

<servlet><servlet-name>a</servlet-name><servlet-class>com.sun.demo.MyServlet</servlet-class><init-param><param-name>type</param-name><param-value>text/html;charset=GBK</param-value></init-param></servlet>

 


Extraction Method:
String str = this. getInitParameter ("type ");

 

12. filter:
Actions processed before arriving at the target page
Purpose:
Permission Verification
Log records
Image Conversion
Data Encryption
And so on.

 

Steps:
1) Implement the Filter Interface
2). Implement the doFilter Method
3) Pass the filter chain and put the request in the past
4). register the filter in the web. xml file.


13. Listener
Triggered by events. For example, the application executes setAttribute ();


Procedure
Two steps:
A. Implement the listener interface to indicate what you want to do
B. register the listener in the web. xml file.

14. Character Set Conversion Problems

Categories
A. If the jsp: include or jsp: forward relationship is used on the page, convert the Chinese character set:
Request. setCharacterEncoding ("GBK ");

B. display Chinese Characters in servlet:
Unable to use the encoding instruction in the jsp page
<% @ Page language = "java" import = "java. util. *" contentType = "text/html; charset = GBK" %>

Set the output encoding in the servlet through:
Response. setContentType ("text/html; charset = GBK ");


C. Passing common parameters
Common parameters also need to take Chinese into account.
In addition to the page display settings contentType = "text/html; charset = GBK", we also need to convert Chinese characters into hard-coded characters.

Hyperlink:
String str = request. getParameter ("username ");
Str = new String (str. getBytes ("iso8859-1"), "GBK ");


Form:
String str = request. getParameter ("username ");
Str = new String (str. getBytes ("iso8859-1"), "GBK ");

Javascript redirection:
String str = request. getParameter ("username ");
Str = new String (str. getBytes ("ISO8859-1"), "gbk ");


Response Method:
String message = "My Chinese test ";
Response. sendRedirect ("L. jsp? Message = "+ URLEncoder. encode (message ));

Receiving page:
String message = request. getParameter ("message ");
Message = new String (message. getBytes ("ISO8859-1"), "GBK ");


Request and other scopes
Request. setAttribute ("username", "my test name ");
Session. setAttribute ("passwd", "My password ");
Conversion not required

 


15. Write a thread-safe servlet

Concept of java thread sharing data
Data used by multiple threads is shared.

Boolean shutdown = true;/*** thread body */public void run () {// TODO Auto-generated method stubint I = 0; while (1 = 1) {I ++; System. out. println (Thread. currentThread (). getName () + "=" + I); if (shutdown = false) {break;} System. out. println ("this thread ends! ");}

 


Servlet is based on multiple threads, so global variables also have the problem of "sharing data.

Define a global variable in the servlet. The data will be "shared" by multiple threads ",

String username; public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {response. setContentType ("text/html"); PrintWriter out = response. getWriter (); username = request. getParameter ("username"); // Zhang santry {Thread. sleep (1000*6);} catch (InterruptedException e) {// TODO Auto-generated catch blocke. printStackTrace ();} out. println (username); out. close ();}

 


If you submit two requests at the same time:
Http: // localhost: 8088/myproject19/servlet/AServlet? Username = zhangshan
Http: // localhost: 8088/myproject19/servlet/AServlet? Username = smith
Then:
Both results are displayed as smith.

This is because the first user obtains the value of zhangshan during access. Later, the value of username is assigned to smith.
Because username is shared by multiple threads, the username in all requests becomes smith.

 

Avoid using global variables
The temporary variables in the method are allocated space on the stack, and each thread has its own private stack space, so they do not affect the thread security.

 

16. How to automatically load servlet
We know that servlet has a lifecycle method, init, service, and destroy. Among them, init can only be accessed once when the servlet is accessed for the first time.
If you need to enable the servlet to start automatically when the server is started, you can use load-on-startup to achieve this. We can use the init method to call it and observe it.

Load-on-startup is the servlet configuration node in the web. xml file.

Describe our scenario:
Assume that you have the following requirement:
To improve system performance, when the server starts, It queries the list of all user names from the database so that they can be directly used on other pages without the need to query from the database. How can this problem be achieved?
A. ServletContextListener can automatically execute this method when the server is started.
B. You can use a servlet and define load-on-startup so that it can automatically execute the method when the server starts.

You can use <load-on-startup> 1 </load-on-startup> to specify the server loading sequence.


Instance code:

/*** Initialization of the servlet. <br> ** @ throws ServletException if an error occure * This method is accessed when the servlet is loaded * here, we start the server and automatically load a piece of data, data Cache effect */public void init () throws ServletException {// Put your code hereList <String> list = new ArrayList <String> (); list. add ("WARD"); list. add ("JONES"); list. add ("JAMES"); this. getServletContext (). setAttribute ("datalist", list );}

 

Configuration File Settings:

<servlet><servlet-name>DataCacheServlet</servlet-name><servlet-class>com.sun.demo.DataCacheServlet</servlet-class><load-on-startup>1</load-on-startup></servlet>

 

 

 

Note: What we have tried every day and every action is the flickering starlight in the vast night sky,

Someone is standing in a corner and shining with your eyes!

 

 

 

 

 

 

 

 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.