每个web工程都只有一个ServletContext对象,也就是不管在哪个servlet里面,获取到的这个类的对象都是同一个。
1.获取对象
ServletContext context = getServletContext();
作用:
1.可以获取全局配置参数
2.可以获取web应用中的资源
1. 获取资源在tomcat里面的绝对路径:context.getReadPath("");获取到项目在tomcat里面的根目录
context.getRealPath("file/config.properties");
/**
* Servlet implementation class Demo03
*/
public class Demo03 extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 获取ServletContext对象
ServletContext context = getServletContext();
//获取给定的文件在服务器上面的绝对路径
String path = context.getRealPath("file/config.properties");
System.out.println("path="+path);
// 1.创建属性对象
Properties properties = new Properties();
// 2.指定载入的数据源
// InputStream is = new FileInputStream("src/config.properties");
InputStream is = new FileInputStream(path);
properties.load(is);
// 3.获取name属性的值
String name = properties.getProperty("name");
System.out.println("name=" + name);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
2.getResourceAsStream获取资源 流对象
3.通过classloader去获取web工程下的资源
3. 使用ServletContext存取数据,servlet间共享数据 域对象
LoginServlet.java:
public class LoginServlet extends HttpServlet {
/*
* request:包含请求信息
* response:响应数据给浏览器,就靠这个对象
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
//1. 获取数据
String userName = request.getParameter("username");
String password = request.getParameter("password");
System.out.println("username="+userName+" "+"password="+password);
//2.校验数据
//向客户端输 出内容
PrintWriter pw = response.getWriter();
if("admin".equals(userName) && "123".equals(password)) {
//System.out.println("登录成功");
//pw.write("login success..");
//成功就跳转到login_success.html
//1.成功的次数累加
//获取以前存的值,然后在旧的值基础上+1
Object obj=getServletContext().getAttribute("count");
//默认就是0次
int totalCount=0;
if(obj!=null)
{
totalCount = (int)obj;
}
System.out.println("已知登录成功的次数是:"+totalCount);
//给这个count赋新的值
getServletContext().setAttribute("count", totalCount+1);
//设置状态码,重新定位状态码
response.setStatus(302);
//定位跳转的位置是哪一个页面
response.setHeader("Location", "login_success.html");
}
else
{
//System.out.println("登录失败");
pw.write("login failed..");
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
CountServlet.java:
public class CountServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1.取值
int count = (int)getServletContext().getAttribute("count");
//输出到界面
response.getWriter().write("当前网站成功登录总次数为:"+count+"次");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
###ServletContext何时创建,何时销毁?
1.服务器启动的时候,会为托管的每一个web应用程序,创建一个ServletContext对象
2.从服务器移除托管,或者是关闭服务器
ServletContext的作用范围?
只要在同一个项目里面,都可以取
###HttpServletRequest
>这个对象封装了客户端提交过来的一切数据。
1.可以获取客户端请求头信息
2.获取客户端提交过来的数据
/**
* Servlet implementation class Demo01
*/
public class Demo01 extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//取出请求里面的所有头信息----得到一个枚举集合
Enumeration<String> headerNames = request.getHeaderNames();
while (headerNames.hasMoreElements()) {
String name = (String) headerNames.nextElement();
System.out.println(name);
}
//2.获取到的是客户端提交上来的数据
String name = request.getParameter("name");
String address = request.getParameter("address");
System.out.println("name="+name);
System.out.println("addrsss="+address);
System.out.println("-----------------");
//获取所有的参数,得到一个枚举集合
//Enumeration<String> parameterNames = request.getParameterNames();
Map<String, String[]> map = request.getParameterMap();
Set<String> keySet = map.keySet();
Iterator<String> iterator = keySet.iterator();
while (iterator.hasNext()) {
String key = (String) iterator.next();
String value = map.get(key)[0];
System.out.println(key+"========"+value);
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
3.获取中文数据
>客户端提交数据给服务器端,如果数据中带有中文的话,有可能会出现乱码情况,那么可以参照以下方法解决:
1.如果是GET方式:
username = new String(name.getBytes("ISO-8859-1"), "UTF-8");
直接在tomcat里面做配置,以后get请求过来的数据永远都是用UTF-8编码。
可以在tomcat里面做设置处理 conf/server.xml
<Connector connectionTimeout = "20000" port="8080" ....URIEncoding="UTF-8"/>
2.如果是POST方式:
//设置请求体里面的文字编码
request.setCharacterEncoding("UTF-8");这行设置一定要写在getParameter之前。
###HttpServletResponse
>负责返回数据给客户端
响应的数据中包含中文---> 乱码。
*以字符流输出
>response.getWriter()
1.指定输出到客户端的时候,这些文字使用UTF-8编码
response.setCharacterEncoding("UTF-8");
2.直接规定浏览器看这份数据的时候,使用什么编码来看
response.setHeader("Content-Type","text/html;charset=UTF-8");
response.getWriter().write("我爱java");
//以字符流的方式写数据
response.getWriter().write("<h1>hello</h1>");
//以字节流的方式写数据
response.getOutputStream().write("hello".getBytes());
*以字节流输出
>response.getOutputStream()
//设置响应的数据类型是 html文本,并且告知浏览器,使用UTF-8来编码
//不管是字节流还是字符流,直接使用一行代码就可以了
response.setContentType("text/html;charset=UTF-8");
然后在写数据即可。
###演练下载资源
1.直接以超链接的方式下载,不写任何代码。也能够下载东西下来
>原因是tomcat里面有一个默认的Servlet--DefaultServlet。这个DefaultServlet专门用于处理放在tomcat服务器上的静态资源。
Demo01.java:
package com.itheima.servlet;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class Demo01
*/
public class Demo01 extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1.获取要下载的文件名字
String fileName = request.getParameter("filename");
//2.获取这个文件在tomcat里面的绝对路径
String path = getServletContext().getRealPath("download/"+fileName);
//让浏览器收到这份资源的时候,以下载的方式提醒用户,而不是直接展示。
response.setHeader("Content-Disposition", "attachment;filename="+fileName);
//3.转化成输入流
InputStream is = new FileInputStream(path);
OutputStream os = response.getOutputStream();
int len=0;
byte[] buffer =new byte[1024];
while((len=is.read(buffer))!=-1)
{
os.write(buffer,0,len);
}
os.close();
is.close();
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
index.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
让tomcat的默认servlet去提供下载:<br>
<a href="download/aa.jpg">aa.jpg</a><br>
<a href="download/bb.txt">bb.txt</a><br>
<a href="download/cc.rar">cc.rar</a><br>
手动编码提供下载:<br>
<a href="Demo01?filename=aa.jpg">aa.jpg</a><br>
<a href="Demo01?filename=bb.txt">aa.jpg</a><br>
<a href="Demo01?filename=cc.rar">aa.jpg</a><br>
</body>
</html>