#IDEA 小技巧

  • alt按住移动鼠标可以多行编辑。
  • cmd + n可以快速创建构造器(自行选择参数)或者重写继承方法。

#从流中获取 properties

新建了一个Maven Module,从archetype中创建的。

Maven Module截图

#创建 properties 文件

文件路径为:servlet-02/src/main/resources/

文件名:db.properties

1
2
username=root
password=123456

#创建 class

文件路径为:servlet-02/src/main/java/

包名为:xyz.onns.servlet

文件名:TestResourceStream.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
package xyz.onns.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Properties;

public class TestResourceStream extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
InputStream resourceAsStream = this.getServletContext().getResourceAsStream("/WEB-INF/classes/db.properties");
Properties properties = new Properties();
properties.load(resourceAsStream);
String username = properties.getProperty("username");
String password = properties.getProperty("password");
String maybenull = properties.getProperty("maybenull");
System.out.println("TestResourceStream");
resp.setHeader("Content-Type", "text/html;charset=utf-8");

PrintWriter writer = resp.getWriter();
writer.print("Success!成功了!");
writer.print("<br/>");
writer.print(username);
writer.print(password);
writer.print(maybenull);
}

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}

#创建路由

文件路径为:servlet-02/src/main/webapp/WEB-INF/

文件名:web.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
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">

<servlet>
<servlet-name>TestResourceStream</servlet-name>
<servlet-class>xyz.onns.servlet.TestResourceStream</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>TestResourceStream</servlet-name>
<url-pattern>/testr</url-pattern>
</servlet-mapping>

</web-app>

#小结

如果先写这句话:

1
PrintWriter writer = resp.getWriter();

再写这句话:

1
resp.setHeader("Content-Type", "text/html;charset=utf-8");

在处理中文的时候也还是会乱码,大概在创建PrintWriter对象的时候就已经把相关参数传过去了吧。

#相关链接