当前位置:网站首页>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
边栏推荐
- [sword finger offer] interview question 41: median in data flow - large and small heap implementation
- It can carry 100 people! Musk releases the strongest "starship" in history! Go to Mars as early as next year!
- Content ambiguity occurs when using transform:translate()
- 判断数据的精确类型
- centos yum方式安装mysql
- Samsung closes its last mobile phone factory in China
- 测试新手学习宝典(有思路有想法)
- 微信小程序个人号开通流量主
- Mapreduce实例(一):WordCount
- Paper_Book
猜你喜欢

flume增量采集mysql数据到kafka

Common tool classes under JUC package

openwrt 增加RTC(MCP7940 I2C总线)驱动详解

Excel extract duplicates

QT (VI) value and string conversion

Nacos

Six capabilities of test and development

Content ambiguity occurs when using transform:translate()

centos上mysql5.7主从热备设置

Single machine high concurrency model design
随机推荐
[sword finger offer] interview question 56-i: the number of numbers in the array I
Openwrt增加对 sd card 支持
flume增量采集mysql数据到kafka
Web test learning notes 01
Makefile specifies the path of the library file loaded when the program runs
[sword finger offer] interview question 49: ugly number
Vant UI toast and dialog use
[sword finger offer] interview question 53- Ⅱ: missing numbers in 0 ~ n-1 - binary search
Openwrt new platform compilation
Brief description of tenant and multi tenant concepts in cloud management platform
A powerful web vulnerability scanning and verification tool (vulmap)
JWT简介
百度图片复制图片地址
Solve the compilation warning of multiple folders with duplicate names under the openwrt package directory (call subdir function)
Text capture picture (Wallpaper of Nezha's demon child coming to the world)
项目优化个人感悟
Easy to understand, distinguish between ++i and I++
Mapreduce实例(三):数据去重
Coding technique - Global log switch
Clickhouse 20.x distributed table testing and chproxy deployment (II)