1.创建JavaWeb
文件-->设置-->Maven
要设置不然TomCat配置里面找不到.war
1.1在main-->java下创建HelloServlet.java文件与GetServletContext.java
package com01; //HelloServlet.java文件 import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; public class HelloServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //context是凌驾于一切Servlet之上 ServletContext context = this.getServletContext(); String username1="CZY"; context.setAttribute("username",username1);//将数据保存在ServletContext中,名字为username,值为username1 } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
package com01; //GetServletContext.java文件 import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; public class GetServletContext extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { ServletContext context = this.getServletContext();//获得context String username = String.valueOf(context.getAttribute ("username")); resp.setCharacterEncoding("utf-8"); resp.setContentType("text/html"); resp.getWriter().print("名字:"+username); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
1.2想运行还需要配置.xml文件
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd" > <web-app> <display-name>Archetype Created Web Application</display-name> [在localhost:8080/s2/Hello运行] <servlet> <servlet-name>helloServlet</servlet-name> <servlet-class>com01.HelloServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>helloServlet</servlet-name> <url-pattern>/Hello</url-pattern> </servlet-mapping> [在localhost:8080/s2/get运行] <servlet> <servlet-name>GetServlet</servlet-name> <servlet-class>com01.GetServletContext</servlet-class> </servlet> <servlet-mapping> <servlet-name>GetServlet</servlet-name> <url-pattern>/get</url-pattern> </servlet-mapping> </web-app>
2.response
package com01; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.FileInputStream; import java.io.IOException; import java.net.URLEncoder; public class FileServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // 1.获取下载文件路径 String realPath = "D:\\JAVA\\JavaWeb\\Web02-Test01\\response\\target\\classes\\a.jpg"; 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 in = new FileInputStream(realPath); // 5.创建缓冲区 int len=0; byte[] buffer = new byte[1024]; // 6.获取outputStream ServletOutputStream out = resp.getOutputStream(); // 7.将FileInputStream写入buffer缓冲区,outputStream输出到客户端 while((len=in.read(buffer))!=-1) { out.write(buffer); } in.close(); out.close(); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
产生验证码
import javax.imageio.ImageIO; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.awt.*; import java.awt.image.BufferedImage; import java.io.IOException; import java.util.Random; public class 验证码 extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //让浏览器5秒自动刷新 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("expires",-1); resp.setHeader("Cache-Control","no-cache"); resp.setHeader("Pragma","no-cache"); //把图片写给浏览器 ImageIO.write(image,"jpg",resp.getOutputStream()); } private String makeNum() { Random random = new Random(); String num=random.nextInt(9999999)+""; StringBuffer sb = new StringBuffer(); for(int i=0;i<7-num.length();i++) { sb.append("0"); } num=sb.toString()+num; return num; } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
重定向
resp.sendRedirect("/is/image"); 【网址栏会发生变化】
获取参数
在jsp文件里 <%--action="${pageContext.request.contextPath}/request"可以获取位置--%> <form action="${pageContext.request.contextPath}/request" method="get">
package com01; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; public class RequestTest extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //getParameter是获取参数的意思 String username = req.getParameter("username"); String password = req.getParameter("password"); resp.getWriter().print(username+":"+password); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { super.doPost(req, resp); } }
Cookie使用
cookie是服务器给客户端的“信“,可存储 键-值数据
import javax.servlet.ServletException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; import java.util.Date; public class CookieDemo extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("text/html"); req.setCharacterEncoding("UTF-8"); resp.setCharacterEncoding("UTF-8"); PrintWriter out = resp.getWriter(); //从请求里获得cookie Cookie[] cookies = req.getCookies(); //判断cookie是否存在 if(cookies!=null) { out.write("上一次访问时间:"); for (Cookie cookie : cookies) { if(cookie.getName().equals("time")) { long value = Long.parseLong(cookie.getValue()); Date date = new Date(value); out.write(date.toLocaleString()); } } }else { out.write("第一次访问:"); } //服务器给客户端响应一个cookie Cookie cookie = new Cookie("time", System.currentTimeMillis()+""); //保存时间1天 cookie.setMaxAge(24*60*60); resp.addCookie(cookie); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
session使用
import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.IOException; public class sessiontest 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;charset=utf-8"); //获得Session HttpSession session = req.getSession(); //给Session存数据 session.setAttribute("name","CZY"); //获得ID String id = session.getId(); if(session.isNew()) { resp.getWriter().write("session创建成功,ID:"+id); } else { resp.getWriter().write("第一次"); } } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
还可以创建另一个java文件,可以实现跨servlet文件
HttpSession session = req.getSession(); session.getAttribute(名字) 【可以获得值】 session.removeAttribute(名字) 【删除】 session.invalidate(名字) 【关闭session】
<session-config> <session-timeout>15</session-timeout> 【15分钟结束】 </session-config>
jsp使用
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <%--该页面发生错误时跳转--%> <%@ page errorPage="error/500.jsp" %> <html> <body> <h2>Hello World!</h2> <%--弄一个错误的代码--%> <% int num=1/0; %> <%--<%= 【java代码,变量或者表达式】%>--%> <%= new java.util.Date()%> <%--<% 【java代码】 %>--%> <% int sum=0; for(int i=0;i<100;i++) { sum+=i; } out.print("<h2>sum="+sum+"</h2>"); %> <%--<%! 里面放全局变量 %>--%> <%! private int a=0; %> </body> </html>
【设置报错时跳转的页面】 <error-page> <error-code>500</error-code> <location>/error/500.jsp</location> </error-page>
【可以添加相同的网页部分】,页面会合在一起,不能一起用int a; <%@include file="common/header.jsp"> <h1>页面</h1> <%@include file="common/footer.jsp"> 方法二:jsp标签,本质还是3个页面 <jsp:include page="/common/header.jsp"/> <h1>页面</h1> <jsp:include page="/common/footer.jsp"/>
在Web2.4之后默认不使用${},故jsp文件需要加上<%@ page isELIgnored="false" %>
pageContext,request,session,application存储数据的区别
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@ page isELIgnored="false" %> <html> <head> <title>Title</title> </head> <body> <% pageContext.setAttribute("name1","a1");//保存的数据只在一个页面中有效 request.setAttribute("name2","a2");//保存的数据只在请求中有效 session.setAttribute("name3","a3");//保存的数据只在一次会话中存在,打开到关闭浏览器 application.setAttribute("name4","a4");//最高,打开服务器关闭服务器 %> <%--用pageContext找--%> <% String name1 = (String) pageContext.findAttribute("name1"); String name2 = (String) pageContext.findAttribute("name2"); String name3 = (String) pageContext.findAttribute("name3"); String name4 = (String) pageContext.findAttribute("name4"); String name5 = (String) pageContext.findAttribute("name5"); %> <h1><%=name1%></h1> <h1>${name2}</h1> <h1>${name3}</h1> <h1>${name4}</h1> <h1>${name5}</h1> <% 【跳转页面】 pageContext.forward("/index.jsp"); %> </body> </html>
跳转页面传递参数
【传递页面】 <jsp:forward page="shou.jsp"> <jsp:param name="name" value="小橙"></jsp:param> <jsp:param name="age" value="18"></jsp:param> </jsp:forward> 【被传递页面】获取参数 <% response.setCharacterEncoding("utf-8"); %> 名字: <%=request.getParameter("name")%> <br> 年龄:<%=request.getParameter("age")%>
使用JSTL核心标签必须加上<%@ taglib prefix="c" uri="Oracle Java Technologies | Oracle" %>t
<c:if test="${param.username=='admin'}" var="isAdmin"> <c:out value="欢迎你"></c:out> </c:if> <c:out value="${isAdmin}"></c:out> <c:if test="${判断条件}" var="isAdmin"> 【成功就执行下面】 <c:out value="欢迎你"></c:out> </c:if> <c:out value="${isAdmin}"></c:out>
<%--定义一个变量score,值为85--%> <c:set var="score" value="85"></c:set> <%--进行选择,判断--%> <c:choose> <c:when test="${score>90}"> 优秀 </c:when> <c:when test="${score>80}"> 良好 </c:when> </c:choose>
<c:forEach var="people" items="${list}" begin="1" end="3" step="2"> <c:out value="${people}"></c:out> </c:forEach> <c:forEach var="自定义变量" items="${要遍历的}" begin="开始" end="末尾" step="自增数量"> <c:out value="${自定义变量}"></c:out> </c:forEach>
useBean使用
People类需要写get,set函数
<%-- Created by IntelliJ IDEA. User: DELL Date: 2022/5/11 Time: 17:53 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <%--useBean类似new People();--%> <jsp:useBean id="p" class="com01.People" scope="page"></jsp:useBean> <%--设置属性--%> <jsp:setProperty name="p" property="age" value="12"></jsp:setProperty> <jsp:setProperty name="p" property="name" value="小橙"></jsp:setProperty> <%--获得属性--%> 姓名:<jsp:getProperty name="p" property="name"/> 年龄:<jsp:getProperty name="p" property="age"/> </body> </html>
MVC
过滤器
在xml中配置
<filter> <filter-name>hello1</filter-name> <filter-class>com01.FilterTest</filter-class> </filter> <filter-mapping> <filter-name>hello1</filter-name> <url-pattern>/hello</url-pattern> </filter-mapping>
package com01; import javax.servlet.*; import java.io.IOException; public class FilterTest implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { System.out.println("初始化"); } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { servletRequest.setCharacterEncoding("utf-8"); servletResponse.setCharacterEncoding("utf-8"); servletResponse.setContentType("text/html;charset=UTF-8"); System.out.println("执行前"); filterChain.doFilter(servletRequest,servletResponse); System.out.println("执行后"); } @Override public void destroy() { System.out.println("销毁了"); } }
监听器
先配置xml
<listener> <listener-class>com01.ListenTest</listener-class> </listener>
package com01; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.*; import java.io.IOException; public class ListenTest extends HttpServlet implements HttpSessionListener{ @Override public void sessionCreated(HttpSessionEvent se) { ServletContext context = se.getSession().getServletContext(); Integer onlineCount = (Integer) context.getAttribute("OnlineCount"); if(onlineCount==null) { onlineCount=1; }else{ onlineCount++; } context.setAttribute("OnlineCount",onlineCount); } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.getWriter().write( this.getServletContext().getAttribute("onlineCount").toString()); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } @Override public void sessionDestroyed(HttpSessionEvent se) { } }