第75節:Java中的JSP,EL和JSTL 哭吧看不完的!!! 和`Session 請求轉發和重定向的區別: 1. 地址不一樣 2. 請求次數也不一樣 3. 數據無法傳遞 4.跳轉範圍有限制 5. 效率 請求轉發請求1次,只能對當前項目跳轉,重定向請求2次.重定向是無法傳遞的,重定向對跳轉範圍沒有 ...
第75節:Java中的JSP,EL和JSTL
哭吧看不完的!!!
Cookie
和`Session
請求轉發和重定向的區別:
- 地址不一樣
- 請求次數也不一樣
- 數據無法傳遞
4.跳轉範圍有限制 - 效率
請求轉發請求1次,只能對當前項目跳轉,重定向請求2次.重定向是無法傳遞的,重定向對跳轉範圍沒有限制.
Cookie
是伺服器發送給客戶端,存儲在客戶端的小數據.發送cookie
:
Cookie cookie = new Cookie("key", value");
response.addCookie(cookie);
伺服器返回cookie給客戶端
// 響應頭
Set-Cookie: a=b
接收cookie
Cookie[] cookies = request.getCookies();
客戶端提交數據的cookie
// Cookie: a=b;c=d;
Cookie
分會話cookie
和持久cookie
關閉cookie
,可以關閉瀏覽器.
持久的cookie
,在一段時間內有效
Cookie cookie = new Cookie("a","b");
cookie.setMaxAge(); // 秒
response.addCookie(cookie);
cookie.setDomain(".dashucoding.com");
// 只有帶上這個功能變數名稱的時候,才會有cookie
// 例如:www.dashucoding.com
cookie..setPath("/Demo");
// 要進行訪問上面的路徑才會帶cookie
http://localhost:8080/Demo
移除cookie
Cookie cookie = new Cookie("a","b");
cookie.setMaxAge(60*60*24);
response.addCookie(cookie);
// 獲取以前cookie,設置有效期
Cookie[] cookies = request.getCookies();
Cookie cookie = CookieUtil.findCookie(cookies,"a");
cookie.setMaxAge(0);
reponse.addCookie(cookie);
cookie
是存在客戶端的.
可以創建一個新的cookie
去替換
Cookie cookie = new Cookie("a","dashu");
cookie.setMaxAge(0);
response.addCookie(cookie);
Session
是基於Cookie
的一種會話技術.cookie
的安全隱患,是把數據存放在客戶端,下次訪問時,帶上這個數據,服務端就知道客戶端是誰.
Session
的數據是存放在服務端.
session
對應sessionid
傳遞給客戶端,是通過cookie
傳遞的.只要有sessiondi
,就可以獲取以前的數據.
HttpSession session = request.getSession();
session.setAttribute();
sesssion.getAttribute();
package com.dashucoding.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 {
// TODO Auto-generated method stub
HttpSession session = request.getSession();
// 得到會話ID
session.getId();
// 存值
//session.setAttribute(name, value);
// 取值
//session.getAttribute(name);
// 移植
//session.removeAttribute(name);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
session
創建:
request.getSession
銷毀
關閉伺服器,或自動會話過期,預設時間為30分鐘.
在進行訪問瀏覽器時,再次重啟是無法獲取以前的數據的,因為
sessionid
是通過cookie
來傳遞的,cookie
沒有設置有效期,關閉後,就cookie
刪除了,同時cookie
帶過來sessionid
同樣也沒有了.
手動設置cookie
String id = request.getSession().getId();
Cookie cookie = new Cookie("JSESSIONID",id);
cookie.setMaxAge(60*60*24*7);
response.addCookie(cookie);
JSP
和EL
和JSTL
什麼是JSP
JSP
就是一個網頁而已,或者是一個Java
類,繼承了servlet
,所以jsp
是一個servlet
.
jsp
設計目的是因為html
是顯示靜態內容,有時網頁要一些動態數據.html
是不支持java
代碼,jsp
支持java
代碼.
寫法
指令
<%@ %>
language
contentType內容類型
content-Type="text/html;charset=UTF-8"
pageEncoding jsp內容編碼
extends="httpjspbase"
用於指定jsp翻譯成java文件後,繼承的父類是誰
import導包使用,一般不用手寫
session
true or false
errorPage 錯誤的頁面.
isErrorPage="true" 顯示錯誤
errorPage="error.jsp" 呈現錯誤
errorPage 值需要給錯誤的頁面路徑
include
<%-- <%@ include file="other02.jsp"%> --%>
把另外一個頁面的內容拿過來
<%-- <%@ taglib prefix="" uri=""%> --%>
url標簽庫的路徑
prefix別名
include
和forward
<%--
<jsp:include page=""></jsp:include>
<jsp:param value="" name=""/>
<jsp:forward page=""></jsp:forward> --%>
<%-- <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>
jsp: param
<jsp:forward page="other02.jsp">
<jsp:param value="beijing" name="address"/>
</jsp:forward>
<%= request.getParameter("address")%>
小結
什麼是JSP
為什麼會有JSP
三大指令集
page
有什麼用,那麼怎麼用,有哪些常用的屬性
include
有什麼用,那麼怎麼用
taglib
有什麼用,怎麼用
JSP動作標簽
jsp:forword
jsp:include
jsp:param
jsp
的內置對象
四個作用域
pageContext
request
session
appiication
JSP
內置對象
內置對象是在jsp
頁面中使用的這些對象,不用創建
pageContext
request
session
application
exception
out
page
config
response
application: ServletContext
config: ServletConfig
out: JspWriter
page: Object
pageContext: PageContext
request: HttpServletRequest
session: HttpSession
final javax.servlet.jsp.PageContext pageContext;
javax.servlet.http.HttpSession session = null;
final javax.servlet.ServletContext application;
final javax.servlet.ServletConfig config;
javax.servlet.jsp.JspWriter out = null;
final java.lang.Object page = this;
javax.servlet.jsp.JspWriter _jspx_out = null;
javax.servlet.jsp.PageContext _jspx_page_context = null;
request, response
四個作用域
pageContext
request
session
application
作用域,就是這個對象可以在哪用,對象可以存值,取值範圍限定.
作用的對象是不一樣的
setAttribute
getAttribute
pageContext:作用域只能在當前頁面,PageContext
request:作用域限於一次請求
只要伺服器做出反應,域中的值就沒有了HttpServletRequest
session:限於一次會話,第二次會話就沒了,HttpSession
application:都有,都可以訪問,只有伺服器關閉後就不能訪問了.->ServletContext
一個工程只能有一個
exception -> Throwable
config -> ServletConfig
page -> Object -> 當前類的實例
response -> HttpServletResponse
out JSP -> JSPWriter
out
response.getWriter
out
對象輸出的內容是放到response
的緩衝區內的,先輸出response
本身的內容,然後才是out
裡面的內容.
exception -> Throwable
page -> Object -> 一般就是jsp翻譯成java類的實例對象 -> this -> 當前實例類
config -> ServletConfig
out -> JspWriter
response -> HttpServletResponse
pageContext -> PageContext: 作用域當前頁面
request -> HttpServletReques: 作用域限於一次請求
session -> HttpSession -> 作用域限於一次會話
application -> ServletContext
整個工程可以訪問,伺服器關閉後就不能進行訪問了
pageContext 也可以獲取其他8個內置對象
EL
表達式:
是什麼,怎麼用,也有內置對象?
// 作用域
pageScope
requestScope
sessionScope
applicationScope
// 請求頭
header
headerValues
參數
param
params
EL
表達式
簡化jsp
中java
的代碼.
${ 表達式 }
取值方式:
<%
String [] a = {"aa","bb","cc","dd"};
pageContext.setAttribute("array", a);
%>
<%
User user = new User {"zhangsan",18};
session.setAttribute("u", user);
%>
${u.name}, ${u.age}
<%@page import="com.dashucoding.domain.User"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta 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>
package com.dashucoding.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;
}
}
<%@page import="java.util.HashMap"%>
<%@page import="java.util.Map"%>
<%@page import="java.util.ArrayList"%>
<%@page import="java.util.List"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta 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>
EL表達式隱式對象
11個內置對象
${ }
pageCotext
pageScope
requestScope
sessionScope
applicationScope
請求參數
param
paramValues
請求頭
header
headerValues
cookie
initParam初始化參數
pageContext是PageContext實例,其他都是Map類.
EL內置對象
// 作用域
pageScope
requestScope
sessionScope
applicationScope
// 請求頭
header
headerValues
// 請求參數
param
params
cookie
全局初始化參數
initparam
pageContext
引入
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta 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>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta 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>
小結案例
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" %>
<%-- <%@ include file="other02.jsp"%> --%>
<%-- <%@ taglib prefix="" uri=""%> --%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<%-- <jsp:include page="other02.jsp"></jsp:include> --%>
這是other頁面的內容.
</body>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" isErrorPage="true"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h3>這是other022222的內容</h3>
<br>收到的參數是:<br>
<%= request.getParameter("address")%>
<%
%>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta 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>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta 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>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
這是other05的頁面<br>
<%
out.write("這是使用out對象輸出的內容");
%>
<br>
<%
response.getWriter().write("這是使用response對象輸出的內容");
%>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta 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>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" isErrorPage="true"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
伺服器正在維護,請稍後訪問..
<%-- <%=exception.toString() %> --%>
</body>
</html>
<%@page import="java.util.HashMap"%>
<%@page import="java.util.Map"%>
<%@page import="java.util.ArrayList"%>
<%@page import="java.util.List"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta 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>
JSTL介紹
jstl是什麼,用來做什麼.
el只能取值操作
jstl遍歷的效果
jstl. jsp standard tag library jsp標簽庫
簡化jsp,與el表達式配合
// 使用jstl
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:set var = "name" value="dashu"></c:set>
${name}
<c:set var = "name" value="dashu" scope="session"></c:set>
${sessionScope.name}
預設存儲的是page
<c:set var = "age" value="12" ></c:set>
<c:if text="${age>10}">
age大於10
</c:if>
<c:forEach begin="1" end="10" var="i" step="2">
${i}
</c:forEach>
學生信息管理系統
login.jsp -> 一個頁面
login_servlet -> 一個頁面
基本操作頁面 -> 查看學生列表
stu_list.jsp
獲取信息
查詢資料庫
判斷賬號信息
正確前往下一頁
錯誤,登錄失敗
案例:
package com.dashucoding.dao;
import java.util.List;
import com.dashucoding.domain.Student;
public interface StuDao {
/**
* 查詢出來所有的學生信息
* @return List集合
*/
List<Student> findAll();
}
package com.dashucoding.dao;
/*
* 定義
* 該Dao定義了對用戶表的訪問規則
* */
public interface UserDao {
/**
* 這裡簡單就返回一個Boolean類型, 成功或者失敗即可。
*
* 但是開發的時候,登錄的方法,一旦成功。這裡應該返回該用戶的個人信息
* @param userName
* @param password
*
* @return true : 登錄成功, false : 登錄失敗。
*/
boolean login(String userName , String password);
}
package com.dashucoding.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.dashucoding.dao.StuDao;
import com.dashucoding.domain.Student;
import com.dashucoding.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.dashucoding.dao.impl;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.dashucoding.dao.UserDao;
import com.dashucoding.util.JDBCUtil;
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.dashucoding.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;
}
}
package com.dashucoding.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.dashucoding.dao.StuDao;
import com.dashucoding.dao.UserDao;
import com.dashucoding.dao.impl.StuDaoImpl;
import com.dashucoding.dao.impl.UserDaoImpl;
import com.dashucoding.domain.Student;
/**
* Servlet implementation class LoginServlet
*/
public class LoginServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
// 提交的數據有可能有中文
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=utf-8");
// 獲取客戶端提交的信息
String userName = request.getParameter("username");
String password = request.getParameter("password");
// 去訪問dao , 看看是否滿足登錄
UserDao dao = new UserDaoImpl();
boolean isSuccess = dao.login(userName, password);
if (isSuccess) {
// response.getWriter().write("登錄成功.");
// 請求轉發
// 查詢所有的學生信息
StuDao stuDao = new StuDaoImpl();
List<Student> list = stuDao.findAll();
// 先把這個集合存到作用域
request.getSession().setAttribute("list", list);
// 重定向
response.sendRedirect("stu_list.jsp");
} else {
response.getWriter().write("用戶名或者密碼錯誤!");
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
package com.dashucoding.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;
}
}
}
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h2>歡迎學生管理系統</h2>
<form action="LoginServlet" method="post">
賬號: <input type="text" name="username" /><br>
密碼: <input type="password" name="password" /><br>
<input type="submit" value="登錄">
</form>
</body>
</html>
<%@ 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>
<html>
<head>
<meta charset="UTF-8">
<title>學生信息管理系統</title>
</head>
<body>
<br>學生列表<br>
<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">
<c:if test=""></c:if>
<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>
</table>
</body>
</html>
分析
login.jsp -> LoginServlet -> 獲取登錄信息
創建用戶表,
創建UserDao
創建UserDaoImple
LoginServlet裡面訪問UserDao,判斷登錄,
創建stu_list.jsp,讓登錄進入
創建學生表
定義Dao,StuDao
StuDao, StuDaoImpl
資料庫
小結
jsp
JSP -> 九個內置對象
page
include
taglib
<jsp:include>
<jsp:forward>
<jsp:param>
EL -> 11個內置對象
${ 表達式 }
取4個作用域中的值
pageContext
pageScope
requestScope
sessionScope
applicationScope
header
headerValues
param
paramValues
cookie
initParam
JSTL
<c:set>
<c:if>
<c:forEach>
如果看了覺得不錯
點贊!轉發!
達叔小生:往後餘生,唯獨有你
You and me, we are family !
90後帥氣小伙,良好的開發習慣;獨立思考的能力;主動並且善於溝通
簡書博客: 達叔小生
https://www.jianshu.com/u/c785ece603d1
結語
- 下麵我將繼續對 其他知識 深入講解 ,有興趣可以繼續關註
- 小禮物走一走 or 點贊