当前位置:网站首页>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 .
边栏推荐
- Function declaration and call of 17 generator
- 【Proteus仿真】Arduino UNO+PCF8574+LCD1602+MPX4250电子秤
- [graph theory] - bipartite graph
- Actual combat | multiple intranet penetration through Viper
- Object structure diagram, which can quickly illustrate the internal structure of an object
- Win10 view my Ini path
- Separate use of alertmanager alarms and use of Prometheus configuration alarm rules
- Automatically add watermark to screenshot
- ICer技能02makefile脚本自跑vcs仿真
- How to make social media the driving force of cross-border e-commerce? This independent station tool cannot be missed!
猜你喜欢

Install and run mongodb under win10

Do280openshift command and troubleshooting -- common troubleshooting and chapter experiments

ICer技能03Design Compile

GNSS速度解算的三种方法

rtklib新版本2.4.3 b34测试对比

Abnova fluorescent dye 555-c3 maleimide scheme

2020:VL-BERT: Pre-training of generic visual-linguistic representation

强推,软件测试快速入门,一看就会

Mini Homer——几百块钱也能搞到一台远距离图数传链路?

Learn to draw Er graph in an article
随机推荐
prometheus、influxdb2.2安装及flume_export下载编译使用
Kail infiltration basic literacy basic command
Shadertoy基础教学02、画笑脸
Separate use of alertmanager alarms and use of Prometheus configuration alarm rules
Metadata management Apache Atlas Compilation (embedded) deployment and various error records encountered
UI自动化定位利器-xpath实战
dolphinscheduler 2.0.5 任务测试(spark task)报错:Container exited with a non-zero exit code 1
Chrome debugging tips
【图像融合】基于非凸罚分的稀疏正则化实现图像融合附matlab代码
rtklib2.4.3 b34的一个与编译器有关的bug
395. redundant path
Abnova blood total nucleic acid purification kit protocol
微信小程序:星际旅行飞船乘坐票制作生成
Talk about the composite pattern in C #
[paper reading] semi supervised learning with ladder networks
This markdown artifact will be charged!
How to use data to tell a wonderful story?
传统意义上的互联网式的平台或将不复存在,一个融合的产业特质和互联网特质的全新产业
rtklib2.4.3 b34 单点定位的一个bug
Meituan's good article: understand swift, Objective-C and the mixing mechanism from the perspective of precompiling