在浏览器中输出 hello servlet!
1.1、创建一个maven项目,连接Tomcat
public class HelloServlet extends HttpServlet { //Art+Ins //由于get或者post只是请求实现的不同的方式,可以相互调用,业务逻辑都一样 @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { PrintWriter writer = resp.getWriter();//响应流 writer.println("hello servlet!!!"); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req,resp); } }
1.2、在web.xml文件中写添加映射
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" version="4.0"> <!--注册servlet--> <servlet> <servlet-name>hello</servlet-name> <servlet-class>com.feng.servlet.HelloServlet</servlet-class> </servlet> <!--mapping:映射--> <servlet-mapping> <servlet-name>hello</servlet-name> <url-pattern>/hello</url-pattern> </servlet-mapping> </web-app>
为什么需要映射:我们写的是java程序,但是要通过浏览器访问,而浏览器需要连接web服务器,所以我们需要在web服务器中注册我们写的Servlet,还需给他一个浏览器能够访问的路径
如果项目没有web,直接项目右键添加即可!
web容器在启动的时候,它会为每个web程序都创建一个对应的ServletContext对象,它代表了当前的web应用;
public class SetServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //this.getInitParameter();初始化参数 //this.getServletConfig();Servlet配置 //this.getServletContext();Servlet上下文 ServletContext context = this.getServletContext(); String name = "bitwind"; //将一个数据保存在了ServletContext中 context.setAttribute("username",name);//setAttribute : 设置属性 } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req,resp); } }
public class GetServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //获取ServletContext中的值 ServletContext context = this.getServletContext(); String name = (String) context.getAttribute("username"); resp.getWriter().println("name = "+name); System.out.println(name); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
添加映射
启动Tomcat,访问!
注意:要先访问GetServlet类,否则name=null,要先存进ServletContext,才有得拿!
public class GetInitParameter extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("text/html"); resp.setCharacterEncoding("utf-8"); //this.getInitParameter();初始化参数 //this.getServletConfig();Servlet配置 //this.getServletContext();Servlet上下文 ServletContext context = this.getServletContext(); String name = context.getInitParameter("Tom"); resp.getWriter().println(name); System.out.println(name); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
在web.xml中设置初始化参数
<!--初始化参数--> <context-param> <param-name>Tom</param-name> <param-value>这是javaweb,这是servlet,这是初始化参数!</param-value> </context-param>
添加映射
启动Tomcat,访问!
public class GetRequestDispatcher extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { ServletContext context = this.getServletContext(); System.out.println("这是GetRequestDispatcher!!!"); RequestDispatcher dispatcher = context.getRequestDispatcher("/init");//这是web设置的url路径 dispatcher.forward(req,resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
添加映射
启动Tomcat,访问!
target*是用来存放项目构建后的文件和目录、jar包、war包、编译的class*文件
Properties
username=张三 password=123456
发现:都被打包到了同一个路径下:classes,我们俗称这个路径为classpath;
public class GetProperties extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("text/html"); resp.setCharacterEncoding("utf-8"); //第一条“/”不能省略,代表真当前web项目 InputStream is = this.getServletContext().getResourceAsStream("/WEB-INF/classes/db.properties"); Properties prop = new Properties(); prop.load(is);//获取文件流 String user = prop.getProperty("username"); String pwd = prop.getProperty("password"); resp.getWriter().print(user+":"+pwd); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
注意:"/WEB-INF/classes/db.properties"这是target 下的项目同名的目录路径!
添加映射
启动Tomcat,访问!
注意:要用maven模板新建的项目,这个target 目录下才有项目同名的包!
web服务器接收到客户端的http请求,针对这个请求,分别创建一个代表请求的HttpServletRequest对象,代表响应的一个HttpServletResponse;
response下载文件
public class HSResponse extends HelloServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String realPath = "文件路径\\文件名.文件类型"; //2. 下载的文件名是什么? String fileName = realPath.substring(realPath.lastIndexOf("\\") + 1); resp.setHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode(fileName,"UTF-8")); FileInputStream fileInputStream = new FileInputStream(realPath); int len = 0; byte[] buffer = new byte[1024]; ServletOutputStream outputStream = resp.getOutputStream(); while ((len = fileInputStream.read(buffer)) > 0){ outputStream.write(buffer,0,len); } fileInputStream.close(); outputStream.close(); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
添加映射
启动Tomcat,访问!
一个web资源收到客户端请求后,它会通知客户端去访问另一个web资源,这个过程叫重定向:
void sendRedirect(java.lang.String s) throws java.io.IOException;
public class Send extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.sendRedirect("/init");//路径发生变化 } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
HttpServletRequest代表客户端的请求,用户通过Http协议访问服务器,HTTP请求中的所有信息会被封装到HttpServlet,通过这个HttpServlet的方法,获得客户端的所有信息;
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>HSRequest</title> </head> <body> <div> <form action="${pageContext.request.contextPath}/request" method="post"> 用户名:<input type="text" name="username"><br> 密码:<input type="password" name="password"><br> 爱好: <input type="checkbox" name="hobbys" value="java">java <input type="checkbox" name="hobbys" value="JavaScript">JavaScript <input type="checkbox" name="hobbys" value="Oracle">Oracle <input type="checkbox" name="hobbys" value="Python">Python <br> <input type="submit"> </form> </div> </body> </html>
public class HSRequest extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String username = req.getParameter("username"); String password = req.getParameter("password"); String[] hobbys = req.getParameterValues("hobbys"); System.out.println(username+"\t"+password+"\t"+ Arrays.toString(hobbys)); req.getRequestDispatcher("/success.jsp").forward(req,resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>成功页面</title> </head> <body> <h1>登录成功</h1> <a href="${pageContext.request.contextPath}/index.jsp">首页</a> </body> </html>