当前位置:网站首页>Servlet self study notes
Servlet self study notes
2022-06-23 05:08:00 【Don't want to be a programmer】
To write Servlet Mapping
Why do I need to map : What we're writing is Java Program , But access it through a browser , The browser needs to connect web The server , So we need to be able to web Register what we wrote in the server servlet,
You also need to give him a path that the browser can access ;
Mapping problem
1、 One servlet You can specify a mapping path
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
2、 One servlet Multiple mapping paths can be specified
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
<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>
3、 One servlet You can specify a generic mapping path
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/hello/*</url-pattern>
</servlet-mapping>
4、 Specify some suffixes or prefixes
<!-- You can customize suffixes to implement request mapping Be careful ,* The path of project mapping cannot be added in the front , As long as .wanaei The ending is OK -->
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>*.wanaei</url-pattern>
</servlet-mapping>
web.xml Head
<?xml version="1.0" encoding="UTF-8"?>
<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" metadata-complete="true">
</web-app>
servletContext
gitee Code
web When the container starts , It will web Programs create a corresponding ServletContext object , It represents the present web application ;
- Shared data
I'm here servlet Data stored in , It can be in another servlet Get in the - Get configuration parameters
<!-- Configure some web Application initialization parameters -->
<context-param>
<param-name>url</param-name>
<param-value>jdbc:mysql://localhost:3306/mybatis</param-value>
</context-param>
- Request forwarding
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext context = this.getServletContext();
// RequestDispatcher requestDispatcher = context.getRequestDispatcher("/gp");// Forward to request path
// requestDispatcher.forward(req,resp);
context.getRequestDispatcher("/gp").forward(req,resp);
}
- Read resource file – properties class
- stay java New under the directory properties
- stay resources New under the directory properties
Find out : Are packaged under the unified path :classes, We commonly call this path classpath
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
InputStream is = this.getServletContext().getResourceAsStream("/WEB-INF/classes/db.properties");
Properties pro = new Properties();
pro.load(is);
String username = pro.getProperty("username");
String password = pro.getProperty("password");
resp.getWriter().print(username+":"+password);
}
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 HttpServletResquest
- If you want to respond to some information to the client : look for HttpServletResponse
1、 Simple classification
Responsible for sending data to the browser
public ServletOutputStream getOutputStream() throws IOException; public PrintWriter getWriter() throws IOException;- The method responsible for sending some response headers to the browser
2、 Simple application
1、 Output message to browser
2、 Download the file
- To get the downloaded file path
- What is the name of the downloaded file
- Set up a way to make the browser support downloading what we need
- Get the download file input stream
- Create buffer
- obtain OutputStream object
- take FileOutputStream Stream write to buffer buffer
- Use OutputStream Output the data in the buffer to the client
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// - To get the downloaded file path
// String realPath = this.getServletContext().getRealPath("F:\\my_project\\JavaToGiteeUp\\javaWebPro\\response\\src\\main\\resources\\1.png");
String realPath = "F:\\my_project\\JavaToGiteeUp\\javaWebPro\\response\\src\\main\\resources\\1.png";
// - What is the name of the downloaded file
String filename = realPath.substring(realPath.lastIndexOf("\\") + 1);
// - Set up a way to make the browser support downloading what we need
resp.setHeader("Content-disposition","attachment;filename="+filename);// You can search web Download the header information of the file
// - Get the download file input stream
FileInputStream in = new FileInputStream(realPath);
// - Create buffer
int len = 0;
byte[] buffer = new byte[1024];
// - obtain OutputStream object
ServletOutputStream out = resp.getOutputStream();
// - take FileOutputStream Stream write to buffer buffer , Use OutputStream Output the data in the buffer to the client
while((len=in.read(buffer))>0){
out.write(buffer,0,len);
}
in.close();
out.close();
}
3、 Verification code function
Verify how it came from ?
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// How to make the browser 3 Refresh every second
resp.setHeader("refresh","3");
// Create an image in memory
BufferedImage bufferedImage = new BufferedImage(80,20, BufferedImage.TYPE_INT_RGB);
Graphics2D graphics = (Graphics2D)bufferedImage.getGraphics();// pen
// Set the background color of the picture
graphics.setColor(Color.WHITE);
graphics.fillRect(0,0,80,20);
// Write data for pictures
graphics.setColor(Color.BLUE);
graphics.setFont(new Font(null,Font.BOLD,20));
graphics.drawString(makeNum(),0,20);
// Tell the browser , This request is opened in the form of a picture
resp.setContentType("image/png");
// There is a cache on the site , Don't let the browser cache
resp.setDateHeader("expirse",-1);
resp.setHeader("Cache-Control","no-cache");
resp.setHeader("pragma","no-cache");
// Write the picture to the browser
boolean write = ImageIO.write(bufferedImage, "png", resp.getOutputStream());
}
// Generate random number
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 , It tells the client to access another web resources , This process is called redirection
resp.sendRedirect("/resp/draw");
Common scenes :
- The user login
Common interview questions : Please talk about the difference between redirection and forwarding ?
The same thing :
- All pages will jump
Difference
- When the request is forwarded ,url There will be no change
- When redirecting ,url The address bar will change
HttpServletRequest
HttpServletRequest Represents the request of the client , User pass Http Protocol problem access server ,HTTP All information in the request will be encapsulated in HttpServletRequest, Through this HttpServletRequest Method , Get all the information from the client ;
1、 Request forwarding
Focus on the first one 、 The fourth one .
边栏推荐
- Go learning record II (window)
- Banner banner
- Cloud native database is in full swing, and the future can be expected
- 【Mac】安全性与隐私中没有任何来源选项
- Experience of Tencent cloud installed by Kali
- Course design C for freshmen -- clothing management system
- Is data scientist a promising profession?
- 美团好文:从预编译的角度理解Swift与Objective-C及混编机制
- Thesis reading_ Relation extraction_ CASREL
- teqc进行GNSS数据质量分析时生成的s文件介绍
猜你喜欢

Receive incoming files and download (simple usage) a tag

微信小程序;AI智能配音助手

ICER skill 02makefile script self running VCs simulation

dolphinscheduler 1.2.1 数据迁移到 dolphinscheduler 2.0.5方法及迁移后数据测试记录

MVC三层架构

Separate use of alertmanager alarms and use of Prometheus configuration alarm rules

Abnova fluorescent dye 510-m streptavidin scheme

使用teqcplot对teqc 质量分析结果进行可视化展示

超越芯片和AI,硬科技资本为什么越来越“硬核”?

AlertManager告警的单独使用及prometheus配置告警规则使用
随机推荐
【毕业季_进击的技术er】送别过去两年迷茫的自己。重整旗鼓,大三我来啦
PRCS-1016 : Failed to resolve Single Client Access Name
MVVM has become history, and Google has fully turned to MVI
dolphinscheduler海豚调度升级代码改造-UpgradeDolphinScheduler
Emergency response HW review
Flask基础:环境搭建+配置+URL与试图之间的映射+重定向+数据库连接
8年经验之谈:月薪3000到30000,测试工程师的变“行”记
物体结构图,快速图解物体内部结构
centos7安装postgresql8.2.15及存储过程创建
Getting started with the shutter AppBar
怎样利用数据讲一个精彩故事?
Shadertoy基础教学02、画笑脸
单行或多行文本溢出,省略号代替
Li Kou today's question 513 Find the value in the lower left corner of the tree
【图像融合】基于非凸罚分的稀疏正则化实现图像融合附matlab代码
使用teqcplot对teqc 质量分析结果进行可视化展示
Metadata management Apache Atlas Compilation (embedded) deployment and various error records encountered
How to make social media the driving force of cross-border e-commerce? This independent station tool cannot be missed!
【图论】—— 二分图
功能测试人员如何做到花一个月的时间进阶自动化软件测试工程师