Servlet
package com.example.servlet01; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import java.io.IOException; @WebServlet(name = "/ser01", value = "/ser01") public class Servlet extends HttpServlet { @Override public void init() throws ServletException { System.out.println("创建实例"); } @Override public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException { // super.service(req, res); System.out.println("hello"); res.getWriter().write("adad"); } @Override public void destroy() { System.out.println("实例销毁"); } }
package com.example.servlet01; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import java.io.IOException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet("/s01") public class Servlet extends HttpServlet { @Override public void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { // 常用方法 //获取请求的完整路径 String url = req.getRequestURL() + ""; System.out.println("获取请求的完整路径" + url); //获取部分路径 String uri = req.getRequestURI() + ""; System.out.println(uri); //获取请求时的字段 System.out.println(req.getQueryString()); //获取请求方式 System.out.println(req.getMethod()); //获取当前协议版本 System.out.println(req.getProtocol()); //获取项目的站点名(项目对外访问路径) System.out.println(req.getContextPath()); //获取请求的参数 //获取指定名称的参数值,返回字符串 String uname = req.getParameter("uname"); String upwd = req.getParameter("upwd"); System.out.println("uname:" + uname + ",upwd" + upwd); //获取指定名称的参数的所有参数值,返回字符串(用于复选框传值) String[] hobbies = req.getParameterValues("hobby"); //判断数组是否为空 if (hobbies != null && hobbies.length > 0) { for (String hobby : hobbies) { System.out.println(hobby); } } } }
package com.example.servlet01; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; @WebServlet("/s01") public class Servlet extends HttpServlet { @Override public void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { req.setCharacterEncoding("UTF-8");//只针对post请求 //获取请求的参数 //获取指定名称的参数值,返回字符串 String uname = req.getParameter("uname"); String upwd = req.getParameter("upwd"); System.out.println("uname:" + uname + ",upwd" + upwd); String name = new String(req.getParameter("uname").getBytes("ISO-8859-1"), "UTF-8")); //用于乱码 //获取指定名称的参数的所有参数值,返回字符串(用于复选框传值) String[] hobbies = req.getParameterValues("hobby"); //判断数组是否为空 if (hobbies != null && hobbies.length > 0) { for (String hobby : hobbies) { System.out.println(hobby); } } } }
请求转发
@WebServlet("/s01") public class Servlet extends HttpServlet { @Override public void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { //接收客户请求的参数 String uname = req.getParameter("uname"); System.out.println(uname); //请求转发跳转到s02 req.getRequestDispatcher("s02").forward(req, res); } }
@WebServlet("/s02") public class Servlet01 extends HttpServlet { @Override public void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { //设置域对象内容 req.setAttribute("name", "admin"); req.setAttribute("age", 18); List<String> list = new ArrayList<>(); list.add("aaa"); list.add("bbb"); req.setAttribute("list", list); //请求跳转到Servlet req.getRequestDispatcher("s01").forward(req, res); } }
@WebServlet("/s01") public class Servlet extends HttpServlet { @Override public void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { //获取对象 String name= (String) req.getAttribute("name"); System.out.println(name); Integer age= (Integer) req.getAttribute("age"); System.out.println(age); List<String> list=(List<String>)req.getAttribute("list"); System.out.println(list); } }
@WebServlet("/s01") public class Servlet extends HttpServlet { @Override public void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { // 响应数据 //getwriter()输出字符串(字符输出流) // PrintWriter writer = res.getWriter(); // 输出数据 // writer.write("hell0"); //getOutPutStream()字节输出流,输出一切数据 ServletOutputStream outputStream=res.getOutputStream(); outputStream.write("HI".getBytes()) } }
//字符流或者字节流 //解决乱码需要设置客户端和服务端的编码格式 res.setCharacterEncoding("UTF-8");//服务端 res.setHeader("content-type", "text/html;charset=UTF-8"); //或者 res.setContentType("text/html;charset=UTF-8");
@WebServlet("/s01") public class Servlet extends HttpServlet { @Override public void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { //重定向:服务端指导,客户端行为 //存在两次请求,地址栏会发生改变,数据不共享 System.out.println("s01"); //重定向跳转到s02 res.sendRedirect("s02"); } }
@WebServlet("/s02") public class Servlet01 extends HttpServlet { @Override public void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { System.out.println("s02"); } }
@WebServlet("/s01") public class Servlet extends HttpServlet { @Override public void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { //创建cookie对象 Cookie cookie=new Cookie("name","admin"); res.addCookie(cookie); } }
@WebServlet("/s02") public class Servlet01 extends HttpServlet { @Override public void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { //获取cookie数组对象 Cookie[] cookies = req.getCookies(); if (cookies != null && cookies.length > 1) { for (Cookie co : cookies) { String name = co.getName(); String value = co.getValue(); System.out.println(name + value); } } } }
//设置cookie的存活时间 // 方法一,默认-1,存在浏览器内存中,关闭浏览器会失效 Cookie cookie = new Cookie("name", "asdjin"); cookie.setMaxAge(-1); // 方法二,设置正整数,会一直保存在电脑硬盘里 cookie.setMaxAge(100); // 方法三,0,删除cookie cookie.setMaxAge(0);
//cookie的路径 Cookie cookie = new Cookie("name", "zhangsan1"); // 当前服务器下任何项目的任意资源都可以获取cookie,只需要设置cookie的路径是/ cookie.setPath("/"); res.addCookie(cookie); // 不设置的话是当前的 // 指定项目 cookie.setPath("/s01"); // 指定项目 cookie.setPath("/s01/servlet01");
package com.example.servlet01; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.IOException; @WebServlet("/s02") public class Servlet01 extends HttpServlet { @Override public void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { HttpSession httpSession=req.getSession();//获取session对象,存在则获取,不存在则创建 String id=httpSession.getId();//获取session的会话标识符 System.out.println(httpSession.getCreationTime());//获取session的创建时间 System.out.println(httpSession.getLastAccessedTime());//获取最后一次的访问时间 System.out.println(httpSession.isNew());//判断是否有新的session对象 //设置域对象 httpSession.setAttribute("name","admin"); // 移除域对象 httpSession.removeAttribute("name"); // 设置时间:默认30分钟,需要在Tomcat的conf目录修改 // 或者自己定义 httpSession.setMaxInactiveInterval(15);//15秒失效 // 立即销毁 httpSession.invalidate();//每次都会立即销毁 // 关闭浏览器就失效,因为session对象依赖于cookie对象,所以只要关闭浏览器就会失效 // 关闭服务器也会失效 } }
//文件上传 package com.example.servlet01; import javax.servlet.ServletException; import javax.servlet.annotation.MultipartConfig; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.Part; import java.io.IOException; @WebServlet("/s01") @MultipartConfig//如果要上传文件,必须要设置注解 public class Servlet extends HttpServlet { @Override public void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { // 设置编码 req.setCharacterEncoding("UTF-8"); // 获取普通表单项 String uname=req.getParameter("uname"); // 获取part对象(Servlet将multipart/form.data的post请求封装成part对象 Part part=req.getPart("myfile");//表单中file文件的name属性值 // 通过part对象读取到上传的文件名 String filename= part.getSubmittedFileName(); // 得到文件存放的路径 String filepath=req.getServletContext().getRealPath("/"); // 上传到指定目录 part.write(filepath+"/"+filename); } }
//文件下载 package com.example.servlet01; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.annotation.MultipartConfig; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; @WebServlet("/s01") @MultipartConfig//如果要上传文件,必须要设置注解 public class Servlet extends HttpServlet { @Override public void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { // 后台下载 // 设置请求的编码格式 req.setCharacterEncoding("UFF-8"); // 获取参数 String filename = req.getParameter("filename"); // 参数的非空判断 if (filename == null || "".equals(filename.trim())) { res.getWriter().write("请输入要下载的文件名"); res.getWriter() .close(); return; } // 找到存放路径 String path = req.getServletContext().getRealPath("/download/"); // 通过路径得到file对象 File file = new File(path + filename); // 判断文件是否存在并且是一个标准资源 if (file.exists() && file.isFile()) { // 设置响应类型 res.setContentType("application/x-msdownload"); // 设置响应头 res.setHeader("Content-Disposition", "attachment;filename=" + filename); // 得到输入流 InputStream in = new FileInputStream(file); // 得到输出流 ServletOutputStream out = res.getOutputStream(): // 定义byte数组 byte[] bytes = new byte[1024]; // 定义长度 int len = 0; // 循环输出 while ((len = in.read(bytes)) != -1) { // 输出内容 out.write(bytes, 0, len); } out.close(); in.close(); } else { res.getWriter().write("文件不存在,请重试"); res.getWriter().close(); } } } ======================================================================== <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <!--文件上传 1.准备表单 2.设置表单的提交类型为post请求,method="post" 3.设置表单类型为文件上传表单entype="multipart/form-data" 4.设置文件提交的地址 5.准备表单元素 1.普通的表单项 type="text" 2.文件项 type="file" 6.设置表单元素的name属性(一定要设置name) --> <form action="" enctype="multipart/form-data" method="posthtml"> 姓名<input name="uname" type="text"><br> 文件<input name="myfile" type="file"><br> <button>提交</button> </form> </body> </html>