Since jsp and servlet are equivalent, built-in objects can be used in jsp, so can also be used in servlet.
1. Get the out object
You can use the following code to obtain the out object:
Import java. io. PrintWriter;
...
Public void doGet (HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
PrintWriter out = reponse. getWriter ();
}
...
However, by default, the out object cannot print Chinese characters. This is because the out output stream has Chinese characters but no encoding is set. To solve this problem, you can
Change the doGet code:
Response. setContentType ("text/html; charset = gb2312 ");
PrintWriter out = response. getWriter ();
// Use the out object
2. Get the request and reponse objects
...
Public void doGet (HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
// Use the reques parameter as the request object
// Use the reponse parameter as response
}
...
3. Get the session object
The session Object corresponds to the HttpSession interface. In Servlet, it can be obtained through the following code:
Import javax. servlet. http. HttpSession;
...
Public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request. getSession ();
// Use session as a session object
}
...
4. Obtain the application Object
The application Object corresponds to the ServletContex interface, which can be obtained through the following code in Servlet:
Import javax. servlet. ServletContext;
...
Public void doGet (HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
ServletContext application = this. getServletContext ();
// Use application as an application Object
}
...
It is worth mentioning that you can use application to implement server redirection. Due to the homogeneity of servlet and jsp, two types of servlet internal jump are commonly used:
(1) redirection (corresponding to sendRedirect in jsp)
Response. sendRedirect ("URL address ");
(2) server redirection (corresponding to forward in jsp)
ServletContext application = this. getServletContext ();
RequestDispatcher rd = application. getRequestDispatcher ("url address ");
Rd. forward (request, response );
The two redirection methods in servlet are equivalent to those mentioned in jsp. Note: in both cases, the url address is written differently. In the first type
For the path, you must write the virtual directory and directory in it, for example, "/Proj09/page. jsp". In the second method, you do not need to write the virtual path root directory in it.
Area, such as "/page. jsp"