Java Server Pagejavascript
从用户角度看待 ,就是是一个网页 , 从程序员角度看待 , 实际上是一个java类, 它继承了servlet,因此能够直接说jsp 就是一个Servlet.html
html 多数状况下用来显示静态内容 , 一成不变的。 可是有时候咱们须要在网页上显示一些动态数据, 好比: 查询全部的学生信息, 根据姓名去查询具体某个学生。 这些动做都须要去查询数据库,而后在网页上显示。 html是不支持写java代码 , jsp里面能够写java代码。java
<%@ 指令名字 %>mysql
代表jsp页面中能够写java代码程序员
其实即便说这个文件是什么类型,告诉浏览器我是什么内容类型,以及使用什么编码sql
contentType="text/html; charset=UTF-8" text/html MIMEType 这是一个文本,html网页
pageEncoding jsp内容编码数据库
extends 用于指定jsp翻译成java文件后,继承的父类是谁,通常不用改。数组
import 导包使用的,通常不用手写。浏览器
session服务器
值可选的有true or false .
用于控制在这个jsp页面里面,可以直接使用session对象。
具体的区别是,请看翻译后的java文件 若是该值是true , 那么在代码里面会有getSession()的调用,若是是false : 那么就不会有该方法调用,也就是没有session对象了。在页面上天然也就不能使用session了。
指的是错误的页面, 值须要给错误的页面路径
上面的errorPage 用于指定错误的时候跑到哪个页面去。 那么这个isErroPage , 就是声明某一个页面究竟是不是错误的页面。
包含另一个jsp的内容进来。
<%@ include file="other02.jsp"%>
能够理解为静态包含 ,把包含的页面全部元素标签所有拿过来,与include动做标签不一样。把另一个页面的全部内容拿过来一块儿输出。 全部的标签元素都包含进来。
<%@ taglib prefix="" uri=""%> uri: 标签库路径 prefix : 标签库的别名
<jsp:include page=""></jsp:include> <jsp:param value="" name=""/> <jsp:forward page=""></jsp:forward>
<jsp:include page="other02.jsp"></jsp:include>
包含指定的页面, 这里是动态包含。 也就是不把包含的页面全部元素标签所有拿过来输出,而是把它的运行结果拿过来。
jsp:forward
<jsp:forward page=""></jsp:forward>
前往哪个页面。
<jsp:forward page="other02.jsp"></jsp:forward>
等同于
<% //请求转发 request.getRequestDispatcher("other02.jsp").forward(request, response); %>
意思是: 在包含某个页面的时候,或者在跳转某个页面的时候,加入这个参数。
向other02.jsp发送参数 <jsp:forward page="other02.jsp"> <jsp:param value="beijing" name="address"/> </jsp:forward>
在other02.jsp中获取参数 <br>收到的参数是:<br> <%= request.getParameter("address")%>
所谓内置对象,就是咱们能够直接在jsp页面中使用这些对象。 不用建立。
以上4个是做用域对象 ,
表示这些对象能够存值,他们的取值范围有限定。 setAttribute 和 getAttribute
使用做用域来存储数据<br> <% pageContext.setAttribute("name", "page"); request.setAttribute("name", "request"); session.setAttribute("name", "session"); application.setAttribute("name", "application"); %> 取出四个做用域中的值<br> <%=pageContext.getAttribute("name")%> <%=request.getAttribute("name")%> <%=session.getAttribute("name")%> <%=application.getAttribute("name")%>
做用域范围大小:
pageContext < request < session < application
做用域仅限于当前的页面。
还能够获取到其余八个内置对象。
做用域仅限于一次请求, 只要服务器对该请求作出了响应。 这个域中存的值就没有了。好比重定向是两次请求,重定向到的页面也取不到值
做用域限于一次会话(屡次请求与响应) 当中。
整个工程均可以访问, 服务器关闭后就不能访问了。
是为了简化我们的jsp代码,具体一点就是为了简化在jsp里面写的那些java代码。
注意:在Eclipse中没有代码提示
${表达式 }
若是从做用域中取值,会先从小的做用域开始取,若是没有,就往下一个做用域取。 一直把四个做用域取完都没有, 就没有显示。
<% pageContext.setAttribute("name", "page"); request.setAttribute("name", "request"); session.setAttribute("name", "session"); application.setAttribute("name", "application"); %> 按普通手段取值<br> <%= pageContext.getAttribute("name")%> <%= request.getAttribute("name")%> <%= session.getAttribute("name")%> <%= application.getAttribute("name")%> <br>使用EL表达式取出做用域中的值<br> ${ pageScope.name } ${ requestScope.name } ${ sessionScope.name } ${ applicationScope.name }
若是域中所存的是数组
<% String [] a = {"aa","bb","cc","dd"}; pageContext.setAttribute("array", a); %> 使用EL表达式取出做用域中数组的值<br> ${array[0] } , ${array[1] },${array[2] },${array[3] }
若是域中锁存的是集合
使用EL表达式取出做用域中集合的值<br> ${li[0] } , ${li[1] },${li[2] },${li[3] } <br>-------------Map数据----------------<br> <% Map map = new HashMap(); map.put("name", "zhangsna"); map.put("age",18); map.put("address","北京.."); map.put("address.aa","深圳.."); pageContext.setAttribute("map", map); %>
取出Map集合的值
<% Map map = new HashMap(); map.put("name", "zhangsna"); map.put("age",18); map.put("address","北京..");
map.put("address.aa","深圳.."); pageContext.setAttribute("map", map);
%> 使用EL表达式取出做用域中Map的值
${map.name } , ${map.age } , ${map.address } , ${map["address.aa"] }
从域中取值。 得先存值。 <%
//pageContext.setAttribute("name", "zhangsan"); session.setAttribute("name", "lisi..."); %>
直接指定说了,到这个做用域里面去找这个name
${ pageScope.name }
//先从page里面找,没有去request找,去session,去application
${ name }
指定从session中取值
${ sessionScope.name }
若是这份值是有下标的,那么直接使用[]
<% String [] array = {"aa","bb","cc"} session.setAttribute("array",array); %> ${ array[1] } --> 这里array说的是attribute的name
若是没有下标, 直接使用 .的方式去取
<% User user = new User("zhangsan",18); session.setAttribute("u", user); %> ${ u.name } , ${ u.age }
通常使用EL表达式,用的比较多的,都是从一个对象中取出它的属性值,好比取出某一个学生的姓名。
${ 对象名.成员 }
做用域相关对象
- pageScope
- requestScope
- sessionScope
- applicationScope
头信息相关对象
- header
- headerValues
参数信息相关对象
- param
- paramValues
全称 : JSP Standard Tag Library jsp标准标签库
简化jsp的代码编写。 替换 <%%> 写法。 通常与EL表达式配合
导入jar文件到工程的WebContent/Web-Inf/lib jstl.jar standard.jar
在jsp页面上,使用taglib 指令,来引入标签库
注意: 若是想支持 EL表达式,那么引入的标签库必须选择1.1的版本,1.0的版本不支持EL表达式。
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:set></c:set>
<c:if test=""></c:if>
<c:forEach></c:forEach>
c:set
<!-- 声明一个对象name, 对象的值 zhangsan , 存储到了page(默认) , 指定是session --> <c:set var="name" value="zhangsan" scope="session"></c:set> ${sessionScope.name }
c:if
判断test里面的表达式是否知足,若是知足,就执行c:if标签中的输出 , c:if 是没有else的。
<c:set var="age" value="18" ></c:set> <c:if test="${ age > 26 }"> 年龄大于了26岁... </c:if> <c:if test="${ age <= 26 }"> 年龄小于了26岁... </c:if> ------------------------------ 定义一个变量名 flag 去接收前面表达式的值,而后存在session域中 <c:if test="${ age > 26 }" var="flag" scope="session"> 年龄大于了26岁... </c:if>
c:forEach
从1 开始遍历到10 ,获得的结果 ,赋值给 i ,而且会存储到page域中, step , 增幅为2, <c:forEach begin="1" end="10" var="i" step="2"> ${i } </c:forEach> ----------------------------------------------- <!-- items : 表示遍历哪个对象,注意,这里必须写EL表达式。 var: 遍历出来的每个元素用user 去接收。 --> <c:forEach var="user" items="${list }"> ${user.name } ----${user.age } </c:forEach>
先写 login.jsp , 而且搭配一个LoginServlet 去获取登陆信息。
建立用户表, 里面只要有id , username 和 password
建立UserDao, 定义登陆的方法
/**
建立UserDaoImpl , 实现刚才定义的登陆方法。
public class UserDaoImpl implements UserDao { @Override public boolean login(String userName , String password) { Connection conn = null; PreparedStatement ps = null; ResultSet rs = null; try { //1. 获得链接对象 conn = JDBCUtil.getConn(); String sql = "select * from t_user where username=? and password=?"; //2. 建立ps对象 ps = conn.prepareStatement(sql); ps.setString(1, userName); ps.setString(2, password); //3. 开始执行。 rs = ps.executeQuery(); //若是可以成功移到下一条记录,那么代表有这个用户。 return rs.next(); } catch (SQLException e) { e.printStackTrace(); }finally { JDBCUtil.release(conn, ps, rs); } return false; } }
在LoginServlet里面访问UserDao, 判断登陆结果。 以区分对待
建立stu_list.jsp , 让登陆成功的时候跳转过去。
建立学生表 , 里面字段随意。
定义学生的Dao . StuDao
public interface StuDao { /** * 查询出来全部的学生信息 * @return List集合 */ List<Student> findAll(); }
对上面定义的StuDao 作出实现 StuDaoImpl
public class StuDaoImpl implements StuDao {
@Override public List<Student> findAll() { List<Student> list = new ArrayList<Student>(); Connection conn = null; PreparedStatement ps = null; ResultSet rs = null; try { //1. 获得链接对象 conn = JDBCUtil.getConn(); String sql = "select * from t_stu"; ps = conn.prepareStatement(sql); rs = ps.executeQuery();
//数据多了,用对象装, 对象也多了呢? 用集合装。 while(rs.next()){ //10 次 ,10个学生
Student stu = new Student(); stu.setId(rs.getInt("id")); stu.setAge(rs.getInt("age")); stu.setName(rs.getString("name")); stu.setGender(rs.getString("gender")); stu.setAddress(rs.getString("address")); list.add(stu); } } catch (SQLException e) { e.printStackTrace(); }finally { JDBCUtil.release(conn, ps, rs); } return list; } }
在登陆成功的时候,完成三件事情。
查询全部的学生
把这个全部的学生集合存储到做用域中。
跳转到stu_list.jsp
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //提交的数据有可能有中文, 怎么处理。 request.setCharacterEncoding("UTF-8"); response.setContentType("text/html;charset=utf-8"); //1. 获取客户端提交的信息 String userName = request.getParameter("username"); String password = request.getParameter("password"); //2. 去访问dao , 看看是否知足登陆。 UserDao dao = new UserDaoImpl(); boolean isSuccess = dao.login(userName, password); //3. 针对dao的返回结果,作出响应 if(isSuccess){ //response.getWriter().write("登陆成功."); //1. 查询出来全部的学生信息。 StuDao stuDao = new StuDaoImpl(); List<Student> list = stuDao.findAll(); //2. 先把这个集合存到做用域中。 request.getSession().setAttribute("list", list); //2. 重定向 response.sendRedirect("stu_list.jsp"); }else{ response.getWriter().write("用户名或者密码错误!"); }
}
在stu_list.jsp中,取出域中的集合,而后使用c标签 去遍历集合。
<table border="1" width="700"> <tr align="center"> <td>编号</td> <td>姓名</td> <td>年龄</td> <td>性别</td> <td>住址</td> <td>操做</td> </tr> <c:forEach items="${list }" var="stu"> <tr align="center"> <td>${stu.id }</td> <td>${stu.name }</td> <td>${stu.age }</td> <td>${stu.gender }</td> <td>${stu.address }</td> <td><a href="#">更新</a> <a href="#">删除</a></td> </tr> </c:forEach>
JSP
三大指令
page include taglib
三个动做标签 <jsp:include> <jsp:forward> <jsp:param>
九个内置对象
四个做用域 pageContext request session application out exception response page config
${ 表达式 }
取4个做用域中的值
${ name }
有11个内置对象。
pageContext pageScope requestScope sessionScope applicationScope header headerValues param paramValues cookie initParam
使用1.1的版本, 支持EL表达式, 1.0不支持EL表达式
拷贝jar包, 经过taglib 去引入标签库
<c:set> <c:if> <c:forEach>
package com.itheima.util; import javax.servlet.http.Cookie; public class CookieUtil { /** * 从一个cookie数组中找到具体咱们想要的cookie对象 * @param cookies * @param name * @return */ public static Cookie findCookie(Cookie[] cookies , String name){ if(cookies != null){ for (Cookie cookie : cookies) { if(name.equals(cookie.getName())){ return cookie; } } } return null; } }
demo1
package com.itheima.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class Demo01 */ public class Demo01 extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //Cookie的简单使用。 //cookie 发送给客户端,而且保存在客户端上的一份小数据 response.setContentType("text/html;charset=utf-8"); /* * 方法参数要什么就给什么。 对象 * * 建立对象的几种手法 * * 1. 直接new * * 2. 单例模式 | 提供静态方法 * * 3. 工厂模式构建 stu * * StuFactory StuBuilder */ //发送cookie给客户端 Cookie cookie = new Cookie("aa", "bb"); //给响应,添加一个cookie response.addCookie(cookie); response.getWriter().write("请求成功了..."); //获取客户端带过来的cookie Cookie[] cookies = request.getCookies(); if(cookies != null){ for (Cookie c : cookies) { String cookieName = c.getName(); String cookieValue = c.getValue(); System.out.println(cookieName + " = "+ cookieValue); } } } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
demo2
package com.itheima.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class Demo02 */ public class Demo02 extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //取客户端发送过来的cookie. Cookie[] cookies = request.getCookies(); if(cookies != null){ for (Cookie cookie : cookies) { System.out.println(cookie.getName()+" = "+cookie.getValue()); } } //1. 先写cookie 能够给客户端返回多个cookie Cookie cookie = new Cookie("name", "zhangsan"); //2. 这个cookie的有效期。 默认状况下 , //关闭浏览器后,cookie就没有了。 ---> 针对没有设置cookie的有效期。 // expiry: 有效 以秒计算。 //正值 : 表示 在这个数字事后,cookie将会失效。 //负值: 关闭浏览器,那么cookie就失效, 默认值是 -1 cookie.setMaxAge(60 * 60 * 24 * 7); //赋值新的值 //cookie.setValue(newValue); //用于指定只有请求了指定的域名,才会带上该cookie cookie.setDomain(".itheima.com"); //只有访问该域名下的cookieDemo的这个路径地址才会带cookie cookie.setPath("/CookieDemo"); response.addCookie(cookie); Cookie cookie2 = new Cookie("age", "18"); response.addCookie(cookie2); response.getWriter().write("hello Cookie..."); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
demo3
package com.itheima.servlet; import java.io.IOException; import java.util.Date; 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 com.itheima.util.CookieUtil; /** * Servlet implementation class Demo03 */ public class Demo03 extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=utf-8"); String userName = request.getParameter("username"); String password = request.getParameter("password"); if("admin".equals(userName) && "123".equals(password)){ //获取cookie last-name --- > Cookie [] cookies = request.getCookies(); //从数组里面找出咱们想要的cookie Cookie cookie = CookieUtil.findCookie(cookies, "last"); //是第一次登陆,没有cookie if(cookie == null){ Cookie c = new Cookie("last", System.currentTimeMillis()+""); c.setMaxAge(60*60); //一个小时 response.addCookie(c); response.getWriter().write("欢迎您, "+userName); }else{ //1. 去之前的cookie第二次登陆,有cookie long lastVisitTime = Long.parseLong(cookie.getValue()); //2. 输出到界面, response.getWriter().write("欢迎您, "+userName +",上次来访时间是:"+new Date(lastVisitTime)); //3. 重置登陆的时间 cookie.setValue(System.currentTimeMillis()+""); response.addCookie(cookie); } }else{ response.getWriter().write("登录失败 "); } } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
package com.itheima.util; import javax.servlet.http.Cookie; public class CookieUtil { /** * 从一个cookie数组中找到具体咱们想要的cookie对象 * @param cookies * @param name * @return */ public static Cookie findCookie(Cookie[] cookies , String name){ if(cookies != null){ for (Cookie cookie : cookies) { if(name.equals(cookie.getName())){ return cookie; } } } return null; } }
package com.itheima.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class ClearHistory */ public class ClearHistory extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.getCookies(); //history : 1#2#4 //演练清除cookie : Cookie cookie = new Cookie("history",""); cookie.setMaxAge(0); //设置当即删除 cookie.setPath("/CookieDemo02"); response.addCookie(cookie); response.sendRedirect("product_list.jsp"); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
package com.itheima.servlet; import java.io.IOException; 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 com.itheima.util.CookieUtil; /** * Servlet implementation class ProductInfoServlet */ public class ProductInfoServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("----来到servlet----"); //获取到当前用户准备浏览的商品ID。 String id = request.getParameter("id"); Cookie[] cookies = request.getCookies(); Cookie cookie = CookieUtil.findCookie(cookies, "history"); //第一次浏览。 if(cookie == null){ System.out.println("----第一次访问----"); //1. 响应返回cookie Cookie c = new Cookie("history", id); //设置有效期。 c.setMaxAge(60*60*24*7); //设置访问这个工程的时候,才带cookie过来 c.setPath("/CookieDemo02"); response.addCookie(c); // //2. 跳转到具体界面 // response.sendRedirect("product_info.htm"); }else{ //第二次 //1. 获取之前的cookie , 由于之前的cookie , 包含了浏览记录123 String ids = cookie.getValue(); //2. 让如今浏览的商品, 和 之前浏览的商品,造成cookie新的值。 cookie.setValue(id+"#"+ids); //设置有效期。 cookie.setMaxAge(60*60*24*7); //设置访问这个工程的时候,才带cookie过来 cookie.setPath("/CookieDemo02"); response.addCookie(cookie); } //3. 跳转 response.sendRedirect("product_info.htm"); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
package com.itheima.domain; public class User { private String name; private int age ; public User(String name, int age) { super(); this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }
el_jsp
<%@page import="java.util.Map"%> <%@page import="java.util.HashMap"%> <%@page import="java.util.ArrayList"%> <%@page import="java.util.List"%> <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <% pageContext.setAttribute("name", "page"); request.setAttribute("name", "request"); session.setAttribute("name", "session"); application.setAttribute("name", "application"); %> 按普通手段取值<br> <%= pageContext.getAttribute("name")%> <%= request.getAttribute("name")%> <%= session.getAttribute("name")%> <%= application.getAttribute("name")%> <br>使用EL表达式取出做用域中的值<br> ${ pageScope.name } ${ requestScope.name } ${ sessionScope.name } ${ applicationScope.name } ${name } <br>-----------------------------<br> <% String [] a = {"aa","bb","cc","dd"}; pageContext.setAttribute("array", a); %> 使用EL表达式取出做用域中数组的值<br> ${array[0] } , ${array[1] },${array[2] },${array[3] } <br>-------------集合数据----------------<br> <% List list = new ArrayList(); list.add("11"); list.add("22"); list.add("33"); list.add("44"); //pageContext.setAttribute("li", list); session.setAttribute("li", list); %> 使用EL表达式取出做用域中集合的值<br> ${li[0] } , ${li[1] },${li[2] },${li[7] } <br>-------------Map数据----------------<br> <% Map map = new HashMap(); map.put("name", "zhangsna"); map.put("age",18); map.put("address","北京.."); map.put("address.aa","深圳.."); //pageContext.setAttribute("map", map); application.setAttribute("m", map); %> 使用EL表达式取出做用域中Map的值<br> ${applicationScope.m.name } , ${m.age } , ${m.address } , ${m["address.aa"] } </body> </html>
el02
<%@page import="com.itheima.domain.User"%> <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> 从域中取值。 得先存值。 <% //pageContext.setAttribute("name", "zhangsan"); session.setAttribute("name", "lisi..."); %> <br>直接指定说了,到这个做用域里面去找这个name<br> ${ pageScope.name } <br>//先从page里面找,没有去request找,去session,去application <br> ${ name } <br>指定从session中取值<br> ${ sessionScope.name } <br>---------------------------------------------<br> <% User user = new User("zhangsan",18); session.setAttribute("u", user); %> ${ u.name } , ${ u.age } ${ a > b} ${ a gt b } ${ empty u } </body> </html>
el03
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> 这是el03页面 <jsp:forward page="el04.jsp"> <jsp:param value="beijing...." name="address"/> </jsp:forward> </body> </html>
el04
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> 这是el04页面<br> <%=request.getParameter("address") %> <br> 使用EL表达式获取这个参数 <%-- response.addCookie(new Cookie("name","value")); ${cookie.name } --%> ${param.address } </body> </html>
jsp_action
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <%-- <jsp:include page=""></jsp:include> <jsp:param value="" name=""/> <jsp:forward page=""></jsp:forward> --%> 这是jsp_action的页面. <%-- <jsp:include page="other02.jsp"></jsp:include> --%> <%-- <jsp:forward page="other02.jsp"></jsp:forward> 等同于如下代码 --%> <% //请求转发 //request.getRequestDispatcher("other02.jsp").forward(request, response); %> <jsp:forward page="other02.jsp"> <jsp:param value="beijing" name="address"/> </jsp:forward> </body> </html>
jstl
<%@page import="com.itheima.domain.User"%> <%@page import="java.util.List"%> <%@page import="java.util.ArrayList"%> <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <!-- 声明一个对象name, 对象的值 zhangsan , 存储到了page(默认) , 指定是session --> <c:set var="name" value="zhangsan" scope="session"></c:set> ${sessionScope.name } <br>----------------------<br> <c:set var="age" value="18" ></c:set> <c:if test="${ age > 26 }" var="flag" scope="session"> 年龄大于了26岁... </c:if> <c:if test="${ age <= 26 }"> 年龄小于了26岁... </c:if> ${flag } <br>----------------------<br> 从1 开始遍历到10 ,获得的结果 ,赋值给 i ,而且会存储到page域中, step , 增幅为2, <c:forEach begin="1" end="10" var="i" step="2"> ${i } </c:forEach> <br>----------------------<br> <% List list =new ArrayList(); list.add(new User("zhangsan",18)); list.add(new User("lisi",28)); list.add(new User("wagnwu",38)); list.add(new User("maliu",48)); list.add(new User("qianqi",58)); pageContext.setAttribute("list", list); %> <!-- items : 表示遍历哪个对象,注意,这里必须写EL表达式。 var: 遍历出来的每个元素用user 去接收。 --> <c:forEach var="user" items="${list }"> ${user.name } ----${user.age } </c:forEach> </body> </html>
other
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %> <%-- <%@ include file="other02.jsp"%> --%> <%-- <%@ taglib prefix="" uri=""%> --%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <jsp:include page="other02.jsp"></jsp:include> 这是other页面的内容. </body> </html>
other2
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" isErrorPage="true"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <h3>这是other022222的内容</h3> <br>收到的参数是:<br> <%= request.getParameter("address")%> <% %> </body> </html>
other3
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> 这是other03的页面 <br>使用做用域来存储数据<br> <% pageContext.setAttribute("name", "page"); request.setAttribute("name", "request"); session.setAttribute("name", "session"); application.setAttribute("name", "application"); %> 取出四个做用域中的值<br> <%=pageContext.getAttribute("name")%> <%=request.getAttribute("name")%> <%=session.getAttribute("name")%> <%=application.getAttribute("name")%> <!-- //跳转到下一个界面去了 --> <% //请求转发. 一次请求 //request.getRequestDispatcher("other04.jsp").forward(request, response); //重定向 2次请求 response.sendRedirect("other04.jsp"); %> </body> </html>
other4
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <h3>这是04的页面</h3><br> 取出四个做用域中的值<br> <%=pageContext.getAttribute("name")%> <%=request.getAttribute("name")%> <%=session.getAttribute("name")%> <%=application.getAttribute("name")%> </body> </html>
other5
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> 这是other05的页面<br> <% out.write("这是使用out对象输出的内容"); %> <br> <% response.getWriter().write("这是使用response对象输出的内容"); %> </body> </html>
package com.itheima.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class LoginServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); String userName = request.getParameter("username"); String password = request.getParameter("password"); if("admin".equals(userName) && "123".equals(password)){ //response.getWriter().write("登陆成功"); /* * 早期的写法: * response.setStatus(302); response.setHeader("Location", "login_success.html");*/ //重定向写法: 从新定位方向 /根目录 response.sendRedirect("login_success.html"); //请求转发的写法: // request.getRequestDispatcher("login_success.html").forward(request, response); }else{ response.getWriter().write("登陆失败"); } } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }
package com.itheima.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; /** * Servlet implementation class Demo01 */ public class Demo01 extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = request.getSession(); //获得会话ID String id = session.getId(); //存值 //session.setAttribute(name, value); //取值 //session.getAttribute(name); //移除值 //session.removeAttribute(name); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
package com.itheima.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class LoginServlet */ public class LoginServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=utf-8"); String sessionid= request.getSession().getId(); System.out.println("sessionid="+sessionid); response.getWriter().write("收到请求了。。"); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }
package com.itheima.servlet; import java.io.IOException; import java.util.LinkedHashMap; import java.util.Map; import javax.servlet.ServletException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class CarServlet */ public class CarServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=utf-8"); //1. 获取要添加到购物车的商品id int id = Integer.parseInt(request.getParameter("id")); // 0 - 1- 2 -3 -4 String [] names = {"Iphone7","小米6","三星Note8","魅族7" , "华为9"}; //取到id对应的商品名称 String name = names[id]; //2. 获取购物车存放东西的session Map<String , Integer> iphoen7 3 //把一个map对象存放到session里面去,而且保证只存一次。 Map<String, Integer> map = (Map<String, Integer>) request.getSession().getAttribute("cart"); //session里面没有存放过任何东西。 if(map == null){ map = new LinkedHashMap<String , Integer>(); request.getSession().setAttribute("cart", map); } //3. 判断购物车里面有没有该商品 if(map.containsKey(name)){ //在原来的值基础上 + 1 map.put(name, map.get(name) + 1 ); }else{ //没有购买过该商品,当前数量为1 。 map.put(name, 1); } String sId = request.getSession().getId(); Cookie cookie = new Cookie("JSESSIONID", sId); cookie.setMaxAge(60*60*24*7); response.addCookie(cookie); //4. 输出界面。(跳转) response.getWriter().write("<a href='product_list.jsp'><h3>继续购物</h3></a><br>"); response.getWriter().write("<a href='cart.jsp'><h3>去购物车结算</h3></a>"); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
package com.itheima.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; /** * Servlet implementation class ClearCartServlet */ public class ClearCartServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = request.getSession(); //强制干掉会话,里面存放的任何数据就都没有了。 session.invalidate(); //从session中移除某一个数据 //session.removeAttribute("cart"); response.sendRedirect("cart.jsp"); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }
package com.itheima.util; import java.io.FileInputStream; import java.io.InputStream; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Properties; public class JDBCUtil { static String driverClass = null; static String url = null; static String name = null; static String password= null; static{ try { //1. 建立一个属性配置对象 Properties properties = new Properties(); // InputStream is = new FileInputStream("jdbc.properties"); //使用类加载器,去读取src底下的资源文件。 后面在servlet InputStream is = JDBCUtil.class.getClassLoader().getResourceAsStream("jdbc.properties"); //导入输入流。 properties.load(is); //读取属性 driverClass = properties.getProperty("driverClass"); url = properties.getProperty("url"); name = properties.getProperty("name"); password = properties.getProperty("password"); } catch (Exception e) { e.printStackTrace(); } } /** * 获取链接对象 * @return */ public static Connection getConn(){ Connection conn = null; try { Class.forName(driverClass); //静态代码块 ---> 类加载了,就执行。 java.sql.DriverManager.registerDriver(new Driver()); //DriverManager.registerDriver(new com.mysql.jdbc.Driver()); //DriverManager.getConnection("jdbc:mysql://localhost/test?user=monty&password=greatsqldb"); //2. 创建链接 参数一: 协议 + 访问的数据库 , 参数二: 用户名 , 参数三: 密码。 conn = DriverManager.getConnection(url, name, password); } catch (Exception e) { e.printStackTrace(); } return conn; } /** * 释放资源 * @param conn * @param st * @param rs */ public static void release(Connection conn , Statement st , ResultSet rs){ closeRs(rs); closeSt(st); closeConn(conn); } public static void release(Connection conn , Statement st){ closeSt(st); closeConn(conn); } private static void closeRs(ResultSet rs){ try { if(rs != null){ rs.close(); } } catch (SQLException e) { e.printStackTrace(); }finally{ rs = null; } } private static void closeSt(Statement st){ try { if(st != null){ st.close(); } } catch (SQLException e) { e.printStackTrace(); }finally{ st = null; } } private static void closeConn(Connection conn){ try { if(conn != null){ conn.close(); } } catch (SQLException e) { e.printStackTrace(); }finally{ conn = null; } } }
package com.itheima.servlet; import java.io.IOException; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.itheima.dao.StuDao; import com.itheima.dao.UserDao; import com.itheima.dao.impl.StuDaoImpl; import com.itheima.dao.impl.UserDaoImpl; import com.itheima.domain.Student; /** * 这是用于处理登陆的servlet */ public class LoginServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //提交的数据有可能有中文, 怎么处理。 request.setCharacterEncoding("UTF-8"); response.setContentType("text/html;charset=utf-8"); //1. 获取客户端提交的信息 String userName = request.getParameter("username"); String password = request.getParameter("password"); //2. 去访问dao , 看看是否知足登陆。 UserDao dao = new UserDaoImpl(); boolean isSuccess = dao.login(userName, password); //3. 针对dao的返回结果,作出响应 if(isSuccess){ //response.getWriter().write("登陆成功."); //1. 查询出来全部的学生信息。 StuDao stuDao = new StuDaoImpl(); List<Student> list = stuDao.findAll(); //2. 先把这个集合存到做用域中。 request.getSession().setAttribute("list", list); //2. 重定向 response.sendRedirect("stu_list.jsp"); }else{ response.getWriter().write("用户名或者密码错误!"); } } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
package com.itheima.dao; import java.util.List; import com.itheima.domain.Student; public interface StuDao { /** * 查询出来全部的学生信息 * @return List集合 */ List<Student> findAll(); }
package com.itheima.dao; /** * 该dao定义了对用户表的访问规则 */ public interface UserDao { /** * 这里简单就返回一个Boolean类型, 成功或者失败便可。 * * 可是开发的时候,登陆的方法,一旦成功。这里应该返回该用户的我的信息 * @param userName * @param password * * @return true : 登陆成功, false : 登陆失败。 */ boolean login(String userName , String password); }
package com.itheima.dao.impl; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import com.itheima.dao.StuDao; import com.itheima.domain.Student; import com.itheima.util.JDBCUtil; public class StuDaoImpl implements StuDao { @Override public List<Student> findAll() { List<Student> list = new ArrayList<Student>(); Connection conn = null; PreparedStatement ps = null; ResultSet rs = null; try { //1. 获得链接对象 conn = JDBCUtil.getConn(); String sql = "select * from t_stu"; ps = conn.prepareStatement(sql); rs = ps.executeQuery(); //数据多了,用对象装, 对象也多了呢? 用集合装。 while(rs.next()){ //10 次 ,10个学生 Student stu = new Student(); stu.setId(rs.getInt("id")); stu.setAge(rs.getInt("age")); stu.setName(rs.getString("name")); stu.setGender(rs.getString("gender")); stu.setAddress(rs.getString("address")); list.add(stu); } } catch (SQLException e) { e.printStackTrace(); }finally { JDBCUtil.release(conn, ps, rs); } return list; } }
package com.itheima.dao.impl; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import com.itheima.dao.UserDao; import com.itheima.util.JDBCUtil; import com.sun.corba.se.spi.orbutil.fsm.Guard.Result; public class UserDaoImpl implements UserDao { @Override public boolean login(String userName , String password) { Connection conn = null; PreparedStatement ps = null; ResultSet rs = null; try { //1. 获得链接对象 conn = JDBCUtil.getConn(); String sql = "select * from t_user where username=? and password=?"; //2. 建立ps对象 ps = conn.prepareStatement(sql); ps.setString(1, userName); ps.setString(2, password); //3. 开始执行。 rs = ps.executeQuery(); //若是可以成功移到下一条记录,那么代表有这个用户。 return rs.next(); } catch (SQLException e) { e.printStackTrace(); }finally { JDBCUtil.release(conn, ps, rs); } return false; } }
package com.itheima.domain; public class Student { //到底有哪些成员。 想要在页面上显示多少。 private int id ; private String name; private int age ; private String gender; private String address; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } }