一.JSP
jsp:网页文件 html + java
Jsp的生命周期(第一次访问时稍慢):
1.创建jsp文件之后
2.Tomcat将jsp翻译成java文件(servlet)
3.将java文件编译生成文件(work文件夹)
4.加载类 实例化类 init service destroy
Jsp的页面构成:
1.html
2.指令标记<%@ %>
– page:用于定义JSP页面的某些属性,翻译时起作用,作用在整个JSP文件,与放置的位置无关
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
– include:JSP可以通过include指令来包含其他文件。被包含的文件可以是JSP文件、HTML文件或文本文件
<%@ include file="login.jsp" %>
– taglib:声明此JSP文件使用了自定义的标签,同时引用标签库,也指定了他们的标签的前缀
<%@ taglib uri="http://www.jspcentral.com/tags" prefix="public" %>
3.脚本段 <% java %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
4. 表达式 (执行结果并输出显示到页面上) <%= 变量名/方法的调用 %>
5.注释 <! -- 会显示在客户端 -->
<%-- 不会显示在客户端 --%>
6.声明 <%! 方法 %>
声明的方法在翻译时被加载,在调用时才生效
7.动作 ---封装了一些有固定功能的java代码
<jsp: >
8.EL表达式 ---- 获取值
9.JSTL标签库 ----- -封装了一些有固定功能的java代码
<c:if >
10.内置对象 (9个)
out---向网页输出内容
request---接收请求(一次请求)
response---返回响应
session---会话对象---在多个页面之间共享值
application---应用对象
page---指向当前JSP页面本身
exception---例外对象
pageContext---提供了对JSP页面内所有的对象及名字空间的访问
config---在一个Servlet初始化时,JSP引擎向它传递信息用的
11.pageContext:可以取其他作用域内的值
findAttribute方法可以按照作用域由小到大的顺序取值
pageContext request session application
当前页面 一次请求 整个会话 整个应用
cookie存值:客户端存值 (浏览器上 磁盘上)
(不属于内置对象) (string,string)--key对应value方式存值--存string类型值
使用时需要创建cookie对象--new
回显之前设置有效期:记录的时间
session存值:服务器端存值
(string,object)--key对应value方式存值--存object类型值
jsp的内置对象,直接使用
有效期:发呆时
•需求:MyJsp2.jsp显示当前时间,通过地址栏,复选框,文本框向MyJsp3.jsp页面传值
1 MyJsp2.jsp
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> 2 <%@page import="java.text.SimpleDateFormat"%> 3 <%@page import="sun.net.www.content.text.plain"%> 4 <% 5 String path = request.getContextPath(); 6 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; 7 %> 8 9 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 10 <html> 11 <head> 12 <base href="<%=basePath%>"> 13 14 <title>My JSP 'MyJsp2.jsp' starting page</title> 15 16 <meta http-equiv="pragma" content="no-cache"> 17 <meta http-equiv="cache-control" content="no-cache"> 18 <meta http-equiv="expires" content="0"> 19 <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> 20 <meta http-equiv="description" content="This is my page"> 21 <!-- 22 <link rel="stylesheet" type="text/css" href="styles.css"> 23 --> 24 25 </head> 26 27 <body> 28 <font>时间</font> 29 <%! 30 31 public String getTime(){ 32 33 Date d1=new Date(); 34 SimpleDateFormat sdf= new SimpleDateFormat("yyyy/MM/dd"); 35 String time=sdf.format(d1); 36 return time; 37 } 38 %> 39 <%=getTime() %> 40 41 42 <form action="MyJsp3.jsp?a=1" method="post"> 43 <input type="text" name="t"/> 44 隐藏域<input type="hidden" name="hi" value="隐藏域"/><br> 45 <input type="checkbox" name="boxs" value="篮球"/>篮球<br/> 46 <input type="checkbox" name="boxs" value="足球"/>足球<br/> 47 <input type="checkbox" name="boxs" value="乒乓球"/>乒乓球<br/> 48 <input type="checkbox" name="boxs" value="橄榄球"/>橄榄球<br/> 49 <input type="checkbox" name="boxs" value="羽毛球"/>羽毛球<br/> 50 <input type="submit" value="提交数据"/> 51 </form> 52 </body> 53 </html>
1 MyJsp3.jsp
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> 2 <% 3 String path = request.getContextPath(); 4 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; 5 %> 6 7 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 8 <html> 9 <head> 10 <base href="<%=basePath%>"> 11 12 <title>My JSP 'MyJsp3.jsp' starting page</title> 13 14 <meta http-equiv="pragma" content="no-cache"> 15 <meta http-equiv="cache-control" content="no-cache"> 16 <meta http-equiv="expires" content="0"> 17 <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> 18 <meta http-equiv="description" content="This is my page"> 19 <!-- 20 <link rel="stylesheet" type="text/css" href="styles.css"> 21 --> 22 23 </head> 24 25 <body> 26 <% 27 request.setCharacterEncoding("utf-8"); 28 response.setContentType("text/html;charset=utf-8"); 29 String a =request.getParameter("a"); 30 String box[]=request.getParameterValues("boxs"); 31 String t =request.getParameter("t"); 32 for(int i=0;i<box.length;i++){ 33 34 %> 35 36 <%=box[i] %><br> 37 <% 38 39 } 40 41 %> 42 43 44 <br/><%=t%><br/> 45 <font style="color:red">传递的变量a的值为:<%=a%></font> 46 </body> 47 </html>
跳转后结果
多个页面之间共享值:
1. 表单---传递String类型的值
隐含表单(隐藏域)hidden---传递String类型的值
2.地址?名=值 ---传递String类型的值
3.session:---在一次会话范围内的多个页面之间共享值
一次会话:从该用户第一次登录开始,到安全退出结束
存值和取值:key ----- value (Object)
Session有效期: (发呆时间,空闲时间)
tomcat下可以配置session的时效
配置路径:Tomcat---conf----web.xml
<session-config>
<session-timeout>30</session-timeout> 30分钟
</session-config>
session存值:
<%
//session发呆时间是10秒,参数为0代表销毁
session.setMaxInactiveInterval(10);
//向session作用域内存值
session.setAttribute("name","Pioneer.HengYu");
//SessionID ----- 区分不同的用户
out.println(session.getId());
%>
session取值:
<%
String str=(String)session.getAttribute("name");
out.println(str);
%>
•需求:用session,三个页面传obj类型值
1 Session1页面 2 3 <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> 4 <% 5 String path = request.getContextPath(); 6 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; 7 %> 8 9 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 10 <html> 11 <head> 12 <base href="<%=basePath%>"> 13 14 <title>My JSP 'Session.jsp' starting page</title> 15 16 <meta http-equiv="pragma" content="no-cache"> 17 <meta http-equiv="cache-control" content="no-cache"> 18 <meta http-equiv="expires" content="0"> 19 <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> 20 <meta http-equiv="description" content="This is my page"> 21 <!-- 22 <link rel="stylesheet" type="text/css" href="styles.css"> 23 --> 24 25 </head> 26 27 <body> 28 这里是session1 29 <a href="session/Session2.jsp">点击跳转</a> 30 <% 31 //session发呆时间是10秒,参数为0代表销毁 32 session.setMaxInactiveInterval(10); 33 //向session作用域内存值 34 session.setAttribute("name","里2"); 35 //SessionID ----- 区分不同的用户 36 out.println(session.getId()); 37 %> 38 <% 39 String str=(String)session.getAttribute("name"); 40 out.println(str); 41 %> 42 </body> 43 </html>
1 Session2页面 2 3 <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> 4 <% 5 String path = request.getContextPath(); 6 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; 7 %> 8 9 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 10 <html> 11 <head> 12 <base href="<%=basePath%>"> 13 14 <title>My JSP 'Session2.jsp' starting page</title> 15 16 <meta http-equiv="pragma" content="no-cache"> 17 <meta http-equiv="cache-control" content="no-cache"> 18 <meta http-equiv="expires" content="0"> 19 <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> 20 <meta http-equiv="description" content="This is my page"> 21 <!-- 22 <link rel="stylesheet" type="text/css" href="styles.css"> 23 --> 24 25 </head> 26 27 <body> 28 这里是session2 29 <a href="session/Session3.jsp">点击跳转</a> 30 31 <% 32 String str=(String)session.getAttribute("name"); 33 out.println(session.getId()); 34 out.println(str); 35 36 %> 37 </body> 38 </html>
1 Session3页面 2 3 <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> 4 <% 5 String path = request.getContextPath(); 6 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; 7 %> 8 9 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 10 <html> 11 <head> 12 <base href="<%=basePath%>"> 13 14 <title>My JSP 'Session3.jsp' starting page</title> 15 16 <meta http-equiv="pragma" content="no-cache"> 17 <meta http-equiv="cache-control" content="no-cache"> 18 <meta http-equiv="expires" content="0"> 19 <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> 20 <meta http-equiv="description" content="This is my page"> 21 <!-- 22 <link rel="stylesheet" type="text/css" href="styles.css"> 23 --> 24 25 </head> 26 27 <body> 28 这里是session3 29 <% 30 String str=(String)session.getAttribute("name"); 31 out.println(session.getId()); 32 out.println(str); 33 %> 34 </body> 35 </html>
运行结果
•需求: 普通用户的登录,如果用户直接访问主页,将该用户踢回登录页面 –防止非法登录
验证:1.先把生成的uuid存入session中
2.取用户输入的验证码
3.判断
文件路径
1 登录页面 2 3 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> 4 <% 5 String path = request.getContextPath(); 6 String basePath = request.getScheme() + "://" 7 + request.getServerName() + ":" + request.getServerPort() 8 + path + "/"; 9 %> 10 11 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 12 <html> 13 <head> 14 <base href="<%=basePath%>"> 15 16 <title>登录页</title> 17 18 <meta http-equiv="pragma" content="no-cache"> 19 <meta http-equiv="cache-control" content="no-cache"> 20 <meta http-equiv="expires" content="0"> 21 <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> 22 <meta http-equiv="description" content="This is my page"> 23 <!-- 24 <link rel="stylesheet" type="text/css" href="styles.css"> 25 --> 26 27 </head> 28 29 <body> 30 <form action="UserServlet" method="post" > 31 用户名 32 <input type="text" name="name"> 33 <br /> 34 密码 35 <input type="password" name="psw" /> 36 <br /> 37 验证码 38 <input type="text" name="clientCheck"/> 39 <img src="http://localhost:8088/myJsp/CheckImg"/> 40 <br/> 41 <input type="submit" value="登录"/> 42 43 </form> 44 </body> 45 </html>
1 创建一个Servlet,对用户的处理起名UserServlet 2 3 package com.neusoft.login; 4 5 import java.io.IOException; 6 import java.io.PrintWriter; 7 8 import javax.servlet.ServletException; 9 import javax.servlet.http.HttpServlet; 10 import javax.servlet.http.HttpServletRequest; 11 import javax.servlet.http.HttpServletResponse; 12 import javax.servlet.http.HttpSession; 13 14 public class UserServlet extends HttpServlet { 15 16 public void doGet(HttpServletRequest request, HttpServletResponse response) 17 throws ServletException, IOException { 18 this.doPost(request, response); 19 } 20 21 public void doPost(HttpServletRequest request, HttpServletResponse response) 22 throws ServletException, IOException { 23 // 设置字符集 24 request.setCharacterEncoding("utf-8"); 25 response.setContentType("text/html;charset=utf-8"); 26 27 28 // 获取用户名和密码,验证码 29 String name = request.getParameter("name"); 30 String psw = request.getParameter("psw"); 31 String clientCheck=request.getParameter("clientCheck"); //自己输入取到的值 32 33 34 // 判断是否正确:正确---index 错误----fail 判断验证码是否正确 35 HttpSession session = request.getSession(); 36 session.setMaxInactiveInterval(30); // 有效期30秒 37 String serverCheck=(String)session.getAttribute("serverCheck"); //验证码生成的值 38 39 40 if(!clientCheck.equals(serverCheck)){ 41 response.getWriter().print("验证码有误"); 42 response.setHeader("refresh", "3;url=http://localhost:8088/myJsp/login/Login.jsp");//验证码有误3秒返回登录页面 43 44 }else if (name.equals("Pioneer.HengYu") && psw.equals("123")) { 45 // 将name的值存入session作用域中 46 session.setAttribute("name", name); 47 request.getRequestDispatcher("index.jsp").forward(request, response); 48 } else { 49 response.sendRedirect("fail.jsp"); 50 } 51 52 } 53 54 }
1 index.jsp 2 3 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> 4 <% 5 String path = request.getContextPath(); 6 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; 7 %> 8 9 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 10 <html> 11 <head> 12 <base href="<%=basePath%>"> 13 14 <title>主页</title> 15 <meta http-equiv="pragma" content="no-cache"> 16 <meta http-equiv="cache-control" content="no-cache"> 17 <meta http-equiv="expires" content="0"> 18 <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> 19 <meta http-equiv="description" content="This is my page"> 20 <!-- 21 <link rel="stylesheet" type="text/css" href="styles.css"> 22 --> 23 </head> 24 25 <body> 26 <!--防止非法登录,不输入账号点登录,直接跳回主页--> 27 <% 28 if(session.getAttribute("name")==null){ 29 response.sendRedirect("login/Login.jsp"); 30 } 31 %> 32 33 <% 34 out.println(UUID.randomUUID().toString()); 35 %> 36 <h1>欢迎<%=session.getAttribute("name")%>登录</h1> 37 38 </body> 39 </html>
1 验证码图片的类 2 3 package com.neusoft.login; 4 5 6 7 import java.awt.Color; 8 import java.awt.Font; 9 import java.awt.Graphics; 10 import java.awt.image.BufferedImage; 11 import java.io.IOException; 12 import java.util.Random; 13 import java.util.UUID; 14 15 import javax.imageio.ImageIO; 16 import javax.servlet.ServletException; 17 import javax.servlet.http.HttpServlet; 18 import javax.servlet.http.HttpServletRequest; 19 import javax.servlet.http.HttpServletResponse; 20 import javax.servlet.http.HttpSession; 21 /** 22 * 生成随机图片(验证码) 23 * 24 */ 25 public class CheckImg extends HttpServlet { 26 27 public void doGet(HttpServletRequest request, HttpServletResponse response) 28 throws ServletException, IOException { 29 30 //生成验证码的背景图片 31 BufferedImage image = new BufferedImage(70, 25, 32 BufferedImage.TYPE_INT_RGB) ; 33 34 //通过画笔类向背景上画内容 35 Graphics g = image.getGraphics(); 36 g.setColor(Color.YELLOW); 37 g.setFont(new Font("黑体",Font.BOLD,20)); 38 39 //生成验证码 40 String uuid = UUID.randomUUID().toString(); 41 uuid = uuid.substring(0,4); 42 43 44 //把生成的随机内容保存到 session 会话作用域中 45 HttpSession session = request.getSession(); 46 session.setAttribute("serverCheck", uuid); 47 48 //画图 49 g.drawString(uuid, 15, 20); 50 51 //生成图片的干扰线条 52 for(int i=0;i < 5;i++) { 53 g.setColor(Color.red); 54 g.drawLine(new Random().nextInt(60), 55 new Random().nextInt(15), 56 new Random().nextInt(60)+10, 57 new Random().nextInt(15)+10); 58 } 59 60 61 ImageIO.write(image, "JPG", response.getOutputStream()); 62 } 63 64 }
1 web.xml中配置 2 3 <?xml version="1.0" encoding="UTF-8"?> 4 <web-app version="2.5" 5 xmlns="http://java.sun.com/xml/ns/javaee" 6 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 7 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 8 http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> 9 <servlet> 10 <servlet-name>UserServlet</servlet-name> 11 <servlet-class>com.neusoft.login.UserServlet</servlet-class> 12 </servlet> 13 14 <servlet-mapping> 15 <servlet-name>UserServlet</servlet-name> 16 <url-pattern>/UserServlet</url-pattern> 17 </servlet-mapping> 18 <welcome-file-list> 19 <welcome-file>index.jsp</welcome-file> 20 </welcome-file-list> 21 22 <servlet> 23 <servlet-name>CheckImg</servlet-name> 24 <servlet-class>com.neusoft.login.CheckImg</servlet-class> 25 </servlet> 26 <servlet-mapping> 27 <servlet-name>CheckImg</servlet-name> 28 <url-pattern>/CheckImg</url-pattern> 29 </servlet-mapping> 30 31 32 </web-app>
执行结果
主页
填写正确跳转
账号密码填错,验证码填对跳转
验证码填错,3秒返回Loogin.jsp