当前位置:网站首页>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 .
边栏推荐
猜你喜欢

ICER skills 03design compile

Wechat applet example development: run

微信小程序:微信也可以发闪照了闪照制作生成微信小程序源码下载,自定义闪照时间

What are the types of independent station chat robots? How to quickly create your own free chat robot? It only takes 3 seconds!

微信小程序:星际旅行飞船乘坐票制作生成

Icer Skill 02makefile script Running VCS Simulation

Emergency response HW review

teqc进行GNSS数据质量分析时生成的s文件介绍

How to make social media the driving force of cross-border e-commerce? This independent station tool cannot be missed!

Abnova fluorescent dye 555-c3 maleimide scheme
随机推荐
Shadertoy基础教学02、画笑脸
1183. electricity
How to make social media the driving force of cross-border e-commerce? This independent station tool cannot be missed!
Dolphin scheduler 2.0.5 task test (spark task) reported an error: container exited with a non zero exit code 1
Apache atlas quick start
Thinkphp6 linked table query without associated ID (2 tables) is mainly the application of select
Meituan's good article: understand swift, Objective-C and the mixing mechanism from the perspective of precompiling
Official download and installation of QT and QT vs tools plug-ins
Metadata management Apache Atlas Compilation (embedded) deployment and various error records encountered
Abnova liquidcell negative enrichment cell separation and recovery system
美团好文:从预编译的角度理解Swift与Objective-C及混编机制
Go learning record II (window)
What are the types of independent station chat robots? How to quickly create your own free chat robot? It only takes 3 seconds!
Separate use of alertmanager alarms and use of Prometheus configuration alarm rules
Learn to draw Er graph in an article
With the arrival of intelligent voice era, who is defining AI in the new era?
396. mine site construction
Composer by installation laravel
centos7部署docker,安装mysql
【图像融合】基于非凸罚分的稀疏正则化实现图像融合附matlab代码