指定一个映射路径:
<servlet-mapping>
<servlet-name>name</servlet-name>
<url-pattern>/xxx</url-pattern>
</servlet-mapping>
指定多个映射路径:直接指定多个路径
指定通用映射路径:/xxx/*
默认请求路径:/*
指定后缀或前缀:*.xxx
,前面不能加斜杠
指定路径的优先级高于默认路径
Web容器在启动的时候,会为每个web程序都创建一个对应的ServletContext对象,代表当前的web应用
获取对象:this.getServletContext()
共享数据:context.setAttribute("key", value)
,context.getAttribute("key")
获取初始化参数:context.getInitParameter("url")
<context-param>
<param-name>url</param-name>
<param-value>jdbc:mysql://localhost:3306/mybatis</param-value>
</context-param>
请求转发:context.getRequestDispatcher("path").forward(req, resp);
读取资源文件:
在resources目录中新建properties
username=root
password=123456
获取输入流:
InputStream is = this.getServletContext().getResourceAsStream("/WEB-INF/classes/db.properties");
加载并获取:
Properties prop = new Properties();
prop.load(is);
String username = prop.getProperty("username");
String password = prop.getProperty("password");
负责向浏览器发送数据的方法:getOutputStream()
,getWriter()
负责向浏览器发送响应头的方法:setxxx()
响应状态码:SC_XXX
向浏览器输出消息
下载文件:
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//获取下载文件的路径
String realPath = "xxxx\\1.png
//下载文件名
String filename = realPath.substring(realPath.lastIndexOf("\\") + 1);
//设置浏览器:下载而非内联,文件名UTF-8编码
resp.setHeader("Content-Disposition", "attachment; filename="+ URLEncoder.encode(filename, "UTF-8"));
//获取文件输入流
FileInputStream in = new FileInputStream(realPath);
//创建缓冲区
int len = 0;
byte[] buffer = new byte[1024];
//获取Servlet输出流
ServletOutputStream out = resp.getOutputStream();
//将文件写入缓冲区
while((len = in.read(buffer))> 0){
out.write(buffer, 0, len);
}
//关闭流
in.close();
out.close();
}
重定向:resp.setRedirect("path")
resp.setHeader("Location","path")
,resp.setStatus(302)
req.getParameter()
req.getRequestDispatcher("path").forward(req,resp)
原文:https://www.cnblogs.com/xiafrog/p/14336153.html