1、Servlet原理
Servlet是由Web服务器调用的,web服务器在收到浏览器请求之后,
2、Mapping问题
- 一个Servlet可以指定一个映射路径
<servlet-mapping><servlet-name>hello</servlet-name><url-pattern>/hello</url-pattern></servlet-mapping>
一个Servlet可以指定多个映射路径
<!--通过映射可以把多个不同的后缀映射到一个实现类上--><servlet-mapping><servlet-name>hello</servlet-name><url-pattern>/hello2</url-pattern></servlet-mapping><servlet-mapping><servlet-name>hello</servlet-name><url-pattern>/hello3</url-pattern></servlet-mapping>
- 一个Servlet可以指定通用映射路径
<servlet-mapping><servlet-name>hello</servlet-name><url-pattern>/hello/*</url-pattern></servlet-mapping>
- 默认请求路径(不推荐使用)
<servlet-mapping><servlet-name>hello</servlet-name><url-pattern>/*</url-pattern></servlet-mapping>
- 指定一些后缀或者前缀等等…
<!--可以自定义后缀实现请求映射注意点,*前面不能加项目映射的路径/hello/*.shuai (报错)--><servlet-mapping><servlet-name>hello</servlet-name><url-pattern>*.shuai</url-pattern></servlet-mapping>
优先级问题
指定了固有的映射路径优先级最高,如果找不到就会走默认的处理请求<!--注册404页面--><servlet><servlet-name>error</servlet-name><servlet-class>com.shuai.Servlet.ErrorServlet</servlet-class></servlet><servlet-mapping><servlet-name>error</servlet-name><url-pattern>/*</url-pattern></servlet-mapping>
3、ServletContext
web容器在启动的时候,它会为每个web程序都创建一对应的ServletContext对象,他代表了当前的web应用;
1、共享数据
我在这个Servlet中保存的数据,可以在另外一个Servlet中拿到;
存数据:
@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {// this.getInitParameter() 初始化参数// this.getServletConfig() Servlet配置// this.getServletContext() Servlet上下文ServletContext context = this.getServletContext();String username = "无敌最俊朗";context.setAttribute("username",username); // 将一个数据存在了ServletContext中,名字为:username,值为无敌最俊朗}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {doGet(req,resp);}
获取数据:
@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {ServletContext context = this.getServletContext();String username = (String) context.getAttribute("username");// 设置字符编码避免乱码resp.setContentType("text/html");resp.setCharacterEncoding("utf-8");resp.getWriter().print("名字:"+ username);}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {super.doPost(req, resp);}
web.xml
<servlet><servlet-name>hello</servlet-name><servlet-class>com.shuai.servlet.HelloServlet</servlet-class></servlet><servlet-mapping><servlet-name>hello</servlet-name><url-pattern>/hello</url-pattern></servlet-mapping><servlet><servlet-name>getc</servlet-name><servlet-class>com.shuai.servlet.GetServlet</servlet-class></servlet><servlet-mapping><servlet-name>getc</servlet-name><url-pattern>/getc</url-pattern></servlet-mapping>
2、获取初始化参数
// ServletDemo3.java@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {ServletContext context = this.getServletContext();String url = context.getInitParameter("url");resp.getWriter().print(url);}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {super.doPost(req,resp);}
web.xml
<!--配置一些web应用初始化参数--><context-param><param-name>url</param-name><param-value>jdbc:mysql://localhost:3306/mybatis</param-value></context-param>
3.请求转发
// ServletDemo4.java@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {ServletContext context = this.getServletContext();// RequestDispatcher requestDispatcher = context.getRequestDispatcher("/gp"); // 转发的请求路径// requestDispatcher.forward(req,resp); // 转发forward实现请求转发context.getRequestDispatcher("/gp").forward(req,resp);}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {super.doPost(req, resp);}
web.xml
<servlet><servlet-name>sd4</servlet-name><servlet-class>com.shuai.servlet.ServletDemo4</servlet-class></servlet><servlet-mapping><servlet-name>sd4</servlet-name><url-pattern>/sd4</url-pattern></servlet-mapping>
4、读取资源文件
Properties
- 在java目录下新建properties
- 在resources目录下新建properties
发现:都被打包到了同一个路径下:classes,我们俗称这个路径为classpath:
思路:需要一个文件流
username = rootpassword = dfafafaf
@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {InputStream is = this.getServletContext().getResourceAsStream("/WEB-INF/classes/com/shuai/servlet/aa.properties");Properties prop = new Properties();prop.load(is);String user = prop.getProperty("username");String pwd = prop.getProperty("password");resp.getWriter().print(user + ":" + pwd);}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {super.doPost(req, resp);}
4、HttpServletReaponse
web服务器接收到客户端的http请求,针对这个请求,分别创建一个代表请求的HttpServletResquest对象,代表响应的一个HttpServletReaponse;
- 如果要获取客户端请求过来的参数:找HttpServletResquest
- 如果要给客户端响应一些信息:找HttpServletReaponse
1、简单分类
负责向浏览器发送数据的方法
ServletOutputStream getOutputStream() throws IOException;PrintWriter getWriter() throws IOException;
负责向浏览器发送响应头的方法
void sendError(int var1, String var2) throws IOException;void sendError(int var1) throws IOException;void sendRedirect(String var1) throws IOException;void setDateHeader(String var1, long var2);void addDateHeader(String var1, long var2);void setHeader(String var1, String var2);void addHeader(String var1, String var2);void setIntHeader(String var1, int var2);void addIntHeader(String var1, int var2);void setStatus(int var1);
2、下载文件
@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {/** 前四个是字符串操作* 后四个是IO操作*/// 解决乱码问题req.setCharacterEncoding("utf-8");resp.setCharacterEncoding("utf-8");resp.setContentType("text/html;charset=utf-8");// 1. 要获取下载文件的路径// String realPath = this.getServletContext().getRealPath("\1.jpg");String realPath = "G:\\JavaProjects\\javaweb-servlet-02\\Response\\target\\classes\\1.jpg";System.out.println("下载的文件路径:"+ realPath);// 2. 下载的文件名是啥?String fileName = realPath.substring(realPath.lastIndexOf("\\") + 1);// String fileName = "1.jpg";// 3.设置想办法让浏览器能够支持 下载我们需要的东西resp.setHeader("Content-Disposition","attachment:filename"+ URLEncoder.encode(fileName,"UTF-8"));// 4.获取下载文件的输入流FileInputStream in = new FileInputStream(realPath); // 把文件变成流就能用了// 5.创减缓冲区int len = 0;byte[] buffer = new byte[1024];// 6.获取OutputStream对象ServletOutputStream out = resp.getOutputStream();// 7.将FileOutputStream流写入到buffer缓冲区,使用OutputStream将缓冲区中的数据输出到客户端!while ((len=in.read(buffer))>0){out.write(buffer,0,len); // 把流写入缓冲区长度从0到len}in.close();out.close();}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {doGet(req, resp);}
3、实现重定向
B一个web资源收到客户端A请求后,B它会通知A客户端去访问另外一个web资源C,这个过程叫做重定向
常见场景:
- 用户登录
void sendRedirect(String var1) throws IOException;
测试:
@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {// resp.sendRedirect("/r/file"); // 重定向ServletContext context = this.getServletContext();context.getRequestDispatcher("/file").forward(req,resp);}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {doGet(req, resp);}
面试题:请你聊聊重定向和转发的区别?
相同点:
- 页面都会跳转
不同点
- 请求转发的时候,url不会产生变化;
- 重定向的时候,url地址栏会发生变化;
5、HttpServletResquest
1、获取参数,请求转发
@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {// 防止请求和响应乱码req.setCharacterEncoding("utf-8");resp.setCharacterEncoding("utf-8");resp.setContentType("text/html;charset=utf-8");// 处理请求(得到前端的参数)String username = req.getParameter("username");String password = req.getParameter("password");String[] hobbys = req.getParameterValues("hobbys"); // 得到数组System.out.println("==================");System.out.println(username);System.out.println(password);System.out.println(Arrays.toString(hobbys));System.out.println("==================");System.out.println(req.getContextPath()); // /r// 通过请求转发// 这里的/代表当前的web项目req.getRequestDispatcher("/success.jsp").forward(req,resp);}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {doGet(req, resp);}
