MVC模式修改用戶管理系統(tǒng)
對當(dāng)前網(wǎng)站結(jié)構(gòu)的問題分析
1. 在LoginCl.java 文件和ManageUser.java文件中都去操作了數(shù)據(jù)庫,它們的邏輯相似,有重復(fù)代碼
2: 整個框架沒有清晰的層次關(guān)系,顯得非常亂.
3:代碼一點也不優(yōu)雅, 可讀性差,可維護性差.
解決方法:
指導(dǎo)思想:
① 業(yè)務(wù)邏輯代碼和界面分離
② 把常用的代碼(對數(shù)據(jù)庫的連接和操作) 封裝到工具類
具體的方法
① 每一張表對應(yīng) 一個 domain類(表示數(shù)據(jù)) 還要對應(yīng)一個 Service 類
比如 users 表 對應(yīng) Users 類(domain 類) UserService類(該類會封裝對users表的各種操作) ,實際上這里體現(xiàn)出 數(shù)據(jù) 和 操作分離的思想
上機練習(xí):
包登錄部分改成mvc模式 ,建議先保存一份項目,再改.
① 完成分頁的mvc模式改寫
首先在UsersService 類中添加方法
//? 為什么要返回ArrayList ,而不是我們想到 ResultSet
//1. ArrayList 中封裝 User對象,更加符合面向?qū)ο蟮木幊谭绞?nbsp; OOP
//2.我們通過 Resulst->User 對象->ArrayList 這樣ArrayList 和 Resultset沒有關(guān)系,就可以及時關(guān)閉數(shù)據(jù)庫資源.
public ArrayList getUsresByPage(int pageNow,int pageSize){
reutrn al;
}
練習(xí): 把我們的用戶管理系統(tǒng)出了 cookie 和 session 相關(guān)的功能不做,其它都做了.
一起完成用戶管理系統(tǒng)的crud操作
1. 一個請求對應(yīng)一個控制器
優(yōu)點: 邏輯清晰
缺點: 會造成控制器過多
可以這樣考慮:一類事務(wù)請求,我們做一個控制器,即讓該控制器可以處理多個請求,為了讓一個控制器去區(qū)分,不同的請求,我們可以這樣做:
在發(fā)出請求的同時,在帶一個type=del 或者 type=add 或者 type=update..., 在控制器中我們接收type的值,從而判斷用戶希望做什么事情!
關(guān)于跳轉(zhuǎn)到修改用戶界面有兩種思路:
(1) 傳遞用戶id號的同時,把用戶的其它信息一并傳遞,這樣可以減少數(shù)據(jù)庫查詢的次數(shù) (缺點: 增加網(wǎng)絡(luò)開銷 100字節(jié)*1000000*2 , 優(yōu)點: 減少對數(shù)據(jù)庫的一次操作)
(2) 只傳遞用戶id好,控制器接收到id后,再查詢數(shù)據(jù)庫,從而顯示.
添加用戶
(1) 用戶id號,我們做成子增長
在oracle中先建立一個sequece
create sequence users_seq
start with 11
increment by 1
minvalue 11
nomaxvalue
nocycle
nocache
課堂練習(xí)
添加查詢用戶功能:安裝老師給出網(wǎng)站結(jié)構(gòu)寫.
會話技術(shù)cookie和session
什么是會話
基本概念: 指用戶開一個瀏覽器,訪問一個網(wǎng)站,只要不關(guān)閉該瀏覽器,不管該用戶點擊多少個超鏈接,訪問多少資源,直到用戶關(guān)閉瀏覽器,整個這個過程我們稱為一次會話.
比如打電話.
為什么需要cookie技術(shù)(會話技術(shù))
如何保存用戶上次登錄時間
如何顯示用戶瀏覽歷史?
如何把登錄的用戶名和密碼電腦,下次登錄,不需要重新輸入:
解決之道—cookie
cookie的原理圖
cookie的小結(jié)
① cookie 是在服務(wù)端創(chuàng)建
② cookie 是保存在瀏覽器這端
③ cookie 的生命周期可以通過
cookie.setMaxAge(2000);
如果不設(shè)置setMaxAge則該cookie的生命周期當(dāng)瀏覽器關(guān)閉時,就消亡.
④ cookie 可以被多個瀏覽器共享(與session的區(qū)別)
⑤ 怎么理解
我們可以把cookie 想成一張表
如果cookie重名會有什么問題?
如果重名就會替換存在的cookie值.
⑥ 一個web應(yīng)用可以保存多個cookie,但保存在同一個cookie文本在客戶端瀏覽器下
⑦ cookie存放的時候是以明文方式存放,因此安全較低.,我們可以通過加密后保存.
->補講md5加密算法 :
請大家注意,以后我們的密碼都要使用加密存放,在驗證密碼的時候,對用戶輸入密碼,進行md5加密,然后該到數(shù)據(jù)庫去驗證。
md5算法
package com.hsp;
import java.security.*;
import java.security.spec.*;
class MD5_test {
public final static String MD5(String s) {
char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'a', 'b', 'c', 'd', 'e', 'f' };
try {
byte[] strTemp = s.getBytes();
MessageDigest mdTemp = MessageDigest.getInstance("MD5");
mdTemp.update(strTemp);
byte[] md = mdTemp.digest();
int j = md.length;
char str[] = new char[j * 2];
int k = 0;
for (int i = 0; i < j; i++) {
byte byte0 = md[i];
str[k++] = hexDigits[byte0 >>> 4 & 0xf];
str[k++] = hexDigits[byte0 & 0xf];
}
return new String(str);
} catch (Exception e) {
return null;
}
}
public static void main(String[] args) {
// MD5_Test aa = new MD5_Test();
System.out.print(MD5_test.MD5("韓順平"));
}
}
保存上次登錄時間
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
//先獲取cookie
// 假設(shè)我們 保存上次登錄時間的cookie "lasttime" "2011-11-11 12:12:12";
// 這里我們要考慮一個情況: 用戶第一次登錄 '您是第一次登錄..'
Cookie []cookies=request.getCookies();
boolean b=false;//假設(shè)沒有l(wèi)asttime cookie
if(cookies!=null){ //保證有cookie,取遍歷
for(Cookie cookie: cookies){
//取出名
String name=cookie.getName();
if("lasttime".equals(name)){
//顯示
out.println("您上次登錄時間是 "+cookie.getValue());
//更新時間
//把當(dāng)前日期保存cookie
SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String nowTime=simpleDateFormat.format(new java.util.Date());
Cookie mycookie=new Cookie("lasttime",nowTime);
mycookie.setMaxAge(7*3600*24);//保存一周
response.addCookie(mycookie);
b=true;
break;
}
}
}
if(!b){
//沒有找到
out.println("您是第一次登錄..");
//把當(dāng)前日期保存cookie
SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String nowTime=simpleDateFormat.format(new java.util.Date());
Cookie cookie=new Cookie("lasttime",nowTime);
cookie.setMaxAge(7*3600*24);//保存一周
response.addCookie(cookie);
}
}
*上機練習(xí)
cookie自動保存用戶密碼
打開登錄頁面的時候,自動填寫該用戶的用戶名和密碼【這個要求學(xué)員課堂練習(xí)(最好單開一個項目)】
cookie保存瀏覽商品
請自己作為作業(yè)考慮實現(xiàn)
cookie的細節(jié)
① 一個瀏覽器最多放入 300cookie,一個web站點,最多 20cookie,而且一個cookie大小限制子4k
② cookie生命周期的再說明:
1. cookie默認生命周期是會話級別
2. 通過setMaxAge() 可以設(shè)置生命周期
setMaxAge(正數(shù)) , 即多少秒后該cookie失效
setMaxAge(0) ,刪除該cookie
setMaxAge(負數(shù)), 相當(dāng)于該cookie生命周期是會話級別.
案例 :
//先得到該cookie
Cookie cookies[]=request.getCookies();
for(Cookie cookie: cookies){
if(cookie.getName().equals("id")){
System.out.println("id");
//刪除
cookie.setMaxAge(0);
response.addCookie(cookie);//一定帶上這句話,否則不能刪除
}
}
特別說明: 如果該web應(yīng)用只有一個cookie ,則刪除該cookie后,在瀏覽器的臨時文件夾下沒有該cookie文件,如果該web應(yīng)用有多個cookie,則刪除一個cookie后,文件還在,只是該cookie沒有
③ cookie存放中文,怎么處理
存放:
String val=java.net.URLEncoder.encode("順平","utf-8");
Cookie cookie=new Cookie("name",val);
取出:
String val=java.net.URLDecoder.decode(cookie.getValue(), "utf-8");
out.println("name ="+val);
session為什么有?
問題1: 如何實現(xiàn)在不同的頁面,可以去查看信息(比如說購物車),同時還要實現(xiàn)不同的用戶看到的信息是自己.
session工作原理圖
session的生命周期是30分鐘
session 小結(jié):
① session是存在服務(wù)器的內(nèi)存中
② 一個用戶瀏覽器,獨享一個session域?qū)ο?br>③ session中的屬性的默認生命周期是30min ,你可以通過 web.xml來修改
④
3種session生命周期的設(shè)置
(1)一個地方是 tomcat/conf/web.xml
<session-config>
<session-timeout>30</session-timeout>//表示30分鐘的意思
</session-config>
對所有的web應(yīng)用生效
(2)另外一個地方,就是在單個web應(yīng)用的下去修改 web.xml
<session-config>
<session-timeout>30</session-timeout>session精確到分鐘,cookie精確到秒
</session-config>
如果發(fā)生沖突,則以自己的web應(yīng)用優(yōu)先級高
(3)session.setMaxInactiveinterval(60)發(fā)呆六十秒后session失效
對session和cookie生命周期小結(jié):
⑤ session中可以存放多個屬性
⑥ session 可以存放對象
⑦ 如果 session.setAttribute(“name”,val) , 如果名字重復(fù),則會替換該屬性.
?如果同一個用戶瀏覽器,向session設(shè)置一個屬性的時候,如果名字相同了,會出現(xiàn)什么情況?
結(jié)論: 會替換該對象值.
session的更深入理解:
為什么服務(wù)器能夠為不同的瀏覽器提供不同session?
因為每個瀏覽器去訪問web站點的時候,如果發(fā)出的http請求頭沒有帶JSESSIONID頭就會自動給你創(chuàng)建一個并返回
www.sourceforge.net [開源之祖]
生成驗證碼案例
使用(原理是使用到j(luò)ava的繪圖技術(shù).)
這里最重要的就是生成驗證碼的servlet
package com.hsp;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class CreateCode extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 7.禁止瀏覽器緩存隨機圖片
response.setDateHeader("Expires", -1);
response.setHeader("Cache-Control", "no-cache");
response.setHeader("Pragma", "no-cache");
// 6.通知客戶機以圖片方式打開發(fā)送過去的數(shù)據(jù)
response.setHeader("Content-Type", "image/jpeg");
// 1.在內(nèi)存中創(chuàng)建一副圖片
BufferedImage image = new BufferedImage(60, 30,
BufferedImage.TYPE_INT_RGB);
// 2.向圖片上寫數(shù)據(jù)
Graphics g = image.getGraphics();
// 設(shè)背景色
g.setColor(Color.BLACK);
g.fillRect(0, 0, 60, 30);
// 3.設(shè)置寫入數(shù)據(jù)的顏色和字體
g.setColor(Color.RED);
g.setFont(new Font(null, Font.BOLD, 20));
// 4.向圖片上寫數(shù)據(jù)
String num = makeNum();
//這句話就是把隨機生成的數(shù)值,保存到session
request.getSession().setAttribute("checkcode", num); 通過session就可以直接去到隨即生成的驗證碼了
g.drawString(num, 0, 20);
// 5.把寫好數(shù)據(jù)的圖片輸出給瀏覽器
ImageIO.write(image, "jpg", response.getOutputStream());
}
//該函數(shù)時隨機生成7位數(shù)字
public String makeNum() {
Random r = new Random();
//9999999 可以生成7位
String num = r.nextInt(9999) + "";
StringBuffer sb = new StringBuffer();
//如果不夠4位,前面補零
for (int i = 0; i < 4 - num.length(); i++) {
sb.append("0");
}
num = sb.toString() + num;
return num;
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
如何適用
Login.java
<img src=”/驗證碼的url”/>
練習(xí),請大家把 驗證碼功能加入到用戶管理系統(tǒng).
過濾器(filter)
①開發(fā)過濾器的步驟:
1. 創(chuàng)建 繼承HttpServlet 同時實現(xiàn)Filter接口
2. 默認filter不生效,需要配置.
<!-- 自己配置的一個filter -->
<filter>
<filter-name>MyFilter</filter-name>
<filter-class>com.zhy.filter.MyFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>MyFilter</filter-name>
<url-pattern>/*</url-pattern> /*表示對該WEB的所有網(wǎng)頁都過濾
</filter-mapping>
3. 在filter的方法中添加業(yè)務(wù)邏輯.
package com.hsp.filter;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.hsp.domain.User;
public class MyFilter1 extends HttpServlet implements Filter {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doGet(request, response);
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
System.out.print("myfilter1...");
//獲取session
HttpServletRequest httpServletRequest=
(HttpServletRequest)request;
//看看請求的資源是什么
String uri=httpServletRequest.getRequestURI();
if(uri.startsWith("/UsersManager3/imgs")||uri.startsWith("/UsersManager3/Login")){
//直接放行.
chain.doFilter(request, response);
}else{
HttpSession session=httpServletRequest.getSession();
User user=(User) session.getAttribute("loginuser");
if(user!=null){
//該用戶合法,放行
chain.doFilter(request, response);
}else{
request.setAttribute("err", "請好好登陸");
httpServletRequest.getRequestDispatcher("/LoginServlet")
.forward(request, response);
}
}
}
public void init(FilterConfig arg0) throws ServletException {
// TODO Auto-generated method stub
}
}
過濾器鏈
實現(xiàn)方式 :
1. 在創(chuàng)建一個過濾器 (繼承HttpServlet 同時還要實現(xiàn)Filter接口)
2. 配置過濾器
配置過濾器的順序就可以決定調(diào)用過濾器的順序.
控制session的銷毀時間
對session的銷毀時間的討論—借助一個案例:
面試題: (應(yīng)用:關(guān)掉IE后,再開IE,上次購買的商品還在。->涉及到session銷毀時間)
分析
我們的session 生命周期如果是30min,該session不會隨瀏覽器的關(guān)閉,而自動銷毀.而會到30min后,才會被服務(wù)器銷毀.
我們使用代碼來實現(xiàn)該功能(session + cookie結(jié)合使用)
分析實現(xiàn)的思路:
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
HttpSession session = request.getSession();
session.setAttribute("name", "張輝胤");
out.println("創(chuàng)一個session并放入姓名屬性");
Cookie cookie = new Cookie("JSESSIONID", session.getId());
cookie.setMaxAge(60*30);
response.addCookie(cookie);
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
HttpSession httpSession = request.getSession();
String name = (String) httpSession.getAttribute("name");
out.println("name = "+name);
}
ie禁用cookie后使用session的方法
如何實現(xiàn)ie禁用cookie后,我們還可以繼續(xù)使用session.
簡易購物車的實例:
思路:
當(dāng)用戶點擊購買商品時,我們把該商品保存到session中,該session的結(jié)構(gòu)是
name val
mybookds hashMap對象
而hashmap的結(jié)構(gòu)是
key val
書號 書對象.
Book.java類;
具體的實現(xiàn),參看myCart項目
總節(jié)我們使用到的相關(guān)知識
(1) java基礎(chǔ)的集合 ArrayList HashMap LinkedHashmap(有序的)
(2) session技術(shù)
(3) servlet
(4) 單態(tài)
(5) 如何選擇不同的集合
list 集合都是有序
map 集合是無序
list和map集合都可以放入null
list可以放入相同的對象,而map也可以放相同對象 , 但是key不能重復(fù).
JSP筆記
1. 為什么需要servletContext
需求1
需求2
解決之道—ServletContext
原理圖:
快速入門
ServletContext
1. ServletContext 是在服務(wù)器
2. ServletContext 是被所有客戶端共享
3. ServletContext 是當(dāng)web應(yīng)用啟動的時候,自動創(chuàng)建
4. ServletContext 當(dāng)web應(yīng)用關(guān)閉/tomcat關(guān)閉/對web應(yīng)用reload 會造成servletContext銷毀.
對ServletContext的用法小結(jié)
獲取:
this.getServletContext(); this.getServletConfig().getServletContext();
添加屬性:
servletcontext.setAttribute(string,object);
取出屬性
servletcontext.getAttribute(“屬性名”)
刪除
setvletContext.removeAttribute(“屬性名”);
ServletContext的應(yīng)用
(1) 獲取WEB應(yīng)用的初始化參數(shù)
<!-- 如果希望所有的servlet都可以訪問該配置. -->
<context-param>
<param-name>name</param-name>
<param-value>scott</param-value>
</context-param>
如何獲取
String val= this.getServletContext().getInitParameter("name");
(2) 使用ServletContext實現(xiàn)跳轉(zhuǎn)
//目前我們跳轉(zhuǎn)到下一個頁面
//1 response.sendRedirect("/web應(yīng)用名/資源名");
//2 request.getRequestDispatcher("/資源名").forward(request, response);
/*
* 區(qū)別1. getRequestDispatcher 一個跳轉(zhuǎn)發(fā)生在web服務(wù)器 sendRedirect發(fā)生在瀏覽器
* 2. 如果request.setAttribute("name","順平") 希望下一個頁面可以使用 屬性值,則使用 getRequestDispatcher
* 3. 如果session.setAttribute("name2","順平3"), 希望下一個頁面可以使用 屬性值,則兩個方法均可使用,但是建議使用 getRequestDispatcher
* 4. 如果我們希望跳轉(zhuǎn)到本web應(yīng)用外的一個url,應(yīng)使用sendRedirect
*/
//3.這種方法和2一樣
this.getServletContext().getRequestDispatcher("/資源url").forward(request, response);
(3) 讀取文件,和獲取文件全路徑
//首先讀取到文件
InputStream inputStream=this.getServletContext().getResourceAsStream("dbinfo.properties");
//創(chuàng)建Properties
Properties pp=new Properties();
pp.load(inputStream);
out.println("name="+pp.getProperty("username"));
*如果文件放在src目錄下;則使用類加載器
//如果文件放在src目錄下,我們應(yīng)該使用類加載器來讀取
InputStream is=Servlet5.class.getClassLoader().getResourceAsStream("dbinfo.properties")
//獲取文件全路徑
//如果讀取到一個文件的全路徑
String path=this.getServletContext().getRealPath("/imgs/Sunset.jpg");
out.println("paht = "+path);
網(wǎng)站計數(shù)器的思考
分析 :
代碼:
我們建立一個文件recoder.txt文件,用于保存訪問量,可以可以保證穩(wěn)定增長.
實現(xiàn)方法
建立InitServlet ,用于初始化我的Servletcontext,和在關(guān)閉tomcat時保存訪問量
package com.hsp;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class InitServlet extends HttpServlet {
/**
* Destruction of the servlet. <br>
*/
public void destroy() {
System.out.println("init servlet destory()被調(diào)用..");
//把ServletContext值重新保存到文件.
//從record.txt文件中,讀取瀏覽量
//1.首先得到該文件真實路徑
String filePath=this.getServletContext().getRealPath("record.text");
//2.打開文件
try {
FileWriter filewriter=new FileWriter(filePath);
//為了讀取我們轉(zhuǎn)為BufferedReader
BufferedWriter bufferedWriter=new BufferedWriter(filewriter);
//從ServletContext讀取訪問量
String nums=(String) this.getServletContext().getAttribute("nums");
//重新寫會文件
bufferedWriter.write(nums);
//一定要關(guān)閉流
bufferedWriter.close();
filewriter.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
//關(guān)閉...
}
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doGet(request, response);
}
public void init() throws ServletException {
// Put your code here
//從record.txt文件中,讀取瀏覽量
//1.首先得到該文件真實路徑
String filePath=this.getServletContext().getRealPath("record.text");
//2.打開文件
try {
FileReader fileReader=new FileReader(filePath);
//為了讀取我們轉(zhuǎn)為BufferedReader
BufferedReader bufferedReader=new BufferedReader(fileReader);
String nums=bufferedReader.readLine();
//把nums添加到Servletcontext
this.getServletContext().setAttribute("nums", nums);
//一定要關(guān)閉流
bufferedReader.close();
fileReader.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
當(dāng)用戶登錄一次我們?nèi)〕鯯ervletContext取出,并+1,
//向servletContext中添加屬性
//1.先取出
String nums=(String) this.getServletContext().getAttribute("nums");
//如果有,則取出+1
this.getServletContext().setAttribute("nums", (Integer.parseInt(nums)+1)+"");
在Mange頁面顯示
String nums=this.getServletContext().getAttribute("nums").toString();
out.println("該管理頁面被訪問了 "+nums+" 次");
問:如果我們的tomcat異常退出,怎么辦.
使用線程,定時把ServletContext的值,刷新到recorder.txt 比如10min.
上機練習(xí):
最后說:
針對工具類 SqlHelper.java
1. 我們的鏈接數(shù)據(jù)庫的變量都是static,這樣有一個潛在危險.如果訪問量大,可能造成一些用戶等待超時.我們可以這樣做:
把static變量 改成 非 static
在調(diào)用SqlHelper時候,首先創(chuàng)建一個 SqlHelper對象,然后調(diào)用相應(yīng)的方法.
2. 我們的SqlHelper在查詢數(shù)據(jù)的 ResultSet 沒有在SqlHelper本類中關(guān)閉,不是太好,解決方案入下:
public static ResultSet executeQuery(String sql,String []parameters){
try {
ct=getConnection();
ps=ct.prepareStatement(sql);
if(parameters!=null&&!parameters.equals("")){
for(int i=0;i<parameters.length;i++){
ps.setString(i+1 , parameters[i]);
}
}
rs=ps.executeQuery();
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e.getMessage());
// TODO: handle exception
}finally{
//close(rs, ps, ct);
}
return rs;
}
上面的代碼可以修改成這樣:
jsp講解
jsp為什么會出現(xiàn)?
因為在開發(fā)web網(wǎng)站時候,發(fā)現(xiàn)servlet做界面比較麻煩,于是又有一個新的技術(shù)jsp
jsp是什么?
1. jsp運行在服務(wù)器
2. jsp(java server page)
3. jsp的基礎(chǔ)是servlet(相當(dāng)于對servlet進行一個包裝)
4. jsp是綜合技術(shù) jsp=html+css+javascript+java代碼+jsp標簽(servlet)
5. jsp無需配置.直接使用,如果你修改了jsp文件,不需要重新reload web應(yīng)用.
6. jsp如何方法 http://ip:8088/web應(yīng)用名/jsp路徑
7. jsp是一種動態(tài)網(wǎng)頁技術(shù).
快如入門案例
講解jsp的運行原理
Web服務(wù)器是如何調(diào)用并執(zhí)行一個jsp頁面的?
看上面的原理圖
Jsp頁面中的html排版標簽是如何被發(fā)送到客戶端的?
out.write(" <table border=1>\r\n");
out.write(" <tr><td>apple</td><td>melon</td><td>orange</td></tr>\r\n");
out.write(" <tr><td>apple</td><td>melon</td><td>orange</td></tr>\r\n");
out.write(" <tr><td>apple</td><td>melon</td><td>orange</td></tr>\r\n");
out.write(" <tr><td>apple</td><td>melon</td><td>orange</td></tr>\r\n");
out.write(" </table>\r\n");
Jsp頁面中的java代碼服務(wù)器是如何執(zhí)行的?
比如jsp是:
<%
int i=90;
int j=i+90;
%>
<h1>測試.</h1>
<%
out.println("j="+j);
%>
當(dāng)被翻譯成jsp后:java文件
public jspService(){
int i=90;
int j=i+90;
}
1. 就是有多個<% %> 其實相當(dāng)于是一個大的 <% %>
2. 在<% %> 中定義的變量,會成為service函數(shù)的局部變量.
Web服務(wù)器在調(diào)用jsp時,會給jsp提供一些什么java對象?
供提供了九個: 我們使用了 out 對象 --->Servlet 的 PrintWriter
說 jsp=html+css+js+java代碼+jsp語法(標簽 )
jsp的語法
① 指令元素
概念: 用于從jsp發(fā)送一個信息到容器,比如設(shè)置全局變量,文字編碼,引入包
1. page指令
<%@ page contentType="text/html;charset=gb2312"%>
常用的屬性:
contentType 和 pageEncoding的區(qū)別
contentType=“text/html;charset=utf-8” 指定網(wǎng)頁以什么方式顯示頁面
pageEncoding=“utf-8” 指定Servlet引擎以什么方法翻譯jsp->servlet 并 指定網(wǎng)頁以什么方式顯示頁面
2. include指令
用法:
<%@ include file=”文件路徑” %>
3. taglib指令
<mytag:xx 屬性 />
② 腳本元素
java片段:
<% java 代碼 %>
表達式:
<%=表達式 %>
<%
int i=90;
%>
<h1>顯示</h1>
<%
out.println("i="+i);
%>
<%=i*78-23 %>
定義變量
<%! int i=90; %>
定義函數(shù)
<%! public int getResult(int a,int b){return a+b;}%>
函數(shù)不能在
<% %> 定義.
面試題:
③ 動作元素
<jsp:forward file=””> 的作用
在開發(fā)jsp的過程中,我們通常把jsp放入WEB-INF目錄,目的是為了防止用戶直接訪問這些jsp文件.
在WebRoot下我們有一個入口頁面,它的主要轉(zhuǎn)發(fā)
<jsp:forword file=”/WEB-INF/xx.jsp”></jsp:forword> 寫.
<jsp:incluce file=””></jsp:inclcue>
動態(tài)引入:
<%@ include file=””%> 靜態(tài)引入
<jsp:incluce file=””></jsp:incule> 動態(tài)引入
相同點: 把一個文件引入到另外一個文件
區(qū)別:靜態(tài)引入 把兩個jsp翻譯成一個Servlet,所以被引入的文件不要包含<body><html>..
動態(tài)引入 把兩個jsp分別翻譯,所以被引入的jsp包含有<html><body>也可以.
修改jsp的模板:
mvc (m(model模型) v (view視圖) c(controller控制器)
mvc 它要求程序員做開發(fā)把 數(shù)據(jù)的輸入(使用jsp 視圖),數(shù)據(jù)的處理(使用Servlet 即 Controller 調(diào)用model完成.),數(shù)據(jù)的顯示(使用jsp),分開.
iso9001
作業(yè):
改寫項目成mvc
JSP的9個內(nèi)置對象
對象名 類型 作用域
request:請求對象 javax.servlet.ServletRequest的子類 Request
response:響應(yīng)對象 javax.servlet.ServletResponse的子類 Page
pageContext:頁面上下文對象 javax.servlet.jsp.PageContext Page
session:會話對象 javax.servlet.http.HttpSession Session
application:應(yīng)用程序?qū)ο?javax.servlet.ServletContext Application
out:輸出對象 javax.servlet.jsp.JspWriter Page
config:配置對象 javax.servlet.ServletConfig Page
page:頁面對象 java.lang.Object Page
exception:異常對象 java.lang.Throwable Page
getParameter
getParameterNames
getParameterValues
本站僅提供存儲服務(wù),所有內(nèi)容均由用戶發(fā)布,如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請
點擊舉報。