总结于遇见狂神说系列课程
1.编写HelloServlet类
public class HelloServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("进入了doGet方法"); PrintWriter writer=resp.getWriter(); writer.print("hello,Servlet"); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
2.在web.xml中编写Servlet的映射
为什么需要映射:我们写的是JAVA程序,但是要通过浏览器访问,而浏览器需要连接web服务器,
所以我们需要再web服务中注册我们写的Servlet,还需给他一个浏览器能够访问的路径;
<?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-name>hello</servlet-name> <servlet-class>com.nine.servlet.HelloServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>hello</servlet-name> <url-pattern>/hello</url-pattern> </servlet-mapping> </web-app>
3.配置Tomcat
<servlet-mapping> <servlet-name>hello</servlet-name> <url-pattern>/hello</url-pattern> </servlet-mapping>
<servlet-mapping> <servlet-name>hello</servlet-name> <url-pattern>/hello</url-pattern> </servlet-mapping> <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-mapping> <servlet-name>hello</servlet-name> <url-pattern>/hello4</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>hello</servlet-name> <url-pattern>/hello5</url-pattern> </servlet-mapping>
<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/sajdlkajda.qinjiang --> <servlet-mapping> <servlet-name>hello</servlet-name> <url-pattern>*.qinjiang</url-pattern> </servlet-mapping>
指定了固有的映射路径优先级最高,如果找不到就会走默认的处理请求;
<servlet> <servlet-name>error</servlet-name> <servlet-class>com.kuang.servlet.ErrorServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>error</servlet-name> <url-pattern>/*</url-pattern> </servlet-mapping>
web容器在启动的时候,它会为每个web程序都创建一个对应的ServletContext对象,它代表了当前的web应用;
实现在一个Servlet中保存的数据,在另外一个servlet中拿到;
HelloServlet
public class HelloServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("进入了doGet方法"); PrintWriter writer=resp.getWriter(); writer.print("hello,Servlet"); ServletContext context=this.getServletContext(); String username="nine"; context.setAttribute("username",username); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
GetServlet
public class GetServlet extends HttpServlet { @Override protected 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); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
web.xml
<servlet> <servlet-name>hello</servlet-name> <servlet-class>com.nine.servlet.HelloServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>hello</servlet-name> <url-pattern>/hello</url-pattern> </servlet-mapping> <servlet> <servlet-name>get</servlet-name> <servlet-class>com.nine.servlet.GetServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>get</servlet-name> <url-pattern>/get</url-pattern> </servlet-mapping>
在web.xml中配置初始化参数在Servlet中获取到
web.xml
<context-param> <param-name>作者</param-name> <param-value>九止</param-value> </context-param>
GetServlet
public class GetServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { ServletContext context=this.getServletContext(); String username=context.getInitParameter("作者"); resp.setContentType("text/html"); resp.setCharacterEncoding("utf-8"); resp.getWriter().print("作者:"+username); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
ServletContext context = this.getServletContext(); System.out.println("进入了ServletDemo04"); //RequestDispatcher requestDispatcher = context.getRequestDispatcher("/gp"); //转发的请求路径 //requestDispatcher.forward(req,resp); //调用forward实现请求转发; context.getRequestDispatcher("/gp").forward(req,resp);
Properties
发现:都被打包到了同一个路径下:classes,我们俗称这个路径为classpath:
思路:需要一个文件流;
nine.properties
username=nine password=123456
HelloServlet
public class HelloServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { InputStream is = this.getServletContext().getResourceAsStream("/WEB-INF/classes/com/nine/servlet/nine.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服务器接收到客户端的http请求,针对这个请求,分别创建一个代表请求的HttpServletRequest对象,代表响应的一个HttpServletResponse;
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { /* resp.setHeader("Location","/r/img"); resp.setStatus(302); */ resp.sendRedirect("welcome.html");//重定向 }
相同点
不同点
index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>$Title$</title> </head> <body> <%--这里提交的路径,需要寻找到项目的路径--%> <%--${pageContext.request.contextPath}代表当前的项目--%> <form action="${pageContext.request.contextPath}/login" method="get"> 用户名:<input type="text" name="username"> <br> 密码:<input type="password" name="password"> <br> <input type="submit" value="登录"> </form> </body> </html>
login.java
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //处理请求 String username = req.getParameter("username"); String password = req.getParameter("password"); System.out.println(username+":"+password); //重定向时候一定要注意,路径问题,否则404; resp.sendRedirect("/s3/success.jsp"); }
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-name>login</servlet-name> <servlet-class>com.nine.servlet.Login</servlet-class> </servlet> <servlet-mapping> <servlet-name>login</servlet-name> <url-pattern>/login</url-pattern> </servlet-mapping> </web-app>
在index.jsp同级别目录中创建success.jsp页面,勿放在WEB-INF目录下
HttpServletRequest代表客户端的请求,用户通过Http协议访问服务器,HTTP请求中的所有信息会被封装到HttpServletRequest,通过这个HttpServletRequest的方法,获得客户端的所有信息;
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("============================="); //后台接收中文乱码问题 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)); System.out.println("============================="); //通过请求转发 //这里的 / 代表当前的web应用 System.out.println(req.getContextPath()); req.getRequestDispatcher("/success.jsp").forward(req, resp); }
会话:用户打开一个浏览器,点击了很多超链接,访问多个web资源,关闭浏览器,这个过程可以称之为会话;
有状态会话:一个同学来过教室,下次再来教室,我们会知道这个同学,曾经来过,称之为有状态会话;
一个网站,怎么证明你来过?
客户端 服务端
cookie
客户端技术 (响应,请求)
session
服务器技术,利用这个技术,可以保存用户的会话信息? 我们可以把信息或者数据放在Session中!
常见:网站登录之后,你下次不用再登录了,第二次访问直接就上去了!
(1)从请求中拿到cookie信息
(2)服务器响应给客户端cookie
Cookie[] cookies = req.getCookies(); //获得Cookie cookie.getName(); //获得cookie中的key cookie.getValue(); //获得cookie中的vlaue new Cookie("lastLoginTime", System.currentTimeMillis()+""); //新建一个cookie cookie.setMaxAge(24*60*60); //设置cookie的有效期 resp.addCookie(cookie); //响应给客户端一个cookie
cookie:一般会保存在本地的 用户目录下 appdata;
Cookie的删除
不设置有效期,关闭浏览器,自动失效;
设置有效期时间为 0 ;
一个Cookie只能保存一个信息;
一个web站点可以给浏览器发送多个cookie,最多存放20个cookie;
Cookie大小有限制4kb;
300个cookie浏览器上限
什么是Session
Session和cookie的区别
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //解决乱码问题 req.setCharacterEncoding("UTF-8"); resp.setCharacterEncoding("UTF-8"); resp.setContentType("text/html;charset=utf-8"); //得到Session HttpSession session = req.getSession(); //给Session中存东西 session.setAttribute("name", new Person("秦疆", 1)); //获取Session的ID String sessionId = session.getId(); //判断Session是不是新创建 if (session.isNew()) { resp.getWriter().write("session创建成功,ID:" + sessionId); } else { resp.getWriter().write("session以及在服务器中存在 了,ID:" + sessionId); } //Session创建的时候做了什么事情; // Cookie cookie = new Cookie("JSESSIONID",sessionId); // resp.addCookie(cookie); }
Java Server Pages : Java服务器端页面,也和Servlet一样,用于动态Web技术!
JSP 本质上就是一个Servlet
在JSP中
只要是 JAVA代码就会原封不动的输出;
如果是HTML代码,就会被转换为:
out.write("<html>\r\n");
这样的格式输出到前端
<%-- JSP表达式 作用:用来将程序的输出,输出到客户端 <%= 变量或者表达式%> -- %> <%= new java.util.Date()%>
<%--jsp脚本片段--%> <% int sum = 0; for (int i = 1; i <=100 ; i++) { sum+=i; } out.println("<h1>Sum="+sum+"</h1>"); %> <% int x = 10; out.println(x); %> <p>这是一个JSP文档</p> <% int y = 2; out.println(y); %> <hr> <%--在代码嵌入HTML元素--%> <% for (int i = 0; i < 5; i++) { %> <h1>Hello,World <%=i%> </h1> <% } %>
<%! static { System.out.println("Loading Servlet!"); } private int globalVar = 0; public void kuang(){ System.out.println("进入了方法Kuang!"); } %>
JSP声明会被编译到JSP生成Java的类中!其他的,就会被生成到_jspService方法中!
脚本片段:<%%>
表达式:<%=%>
声明:<%!%>
<%–注释–%>
<%@page args.... %> <%@include file=""%> <%--@include会将两个页面合二为一,不可用同名局部变量--%> <%@include file="common/header.jsp"%> <h1>网页主体</h1> <%@include file="common/footer.jsp"%> <hr> <%--jSP标签 jsp:include:拼接页面,本质还是三个 --%> <jsp:include page="/common/header.jsp"/> <h1>网页主体</h1> <jsp:include page="/common/footer.jsp"/>
pageContext.setAttribute("name1","one"); //保存的数据只在一个页面中有效 request.setAttribute("name2","two"); //保存的数据只在一次请求中有效,请求转发会携 带这个数据 session.setAttribute("name3","three"); //保存的数据只在一次会话中有效,从打开浏览器 到关闭浏览器 application.setAttribute("name4","four"); //保存的数据只在服务器中有效,从打开服 务器到关闭服务器