Servlet资源共享以及Properties配置文件读取
一、Servlet资源共享
1.SetServlet
创建SetServlet类,继承HttpServlet,重写doGet方法
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String userName = "无心";
resp.setCharacterEncoding("utf-8"); // 设置编码
resp.setContentType("text/html"); // 指定HTTP响应访问的编码
resp.getWriter().print("<h1>名字设置成功</h1>");
ServletContext context = this.getServletContext();
context.setAttribute("userName",userName);
}
2.GetServlet
创建GetServlet类,继承HttpServlet,重写doGet方法
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext context = this.getServletContext();
String userName = (String) context.getAttribute("userName");
resp.setCharacterEncoding("utf-8"); // 设置编码
resp.setContentType("text/html"); // 指定HTTP响应访问的编码
PrintWriter writer = resp.getWriter();
writer.print("<H1>名字:" + userName+"</H1>");
}
3.配置web.xml
配置servlet和servlet-mapping映射
<?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">
<servlet>
<servlet-name>setc</servlet-name> <!-- servlet名称 -->
<servlet-class>com.wuxin.Servlet.SetServlet</servlet-class> <!-- servlet类具体地址 -->
</servlet>
<servlet-mapping>
<servlet-name>setc</servlet-name>
<url-pattern>/setc</url-pattern> <!-- 具体访问关键字 -->
</servlet-mapping>
<servlet>
<servlet-name>getc</servlet-name>
<servlet-class>com.wuxin.Servlet.GetServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>getc</servlet-name>
<url-pattern>/getc</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>prop</servlet-name>
<servlet-class>com.wuxin.Servlet.PropertiesServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>prop</servlet-name>
<url-pattern>/prop</url-pattern>
</servlet-mapping>
</web-app>
二、Properties配置文件读取
1.新建配置文件
在resources目录下新建**.Properties配置文件
2.读取
在java目录下新建PropertiesServlet类,继承HttpServlet,并且重写doGet方法
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setCharacterEncoding("utf-8"); // 设置编码
resp.setContentType("text/html"); // 指定HTTP响应访问的编码
// 获取相对路径下的输入字节流
InputStream is = this.getServletContext().getResourceAsStream("/WEB-INF/classes/db.properties");
Properties prop = new Properties(); // 初始化Properties对象
prop.load(is); // 读取is字节流
String user = prop.getProperty("userName"); // 获取键值对
String pwd = prop.getProperty("PassWord"); // 获取键值对
resp.getWriter().print("账号:" + user + "密码" + pwd);
}
苟利国家生死以,岂因祸福避趋之