当前位置:网站首页>Servlet knowledge points
Servlet knowledge points
2022-07-01 19:48:00 【Dragon_ qing】
Servlet
1. brief introduction
servlet Interface sun The company has two default implementation classes :HttpServlet,GenericServlet
- Namely sun Company development trends web A technology of
- sun In these API Provides an interface called :Servlet, If you want to develop a servlet Program , Only two small steps need to be completed :
- Write a class , Realization servlet Interface
- Deploy to web Server
To achieve Servlet Interface Java The program is called ,Servlet
2.HelloServlet
Construct a Maven project , Delete the inside src Catalog , Build... In the project module;
About Maven Understanding of father son project :
There will be
<modules> <module>servlet-01</module> </modules>
The subproject will have
<parent> <artifactId>javaweb-02-servlet</artifactId> <groupId>org.example</groupId> <version>1.0-SNAPSHOT</version> </parent>
In the parent project java Subprojects can directly use
son extends father
Maven Environmental optimization
- modify web.xml For the latest
webapp
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" version="4.0">
</web-app>
take Maven The structure of the building is complete
web Project dependence
servlet and jsp
pom.xml
<!-- https://mvnrepository.com/artifact/javax.servlet.jsp/javax.servlet.jsp-api --> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>javax.servlet.jsp-api</artifactId> <version>2.3.3</version> </dependency> <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>4.0.1</version> </dependency>
Write a Servlet Program
Write a common class
Realization Servlet Interface , Direct inheritance HttpServlet
public class HelloServlet extends HttpServlet { // because get perhaps post It's just the different ways that requests are implemented , Can call each other , The business logic is the same @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { PrintWriter writer = resp.getWriter(); // Response flow writer.println("hello,Servlet"); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { super.doPost(req, resp); } }
To write Servlet Mapping
Why do I need to map : What we're writing is java Program , But access through a browser , The browser needs to connect web The server , So we need to web Registration in the service we wrote Servlet, Also need to give him a browser can access the path ;
<!-- register servlet--> <servlet> <servlet-name>hello</servlet-name> <servlet-class>com.wan.servlet.HelloServlet</servlet-class> </servlet> <!-- servlet The request path for --> <servlet-mapping> <servlet-name>hello</servlet-name> <url-pattern>hello</url-pattern> </servlet-mapping>
To configure Tomcat
Be careful : Just configure the project publishing path
3.Servlet principle
servlet Yes, there is web Server calls ,web The server will provide a response after receiving the browser request ;
4.Mapping problem
One Servlet You can specify a mapping path
<servlet-mapping> <servlet-name>hello</servlet-name> <url-pattern>/hello</url-pattern> </servlet-mapping>
One Servlet Multiple mapping paths can be specified
<servlet-mapping> <servlet-name>hello</servlet-name> <url-pattern>/hello1</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>hello</servlet-name> <url-pattern>/hello2</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>hello</servlet-name> <url-pattern>/hello3</url-pattern> </servlet-mapping>
One Servlet You can specify a generic mapping path
<servlet-mapping> <servlet-name>hello</servlet-name> <url-pattern>/hello/*</url-pattern> </servlet-mapping>
Specify some suffixes or prefixes and so on ...
<!--* The path of project mapping cannot be added in the front --> <servlet-mapping> <servlet-name>hello</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping>
Priority questions
The inherent mapping path is specified with the highest priority , If it cannot be found, it will follow the default request path ;
5.ServletContext
web When the container starts , It will web Programs create a corresponding servletContext object , It represents the present web application ;
1. Shared data
eg:
Add attribute
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext context = this.getServletContext();
String username = " Zhang San ";
context.setAttribute("username", username); // Key value pair form input
}
get attribute :
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext context = this.getServletContext();
String name = (String) context.getAttribute("username");
resp.setCharacterEncoding("utf-8");
resp.setContentType("text/html");
resp.getWriter().println(" full name "+name);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doGet(req, resp);
}
To configure
<servlet>
<servlet-name>hello</servlet-name>
<servlet-class>com.wan.servlet.HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>getc</servlet-name>
<servlet-class>com.wan.servlet.GetServletContext</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>getc</servlet-name>
<url-pattern>/getc</url-pattern>
</servlet-mapping>
2. Get initialization parameters
xml Set initialization parameters in
eg: Database parameters
<context-param>
<param-name>url</param-name>
<param-value>jdbc:mysql:http://localhost:3306/mybatis</param-value>
</context-param>
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String url = this.getServletContext().getInitParameter("url");
resp.getWriter().println(url);
}
3. Request forwarding
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext context = this.getServletContext();
System.out.println(" Into the RequestD");
context.getRequestDispatcher("/getp").forward(req, resp); // call forward Implement request forwarding ;
}
4. Read resource file
Properties
stay java New under the directory properties( Pay attention to the configuration pom.xml file , Or maybe maven Cannot export properties file )
pom.xml The configuration file
<!-- stay build Middle configuration resources, To prevent our resource export failure -->
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<includes>**/*.properties</includes>
<includes>**/*.xml</includes>
</includes>
<filtering>false</filtering>
</resource>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
</build>
- stay resource Under the new properties
Need a file stream ;
username = root
password = 123456
java Code
public class PropertiesServlet extends HelloServlet{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
InputStream is = getServletContext().getResourceAsStream("/WEB-INF/classes/db.properties");
Properties prop = new Properties();
prop.load(is);
String usr = prop.getProperty("username");
String pwd = prop.getProperty("password");
resp.getWriter().println(usr+":"+pwd);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doGet(req,resp);
}
}
web.xml
<servlet>
<servlet-name>ps</servlet-name>
<servlet-class>com.wan.servlet.PropertiesServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ps</servlet-name>
<url-pattern>/ps</url-pattern>
</servlet-mapping>
Access test
6.HttpServletRequest
HttpServletRequest Requests on behalf of clients , User pass Http Protocol access server ,HTTP All information in the request will be encapsulated in HttpServletRequest, adopt HttpServletRequest The method in , Get all the information from the client ;
1. Get the parameters passed by the front end
index.jsp Home page
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@page isELIgnored="false"%>
<html>
<head>
<title> Sign in </title>
</head>
<body>
<div style="text-align: center">
<form action="${pageContext.request.contextPath}/login" method="post">
<p> user name :<input type="text" name="username"></p>
<p> password :<input type="password" name="password"></p>
<p>
hobby :
<input type="checkbox" name="hobbys" value=" Code "> Code
<input type="checkbox" name="hobbys" value=" The movie "> The movie
<input type="checkbox" name="hobbys" value=" Sing a song "> Sing a song
</p>
<input type="submit" value=" Sign in ">
</form>
</div>
</body>
</html>
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("hello");
req.setCharacterEncoding("utf-8");
resp.setCharacterEncoding("utf-8");
String password = req.getParameter("password");
String username = req.getParameter("username");
String[] hobbys = req.getParameterValues("hobbys");
System.out.println("==========================");
System.out.println(" user name :"+username);
System.out.println(" password :"+password);
System.out.println(" hobby :"+ Arrays.toString(hobbys));
System.out.println("==========================");
// Request forwarding
req.getRequestDispatcher("success.jsp").forward(req,resp);
}
7.HttpServletResponse
web The server received... From the client http request , In response to this request , Create one for each request HttpServletRequest object , Represents a response HttpServletResponse;
- If you want to get the parameters requested by the client : look for HttpServletRequest
- If you want to respond to some information to the client : look for HttpServletResponse
1. Simple classification
Responsible for sending data to the browser
ServletOutputStream getOutputStream() throws IOException; PrintWriter getWriter() throws IOException;
The method responsible for sending the response header to the browser
void setCharacterEncoding(String var1);
void setContentLength(int var1);
void setContentLengthLong(long var1);
void setContentType(String var1);
void setDateHeader(String var1, long var2);
void addDateHeader(String var1, long var2);
void setHeader(String var1, String var2);
void addHeader(String var1, String var2);
void setIntHeader(String var1, int var2);
void addIntHeader(String var1, int var2);
void setStatus(int var1);
The status code of the response
int SC_CONTINUE = 100;
int SC_SWITCHING_PROTOCOLS = 101;
int SC_OK = 200;
int SC_CREATED = 201;
int SC_ACCEPTED = 202;
int SC_NON_AUTHORITATIVE_INFORMATION = 203;
int SC_NO_CONTENT = 204;
int SC_RESET_CONTENT = 205;
int SC_PARTIAL_CONTENT = 206;
int SC_MULTIPLE_CHOICES = 300;
int SC_MOVED_PERMANENTLY = 301;
int SC_MOVED_TEMPORARILY = 302;
int SC_FOUND = 302;
int SC_SEE_OTHER = 303;
int SC_NOT_MODIFIED = 304;
int SC_USE_PROXY = 305;
int SC_TEMPORARY_REDIRECT = 307;
int SC_BAD_REQUEST = 400;
int SC_UNAUTHORIZED = 401;
int SC_PAYMENT_REQUIRED = 402;
int SC_FORBIDDEN = 403;
int SC_NOT_FOUND = 404;
int SC_METHOD_NOT_ALLOWED = 405;
int SC_NOT_ACCEPTABLE = 406;
int SC_PROXY_AUTHENTICATION_REQUIRED = 407;
int SC_REQUEST_TIMEOUT = 408;
int SC_CONFLICT = 409;
int SC_GONE = 410;
int SC_LENGTH_REQUIRED = 411;
int SC_PRECONDITION_FAILED = 412;
int SC_REQUEST_ENTITY_TOO_LARGE = 413;
int SC_REQUEST_URI_TOO_LONG = 414;
int SC_UNSUPPORTED_MEDIA_TYPE = 415;
int SC_REQUESTED_RANGE_NOT_SATISFIABLE = 416;
int SC_EXPECTATION_FAILED = 417;
int SC_INTERNAL_SERVER_ERROR = 500;
int SC_NOT_IMPLEMENTED = 501;
int SC_BAD_GATEWAY = 502;
int SC_SERVICE_UNAVAILABLE = 503;
int SC_GATEWAY_TIMEOUT = 504;
int SC_HTTP_VERSION_NOT_SUPPORTED = 505;
It's enough to remember the general
200: Request response successful
3**: request redirections
404: Resource not found
- Resource does not exist
5XX: Server code error 500 502: Gateway error
2. Download the file
Output message to browser
Download the file
1. To get the path of the downloaded file
2. Download file name
3. The setting method enables the browser to support downloading what we need
4. Get the input stream of the download file
5. Create buffer
6. obtain outputstream object
7. take FileOut Ordinary Stream Stream write to buffer buffer
8. Use OutPutStream Output the data in the buffer to the client
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 1. To get the path of the downloaded file
String realPath = "D:\\code\\javaweb\\javaweb-02-servlet\\response\\src\\main\\resources\\ tencent qqicon.png";
//String realPath = this.getServletContext().getRealPath("/ tencent qqicon.png"); This is the wrong path to find
System.out.println(" Download file path :"+realPath);
// 2. Download file name
String filename = realPath.substring(realPath.lastIndexOf("\\") + 1);
System.out.println("filename="+filename);
// 3. The setting method enables the browser to support downloading what we need , Chinese file name URLEncoder.encode code , Otherwise, it may be garbled
resp.setHeader("Content-disposition","attachment;filename="+ URLEncoder.encode(filename,"utf-8"));
// 4. Get the input stream of the download file
FileInputStream in = new FileInputStream(realPath);
// 5. Create buffer
int len = 0;
byte[] buffer = new byte[1024];
// 6. obtain outputstream object
ServletOutputStream out = resp.getOutputStream();
// 7. take FileOutStream Stream write to buffer buffer
while((len = in.read(buffer))!=-1){
// 8. Use OutPutStream Output the data in the buffer to the client
out.write(buffer,0,len);
}
in.close();
out.close();
}
3. Verification code function
How to get the verification code ?
- The front-end implementation
- The backend implementation , use java Picture class of , Produce a picture
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// browser 3 Refresh every second
resp.setHeader("refresh","3");
// Create an image in memory
BufferedImage image = new BufferedImage(80, 20, BufferedImage.TYPE_INT_RGB);
Graphics2D g = (Graphics2D) image.getGraphics();
// Set the picture background color
g.setColor(Color.white);
g.fillRect(0,0,80,20);
g.setColor(Color.BLUE);
g.setFont(new Font(null,Font.BOLD,20));
g.drawString(makeNum(),0,20);
// Tell the browser , This request is opened in the form of a picture
resp.setContentType("image/jpeg");
// There is a cache on the site , Don't let the browser cache
resp.setDateHeader("expires",-1);
resp.setHeader("Cache-control","no-cache");
resp.setHeader("Pragma","no-cache");
// Return the image to the browser
ImageIO.write(image, "jpg", resp.getOutputStream());
}
/** * Generate random number * @return */
private String makeNum(){
Random random = new Random();
String num = random.nextInt(9999999) + "";
StringBuffer sb = new StringBuffer();
for (int i = 0; i < 7-num.length(); i++) {
sb.append("0");
}
num = sb.toString()+num;
return num;
}
4. Implement redirection
One web After the resource receives a client request , He will tell the client to access another web resources C, This process is called redirection
void sendRedirect(String var1) throws IOException;
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
/* resp.setHeader("Location","/response_Web_exploded/image"); resp.setStatus(302); */
resp.sendRedirect("/response_Web_exploded/image");
}
The difference between redirection and forwarding :
The same thing :
- Page will jump
Difference :
- When the request is forwarded ,url Will change 307
- When redirecting ,url And then change 302
Case study
demand : Redirect after login
RequestTest.java
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println(" Get into requestTest class !");
String username = req.getParameter("username");
String password = req.getParameter("password");
System.out.println(username+":"+password);
resp.sendRedirect("/response_Web_exploded/success.jsp");
}
web.xml
<servlet>
<servlet-name>request</servlet-name>
<servlet-class>RequestTest</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>request</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
index.jsp
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<h2>Hello World!</h2>
<%@ page pageEncoding="UTF-8" %>
<form action="${pageContext.request.contextPath}/login" method="get">
<p> user name :<input type="text" name="username"></p>
<p> password :<input type="password" name="password"><br></p>
<input type="submit">
</form>
</body>
</html>
success.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>success</title>
</head>
<body>
<h1>congratulation</h1>
</body>
</html>
边栏推荐
- Graduation season | Huawei experts teach the interview secret: how to get a high paying offer from a large factory?
- SQL 入门计划-1-选择
- [SQL optimization] the difference between with as and temporary tables
- 118. 杨辉三角
- 面试题篇一
- PowerDesigner设计Name和Comment 替换
- Use the uni app demo provided by Huanxin to quickly realize one-on-one chat
- ffmpeg AVFrame 转 cv::Mat
- DS Transunet:用于医学图像分割的双Swin-Transformer U-Net
- 博途V16 获取系统时间转换成字符串
猜你喜欢
[research materials] iResearch tide Watching: seven major trends in the clothing industry - Download attached
HLS4ML报错The board_part definition was not found for tul.com.tw:pynq-z2:part0:1.0.
1592 例题1 国王(Sgu223 LOJ10170 LUOGU1896 提高+/省选-) 暴力思考 状压DP 01背包
Technology T3 domestic platform! Successfully equipped with "Yihui domestic real-time system sylixos"
Axure does not display catalogs
Why must we move from Devops to bizdevops?
Use the uni app demo provided by Huanxin to quickly realize one-on-one chat
毕业季 | 华为专家亲授面试秘诀:如何拿到大厂高薪offer?
大厂音视频职位面试题目--今日头条
[research data] observation on the differences of health preservation concepts among people in 2022 - Download attached
随机推荐
Why has instagram changed from a content sharing platform to a marketing tool? How do independent sellers use this tool?
集合对象值改变NULL值对象
一文读懂C语言中的结构体
GB28181的NAT穿透
Test self-study people must see: how to find test items in software testing?
win10下使用msys+vs2019编译ffmpeg源码
[research materials] national second-hand housing market monthly report January 2022 - Download attached
1592 例题1 国王(Sgu223 LOJ10170 LUOGU1896 提高+/省选-) 暴力思考 状压DP 01背包
Using win7 vulnerability to crack the system login password
再回顾集合容器
Time series analysis using kibana timelion
Define dichotomy lookup
[research data] observation on the differences of health preservation concepts among people in 2022 - Download attached
HLS4ML进入方法
墨天轮沙龙 | 清华乔嘉林:Apache IoTDB,源于清华,建设开源生态之路
Interview questions for audio and video positions in Dachang -- today's headline
P2433 【深基1-2】小学数学 N 合一
Is Dao safe? Build finance encountered a malicious governance takeover and was looted!
Crunch简介、安装,使用Crunch制作密码字典
[research materials] iResearch tide Watching: seven major trends in the clothing industry - Download attached