1、什么是servletcontext
web容器在启动的时候,他会为每个web程序创建一个对应的servletcontext对象,他代表的是当前的web应用:
共享数据
我在这个Servlet中保存的数据,可以在宁一个servlet中拿到:
例子如下
设置数据
public class Servlettest extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request,response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ServletContext context = this.getServletContext();
String userName="小米";
context.setAttribute("userName",userName);
}
获取数据
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request,response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ServletContext context = this.getServletContext();
String userName =(String)context.getAttribute("userName");
System.out.println(userName);
}
web.xml的配置
<servlet>
<servlet-name>gethello</servlet-name>
<servlet-class>com.xiaoming.servlet.GetServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>gethello</servlet-name>
<url-pattern>/gethello</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>sethello</servlet-name>
<servlet-class>com.xiaoming.servlet.Servlettest</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>sethello</servlet-name>
<url-pattern>/sethello</url-pattern>
</servlet-mapping>
测试结果:
二、servletcontext的方法介绍
servlet获取初始化参数
<context-param>
<param-name>url</param-name>
<param-value>jdbc:mysql://localhost:8080/test</param-value>
</context-param>
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html");
resp.setCharacterEncoding("utf-8");
ServletContext servletContext = this.getServletContext();
String url = servletContext.getInitParameter("url");
resp.getWriter().print(url);
}
请求转发
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setCharacterEncoding("utf-8");
resp.setContentType("text/html");
ServletContext context = this.getServletContext();
context.getRequestDispatcher("/hello").forward(req,resp);
}
读取properties资源文件
在Java和resource的目录下创建一个文件都会生成到classes文件下
classes被称为类路径。
下载文件的案例
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// String path = this.getServletContext().getRealPath("/1.png");
String path = "E:\\learn\\javaweb\\java_servlet\\ResponseServlet\\src\\main\\resources\\1.png";
System.out.println("文件的绝对路径"+path);
String filename = path.substring(path.lastIndexOf("\\") + 1);
resp.setHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode(filename,"utf-8"));
FileInputStream stream = new FileInputStream(path);
int len=0;
byte[] buffer = new byte[1024];
ServletOutputStream outputStream = resp.getOutputStream();
while((len=stream.read(buffer))>0){
outputStream.write(buffer,0,len);
}
outputStream.close();
stream.close();
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
在Java中生成验证码图片
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setHeader("refresh","3");
// 在内存中创建一个图片
BufferedImage Image = new BufferedImage(80, 20, BufferedImage.TYPE_3BYTE_BGR);
Graphics2D g = (Graphics2D)Image.getGraphics();//得到一个笔
g.setColor(Color.white);//设置背景颜色
g.fillRect(0,0,80,20);//用笔把画布进行填充
//生成随机数
g.setColor(Color.blue);
g.setFont(new Font(null,Font.BOLD,20));
g.drawString(makeNum(),0,20);
//告诉浏览器,这个文件用图片方式打开
response.setContentType("image/jpg");
response.setDateHeader("expires",-1);
response.setHeader("Cache-Control","no-cache");
response.setHeader("pragma","no-cache");
//把图片写给浏览器
ImageIO.write(Image,"jpg", response.getOutputStream());
}
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");
}
String s = sb.toString() + num;
return s;
}
}
重定向
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.sendRedirect("/test3/image");
}
重定向和转发都会跳转页面,但是转发的url地址栏不会发生变化而重定向地址栏会发生变化。