当前位置:网站首页>Servlet basic knowledge points
Servlet basic knowledge points
2022-07-27 16:14:00 【w ͏ l ͏ j ͏】
notes : This article is only for personal learning records , If there is a mistake , Welcome to point out , thank you
Servlet
What is? Servlet?
Java Servlet Is running on the Web A program on a server or application server , It's as coming from Web Browser or something HTTP Client requests and HTTP The middle tier between databases or applications on the server .
Use Servlet, You can collect user input from web forms , Render records from databases or other sources , You can also create web pages dynamically .
Sevlet characteristic
- Better performance .
- Servlet stay Web Execute in the address space of the server . So it doesn't have to create a separate process to handle every client request .
- Servlet It's platform independent , Because they use Java Compiling .
- On the server Java The security manager implements a series of restrictions , To protect resources on the server computer . therefore ,Servlet It's believable .
- Java All the functions of the class library are right Servlet It's all available . It can go through sockets and RMI Mechanism and applets、 Database or other software to interact .
Servlet framework

servlet be used for HTTP And the middle tier of the database , Used to connect to HTTP Servers and databases .
Servlet Mission
Read the client ( browser ) Explicit data sent . This includes HTML Forms , Or it could be from applet Or custom HTTP Client forms .
Read the client ( browser ) Sending implicit HTTP Request data . This includes cookies、 Media types and compression formats that browsers can understand .
Process data and generate results . This process may require access to the database , perform RMI or CORBA call , call Web service , Or directly calculate the corresponding response .
Send explicit data ( The document ) To client ( browser ). The format of the document can be varied , Include text files (HTML or XML)、 Binary (GIF Images )、Excel etc. .
Send implicit HTTP Response to client ( browser ). This includes telling the browser or other client the type of document returned ( for example HTML), Set up cookies And cache parameters , And other similar tasks .
Servlet package
Java Servlet Is running with support Java Servlet The interpreter of the specification web On the server Java class .Servlet have access to javax.servlet and javax.servlet.http Package creation , It is Java Standard components of the Enterprise Edition ,Java The enterprise edition supports large-scale development projects Java An extended version of the class library . These classes implement Java Servlet and JSP standard . In writing this tutorial , The corresponding versions of the two are Java Servlet 2.5 and JSP 2.1.
Servlet Life cycle
Servlet Life cycle can be defined as the whole process from creation to destruction . Here are Servlet Follow the process :
- Servlet Call after initialization init () Method .
- Servlet call service() Method to handle client requests .
- Servlet Call before destruction destroy() Method .
- Last ,Servlet By JVM Garbage collector for garbage collection .
init Method is designed to be called only once . It was created for the first time Servlet When called , It is not called at every subsequent user request .
service() Method is the main way to perform practical tasks .
service() Method is called by the container ,service Method is called when appropriate doGet、doPost、doPut、doDelete Other methods .
Architecture diagram

Servlet example
- newly build web project ( Deploy the project to web Server )
- New package , And create a new ordinary under the package java project
- Inherit HttpServer



Servlet The form data
get,post
servlet Common classes
HttpServletRequest
Cookie[] getCookies() Returns an array , Contains all of the Cookie object .
Enumeration getAttributeNames() Returns an enumeration , Contains the property names available for the request .
Enumeration getHeaderNames() Returns an enumeration , Include all headers included in the request .
Object getAttribute(String name) Returns the value of a named property as an object , If no attribute with the given name exists , Then return to null.
Request to forward the small case (HttpServletRequest)
package com.wanglj.servlet;
import java.io.IOException;
import javax.print.attribute.standard.JobOriginatingUserName;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
@WebServlet("/ser05")
public class Servlet05 extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
// Set encoding
req.setCharacterEncoding("utf-8");
String userNameString = req.getParameter("name");
String pwdString = req.getParameter("pwd");
// System.out.println(" user name :"+userNameString);
// System.out.println(" password :"+pwdString);
try {
// String comparison uses equals
if(userNameString.equals("admin") && pwdString.equals("toor")) {
System.out.println(" Login successful ");
// Set scope
// req.setAttribute("userName", userNameString);
// Remove scope
req.removeAttribute("userName");
req.getRequestDispatcher("success.jsp").forward(req, res);
}
else {
System.out.println(" Login failed ");
// Request forwarding ( Server jump , The address bar doesn't change , Request forwarding can share data , But redirection cannot share data )
// req.getRequestDispatcher(" route ").forward(req, res);
req.setAttribute("msg", " Wrong user name or password !");
req.getRequestDispatcher("failed.jsp").forward(req, res);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Insert title here</title>
</head>
<body>
<!-- Submitted to the ser05,name="para" Can be in jsp Get the submitted parameters -->
<form action="ser05">
userName:<input type="text" name="name">
password:<input type="password" name="pwd">
<button type="submit"> Sign in </button>
<!-- http://localhost:8080/ServletTest/ser05?name=wanglj&pwd=toor -->
</form>
</body>
</body>
</html>
HttpServletResponse object
The response data
getWriter() Obtain byte stream
getOutputStream() Obtain byte stream , Able to respond to any type of data
! Both cannot be used at the same time , Otherwise you may report an error
package com.wanglj.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.catalina.filters.SetCharacterEncodingFilter;
// When using a new servlet When , Reboot required tomcat The server
// getWriter() Response character
// getOutputStream() Respond to any type , Not with the above getWriter() share , Otherwise, an error will be reported
@WebServlet("/ser06")
public class Servlet06 extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// resp.setContentType("text/html");
// Chinese and English garbled code solution
// // Set the server coding format
// resp.setCharacterEncoding("UTF-8");
// // Client code
// resp.setHeader("content-type", "text/html;charset=UTF-8");
Character input stream
resp.setContentType("text/html;charset=UTF-8");
// PrintWriter writer = res.getWriter();
// writer.write("<h2>hello getWriter</h2>");
// // Refresh
// writer.flush();
// // close
// writer.close();
// Byte input stream
// When the character encoding of the server is different from that of the client , Or when Chinese is not supported , It's going to be messy
ServletOutputStream out = resp.getOutputStream();
//getBytes("utf-8") Also write the type , Otherwise, it may also cause garbled code
out.write("<h2> China </h2>".getBytes("UTF-8"));
out.flush();
out.close();
}
}
// Chinese and English garbled code solution
// The first one is
// // Set the server coding format
resp.setCharacterEncoding("UTF-8");
// // Client code
resp.setHeader("content-type", "text/html;charset=UTF-8");
The second kind :
resp.setContentType("text/html;charset=UTF-8");
out.write("<h2> China </h2>".getBytes("UTF-8"));
The difference between request forwarding and redirection
Request forwarding is a server jump , Redirection is a client jump
Request forwarding is a request , Redirection is two requests
Request forwarding can be shared request data , Redirection cannot
The request forwarding address bar does not change , The redirection address will change
Request forwarding can only jump to the resources under the current project , Redirection can be any resource ( It can span servers )
package com.wanglj.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/ser07")
public class Servlet07 extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// Redirect , You can redirect to jsp,servlet, And cross server forwarding
// resp.sendRedirect("sign.jsp");
// Request forwarding 、
// req.getRequestDispatcher("sign.jsp").forward(req, resp);
resp.sendRedirect("https://www.baidu.com/");
}
}
cookie object
meaning :
Cookie, Sometimes in the plural Cookies. The type is “ Small text files ”, It's some websites to identify users , Conduct Session Tracking data stored on the user's local terminal ), By the user client Information temporarily or permanently stored by a computer .
Create and send Cookie
// establish cookie object
Cookie cookie = new Cookie("wanglj", "123456");
// send out cookie
resp.addCookie(cookie);
// obtain cookie
req.getCookies()
private String comment; // describe
private String domain; // You can visit the Cookie Domain name of
private int maxAge = -1; // The Cookie Expiration time , The unit is in seconds , And often Expires Use it together , It can be used to calculate its effective time .Max Age If it's a positive number , Then Cookie stay Max Age Seconds later . If it's negative , When the browser is closed Cookie I.e. failure , The browser will not save the Cookie.
private boolean secure; // Whether to use SSL
package com.wanglj.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/ser07")
public class Servlet07 extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// establish cookie object
Cookie cookie = new Cookie("demo", "6473456");
// send out cookie
resp.addCookie(cookie);
// obtain cookies
Cookie[] cookies = req.getCookies();
// Traverse cookie
if(cookies != null){
for(Cookie cok:cookies) {
System.out.println(cok.getName());
System.out.println(cok.getValue());
}
}
}
}

Refer to the rookie tutorial :https://www.runoob.com/servlet/servlet-writing-filters.html
边栏推荐
猜你喜欢
随机推荐
Determine the exact type of data
Have you ever used the comma operator?
busybox login: can't execute '/bin/bash': No such file or directory 解决方法
Mapreduce实例(一):WordCount
Leetcode 226 翻转二叉树(递归)
[sword finger offer] interview question 45: arrange the array into the smallest number
DRF学习笔记(三):模型类序列化器ModelSerializer
Clickhouse 20.x distributed table testing and chproxy deployment (II)
scrapy爬虫框架
Wechat applet personal number opens traffic master
Sword finger offer 51. reverse pairs in the array
多行文本溢出打点
SQL multi table query
Mapreduce实例(二):求平均值
Content ambiguity occurs when using transform:translate()
43亿欧元现金收购欧司朗宣告失败!ams表示将继续收购
Introduction to JWT
文本截取图片(哪吒之魔童降世壁纸)
Openwrt增加对 sd card 支持
Baidu picture copy picture address








