Servlet在sun公司有两个实现类:HttpServlet、GenericServlet
web.xml:
<?xm1 version="1.0" encoding="UTF-8”?>
<web-app xm1ns= "http://xm1ns.jcp.org/xm1/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xm1/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0"
metadata-complete="true">
</web-app>
实现一个类继承HttpServlet:
servlet的运行原理(web容器就是Tomcat,web服务器)
Mapping问题
请求:http://localhost:8080/s1/hello
请求:http://localhost:8080/s1/hello
http://localhost:8080/s1/hello2
http://localhost:8080/s1/hello3
http://localhost:8080/s1/hello4
请求:http://localhost:8080/s1/sjiwhduefjak
ServletContext
1、共享数据
向ServletContext中存放数据
另一个servlet从ServletContext中取数据
配置xml
2、获取初始化参数
3、请求转发
请求转发后路径不会发生变化
和重定向的区别:重定向路径会发生变化
4、读取资源文件
把文件变成流来读取资源
Response 下载文件
HttpServletResponse
1、简单分类
2、常见应用
1、向浏览器输出消息
2、下载文件
public class FileServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//1、获取文件的路径
String realPath = "F:\caoyuetian\javaweb-maven-sevlet\response\src\main\resources\1.png";
System.out.println(realPath);
//2、获取文件的名字
String filename = realPath.substring(realPath.lastIndexOf("//") + 1);
//3、设置浏览器可以下载文件,URLEncoder.encode(filename,"UTF-8")让中文文件可以编码
resp.setHeader("Content-Disposition","attachment;filename="+URLEncoder.encode(filename,"UTF-8"));
//4、文件输入流
FileInputStream is = new FileInputStream(realPath);
//5、设置缓冲区
int len=0;
byte[] buffers=new byte[1024];
//6、使用输出流输出到客户端
ServletOutputStream os = resp.getOutputStream();
while((len=is.read(buffers))>0){
os.write(buffers,0,len);
}
is.close();
os.close();
}
3、设置验证码
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_RGB);
//得到图片
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);
//告诉浏览器,这个请求用图片的方式打开
resp.setContentType("image/jpeg");
//浏览器有缓存,不让浏览器缓存
resp.setDateHeader("exprise",-1);
resp.setHeader("Pragma","no-cache");
resp.setHeader("Cache-Control","no-cache");
//把图片写给浏览器
ImageIO.write(image,"jpg",resp.getOutputStream());
}
//生成7位随机数,其他位数用0补足
public String makeNum(){
Random r=new Random();
String num = r.nextInt(9999999)+"";
StringBuffer sb=new StringBuffer();
for (int i = 0; i < 7-num.length(); i++) {
sb.append("0");
}
num = sb.toString() + num;
return num;
}
4、重定向(路径会发生变化)
demo:
从index.jsp传递消息
接收到消息,处理请求
HttpServletRequest
1、获取前端获得的参数
2、请求转发
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
resp.setCharacterEncoding("utf-8");
String username = req.getParameter("username");
String password = req.getParameter("password");
String[] hobbys = req.getParameterValues("hobbys");
System.out.println(username);
System.out.println(password);
System.out.println(Arrays.toString(hobbys));
//请求转发,这里的/代表当前web应用,因此不需要再加项目名
req.getRequestDispatcher("/success.jsp").forward(req,resp);
}
7、cookie
demo:
public class cookieDemo1 extends HttpServlet {
@Override
//保存用户上一次访问的时间,req表示浏览器发给服务器的请求信息,resp表示服务器给浏览器的响应信息
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
resp.setCharacterEncoding("utf-8");
//服务器告诉你你来的时间,把时间封装成信件,然后下次带过来,服务器就知道你来了
PrintWriter out = resp.getWriter();
//服务端获取客户端带来的cookies
Cookie[] cookies = req.getCookies();
if(cookies!=null){
out.write("你上次访问的时间是:");
for (int i = 0; i < cookies.length; i++) {
//获取coookie的名字
if(cookies[i].getName().equals("LastLoginTime")){
//获取cookie的值,获得时间并把时间写出
long lasttime=Long.parseLong(cookies[i].getValue());
Date date=new Date(lasttime);
out.write(date.toLocaleString());
}
}
}else {
out.write("这是你第一次访问");
}
//服务端给客户端的cookie,如果没有访问过,那么会给一个新的cookie;如果访问过了,那么会更新cookie
Cookie cookie=new Cookie("LastLoginTime",System.currentTimeMillis()+"");
//cookie的有效期为一天
cookie.setMaxAge(24*60*60);
resp.addCookie(cookie);//更新cookies
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
session(重点)
demo1:
public class sessionDemo1 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
resp.setCharacterEncoding("utf-8");
resp.setContentType("text/html");//这是浏览器响应的格式
//得到session
HttpSession session = req.getSession();
//存入信息
session.setAttribute("name",new person("sweet",24));
//获取session
String id = session.getId();
//判断id是否为新创建的
if(session.isNew()){
resp.getWriter().write("新创建了一个id:"+id);
}else{
resp.getWriter().write("已经存在一个id:"+id);
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
demo2:
public class sessionDemo2 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
resp.setCharacterEncoding("utf-8");
resp.setContentType("text/html");//这是浏览器响应的格式
//得到session
HttpSession session = req.getSession();
person person =(person) session.getAttribute("name");
System.out.println(person.toString());
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
手动销毁session和自动销毁session:
在xml中设置,自动销毁session时,退出网站,只要时间没有达到,就不会销毁session
8、JSP
在电脑的位置:C:\Users\caoyuetian.IntelliJIdea2019.3\system\tomcat\Unnamed_javaweb-session-cookies\work\Catalina\localhost\s1\org\apache\jsp
页面转换成Java程序
浏览器向服务器发送请求,无论访问什么资源,都是在访问servlet
JSP最终会转换成java类
JSP本质就是一个servlet
源码:
java代码需要写在<% %>