复习!
4.5、ServletContext
web容器在启动的时候,他会为每个web程序创建一个对应的servletContext对象,它代表当前的web应用。
4个案例
1、共享数据
我在这个servlet中保存的数据,可以在另一个servlet中拿到
public class HelloServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//this.getServletContext()
ServletContext servletContext = this.getServletContext();
//共享数据
String username = "hyf";
servletContext.setAttribute("username",username);
}
}
public class GetServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext servletContext = this.getServletContext();
String username = String.valueOf(servletContext.getAttribute("username"));
resp.getWriter().print("name:"+username);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
在web.xml中添加映射
<servlet>
<servlet-name>hello</servlet-name>
<servlet-class>com.hao.servlet.HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>getname</servlet-name>
<servlet-class>com.hao.servlet.GetServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>getname</servlet-name>
<url-pattern>/getname</url-pattern>
</servlet-mapping>
2、获取初始化参数
//获取初始化参数
public class ServletDemo03 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext servletContext = this.getServletContext();
String url = servletContext.getInitParameter("url");
resp.getWriter().print(url);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
<!--配置一些web应用初始化参数-->
<context-param>
<param-name>url</param-name>
<param-value>jdbc:mysql://localhost:3306/mybatis</param-value>
</context-param>
<servlet>
<servlet-name>gp</servlet-name>
<servlet-class>com.hao.servlet.ServletDemo03</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>gp</servlet-name>
<url-pattern>/gp</url-pattern>
</servlet-mapping>
3、请求转发
//请求转发
public class ServletDemo04 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext servletContext = this.getServletContext();
RequestDispatcher requestDispatcher = servletContext.getRequestDispatcher("/gp");//转发的请求路径
requestDispatcher.forward(req,resp);//调用forward实现请求转发
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
在web.xml中添加映射,略
4、读取资源文件
/*
读取资源文件
//properties
在Java目录下新建properties
在resources目录下新建properties
发现:都被打包到了同一路径下classes,我们俗称这个路径为classpath
**/
public class ServletDemo05 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext servletContext = this.getServletContext();
InputStream asStream = servletContext.getResourceAsStream("/WEB-INF/classes/com/hao/servlet/aa.properties");
Properties properties = new Properties();
properties.load(asStream);
String user = properties.getProperty("username");
String pwd = properties.getProperty("password");
resp.getWriter().print(user+":"+pwd);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
会出现资源导出失败问题,需要在pom.xml中 build里添加
<resources>
<resource>
<directory>src/main/resources</directory>
<excludes>
<exclude>**/*.properties</exclude>
<exclude>**/*.xml</exclude>
</excludes>
<filtering>true</filtering>
</resource>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
添加映射
4.6、HttpServletResponse
1、下载文件
web服务器 接收到客户端的http请求,针对这个请求,分别创建一个代表请求的HttpServletResponse对象,代表响应一个HttpServletResponse
public class FileServletTest extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 1、获取下载文件路径
//F:\idea-workspace\javaweb-02-servlet\response\src\main\resources\tx.jpg
String realPath = "F:\\idea-workspace\\javaweb-02-servlet\\response\\src\\main\\resources\\tx.jpg";
//String realPath = this.getServletContext().getRealPath("/tx.jpg");
System.out.println("下载文件的路径:"+realPath);
// 2、文件名
String fileName = realPath.substring(realPath.lastIndexOf("\\" )+1);
// 3、想办法设置让浏览器能够支持(Content-Disposition)下载我们需要的东西
//"attachment:filename"是查看,分号是实现下载
resp.setHeader("Content-Disposition","attachment;filename"+fileName);
// 4、获取下载文件输入流
FileInputStream in = new FileInputStream(realPath);
// 5、创建缓冲区buffer
int len = 0;
byte[] buffer = new byte[1024];
// 6、获取OutputStream对象
ServletOutputStream os = resp.getOutputStream();
// 7、将FileOutputStream流写入到buffer缓冲区
// 8、使用OutputStream将缓冲区的数据传输到客户端
while(in.read(buffer)>0){
os.write(buffer,0,len);
}
in.close();
os.close();
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
2、验证码实现
//验证码实现
public class ImageServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//让浏览器自动3秒刷新一次就生成一个验证码
resp.setHeader("refresh","3");
//在内存中创建一个图片
BufferedImage image = new BufferedImage(80,20,BufferedImage.TYPE_INT_BGR);
//画图,得到一个图片
Graphics2D g = (Graphics2D) image.getGraphics();//笔
//设置图片背景色
g.setColor(Color.lightGray);
g.fillRect(0,0,80,20);
//给图片写数据
g.setColor(Color.blue);
g.setFont(new Font(null,Font.ITALIC,20));
g.drawString(makeNum(),0,20);
//告诉浏览器,请求用图片的方式打开
resp.setContentType("image/jpg");
//不让浏览器缓存
resp.setDateHeader("expires",-1);
resp.setHeader("Cache-Control","no-cache");
resp.setHeader("Pragma","no-cache");
//图片写给浏览器
ImageIO.write(image,"jpg",resp.getOutputStream());
}
//生成随机数
private String makeNum(){
Random random = new Random();
String num = random.nextInt(9999)+"";
StringBuffer sb = new StringBuffer();
for (int i=0;i<4-num.length();i++){
sb.append("0");
}
num = sb.toString()+num;
return num;
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
3、重定向
//重定向
public class SendRedirectServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.sendRedirect("/response_war/img");
//重定向:status code:302 location
//重定向 VS 请求转发307
/*
相同点:都会跳转
不同: 请求转发,url不会变化
重定向 url变化
* */
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
jsp文件
<!--这个提交路径,需要找项目路径-->
<%--${pageContext.request.contextPath}代表当前项目--%>
<form action="${pageContext.request.contextPath}/login" method="get">
用户名:<input type="text" name="user"><br>
密码:<input type="password" name="password"><br>
<input type="submit">
</form>
public class RequestTest extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("进入了这个请求");
//处理请求
String user = req.getParameter("user");
String password = req.getParameter("password");
System.out.println(user+":"+password);
//重定向
resp.sendRedirect("/response_war/success.jsp");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
4.7、HttpServletRequest
获取前端传递的参数、请求转发
public class loginServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String user = req.getParameter("user");
String password = req.getParameter("password");
String[] hobbies = req.getParameterValues("hobby");
System.out.println("=============");
System.out.println(user+":"+password);
System.out.println(Arrays.toString(hobbies));
//通过请求转发 307
//转发跟重定向不一样,转发,/就是当前项目
req.getRequestDispatcher("/success.jsp").forward(req,resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
大处着眼、小处着手
对照的课程