Jsp學習
Jsp學習:
問題:
使用servlet進行用戶請求處理時,發現,使用Servlet盡心頁面響應時,
響應頁面的代碼寫起來過去麻煩,極大的影響了開發的效率。
解決:
使用jsp技術 java server page
使用:
jsp的訪問原理:
當瀏覽器發起一個jsp請求時,tomcat不是去直接執行jsp文件,而是先執行
JspServlet的文件。JspServlet會將被訪問的Jsp文件盡心轉譯,轉譯爲對應的Servlet文件
然後tomcat服務器繼續執行被jsp轉譯好的Servlet文件。
Jsp的基本語法:
Jsp的指令:
page指令:
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
language:設置jsp要轉譯的語言。
import:在轉譯爲java文件時,要導入的包。
pageEncoding:設置轉譯的編碼格式,以及響應編碼格式。
session:開始對session的支持,默認爲true,false爲關閉。
taglib指令:
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
作用:引入外部的資源文件,主要是引入jstl資源
jsp的代碼塊:
聲明局部代碼塊:<% java代碼 %> 可以聲明在jsp文件的任意位置。但是,會轉譯到_jspService方法中
聲明全局代碼塊:<%! 全局java代碼 %> 可以聲明在jsp文件的任意位置。但是,會轉譯爲全局代碼。
jsp的註釋: <%--註釋內容--%>
jsp的註釋,註釋的內容不會被轉譯。除了jsp註釋以外的其他語言的註釋都會被轉譯。
HTML+js+css+jQuery等前端語言的註釋不但會轉譯而且還會發送給瀏覽器
java代碼的註釋會轉譯,單不會被執行
jsp的腳本語句:
<%=要打印給客戶端的數據%>
注意:不要帶分號。
示例:
<font color="red" size="15"><% out.write((String)request.getAttribute("str")); %></font>
<font color="red" size="15"><%=(String)request.getAttribute("str")%></font>
Jsp的缺點:
做頁面的展現很方便,做業務邏輯處理特別麻煩
開發使用servlet做業務邏輯處理,jsp做頁面的展現。
Jsp的九大內置對象:jsp在轉譯的時候自動創建的九個對象。
pageContext:頁面上下文對象,此對象封存了另外八個。封存了jsp運行的所有數據。
作用域範圍:當前Jsp頁面
request:
sesssion:
application(ServlectContext):
response
out
config
page
exception
注意:tomcat和瀏覽器交互機制一定是根據URI執行Servlet。
jsp:
<%@ page language="java" import="java.util.*,java.lang.*" pageEncoding="utf-8" session="true"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>登錄頁面</title>
<meta charset=utf-8/>
</head>
<body>
<%!
//String st="6666";
public void test(){}
%>
<!--局部變量 -->
<%--
哈哈
--%>
<%
int a=3;
if(a>2){
%>
<h3>歡迎登錄506峽谷</h3>
<%
}
request.setAttribute("str", "真知棒");
%>
<font color="red" size="15"><% out.write((String)request.getAttribute("str")); %></font>
<font color="red" size="15"><%=(String)request.getAttribute("str")%></font>
<form action="#" method="get">
用戶名: <input type="text" name="uname" value=""/><br />
密碼 : <input type="password" name="pwd" value=""/><br />
<input type="submit" value="登錄"/>
</form>
</body>
</html>
El表達式
EL表達式學習:
問題:
在jsp中獲取作用域中的數據時,特別麻煩,需要強轉,導包。
解決:
使用EL表達式
特點:
獲取作用域中的數據的
如果沒有找到則什麼都不顯示
使用:
基本格式:
${作用域名.鍵名}或者${鍵名}
作用域查找順序
pageContext-->request--->session--->application
注意:
可以指定作用域獲取數據
${作用域名Scope.鍵名} 特殊:${pageScope.鍵名}
關係運算
${鍵名 關係運算符 鍵名}
總結:
El表達式主要是在jsp中獲取作用域中的數據的。
------------------------------------------------------------------------------------------
<h3>使用jsp方式獲取</h3>
<ul>
<li><%=request.getParameter("uname")%></li>
<li><%=request.getAttribute("str")%></li>
<li><%=((User)request.getAttribute("user")).getAddr().getTown() %></li>
<li><%=((ArrayList)request.getAttribute("list")).get(0) %></li>
<li><%=((User)((ArrayList)request.getAttribute("list")).get(2)).getAddr().getTown() %></li>
<li><%=((HashMap)request.getAttribute("hs")).get("v1") %></li>
<li><%=((User)(((HashMap)request.getAttribute("hs")).get("u"))).getAddr().getTown() %></li>
</ul>
<h3>使用El表達式方式獲取</h3>
<ul>
<li>${param.uname}</li>
<li>${str}</li>
<li>${user.addr.town}</li>
<li>${list[0]}</li>
<li>${list[2].addr.town}</li>
<li>${hs.v1}</li>
<li>${hs.u.addr.town}</li>
</ul>
練習源碼:
com.bjsxt.pojo:
Address.java:
package com.bjsxt.pojo;
public class Address {
private String pre;
private String city;
private String town;
public String getPre() {
return pre;
}
public void setPre(String pre) {
this.pre = pre;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getTown() {
return town;
}
public void setTown(String town) {
this.town = town;
}
@Override
public String toString() {
return "Address [pre=" + pre + ", city=" + city + ", town=" + town
+ "]";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((city == null) ? 0 : city.hashCode());
result = prime * result + ((pre == null) ? 0 : pre.hashCode());
result = prime * result + ((town == null) ? 0 : town.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Address other = (Address) obj;
if (city == null) {
if (other.city != null)
return false;
} else if (!city.equals(other.city))
return false;
if (pre == null) {
if (other.pre != null)
return false;
} else if (!pre.equals(other.pre))
return false;
if (town == null) {
if (other.town != null)
return false;
} else if (!town.equals(other.town))
return false;
return true;
}
public Address() {
super();
// TODO Auto-generated constructor stub
}
public Address(String pre, String city, String town) {
super();
this.pre = pre;
this.city = city;
this.town = town;
}
}
User.java:
package com.bjsxt.pojo;
public class User {
private int uid;
private String uname;
private int age;
private Address addr;
public int getUid() {
return uid;
}
public void setUid(int uid) {
this.uid = uid;
}
public String getUname() {
return uname;
}
public void setUname(String uname) {
this.uname = uname;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Address getAddr() {
return addr;
}
public void setAddr(Address addr) {
this.addr = addr;
}
@Override
public String toString() {
return "User [uid=" + uid + ", uname=" + uname + ", age=" + age
+ ", addr=" + addr + "]";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((addr == null) ? 0 : addr.hashCode());
result = prime * result + age;
result = prime * result + uid;
result = prime * result + ((uname == null) ? 0 : uname.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
User other = (User) obj;
if (addr == null) {
if (other.addr != null)
return false;
} else if (!addr.equals(other.addr))
return false;
if (age != other.age)
return false;
if (uid != other.uid)
return false;
if (uname == null) {
if (other.uname != null)
return false;
} else if (!uname.equals(other.uname))
return false;
return true;
}
public User() {
super();
// TODO Auto-generated constructor stub
}
public User(int uid, String uname, int age, Address addr) {
super();
this.uid = uid;
this.uname = uname;
this.age = age;
this.addr = addr;
}
}
com.bjsxt.servlet:
ElServlet.java:
package com.bjsxt.servlet;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.bjsxt.pojo.Address;
import com.bjsxt.pojo.User;
public class ElServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
//設置請求編碼格式
req.setCharacterEncoding("utf-8");
//設置響應編碼格式
resp.setCharacterEncoding("UTF-8");
resp.setContentType("text/html;charset=utf-8");
//獲取請求信息
String uname=req.getParameter("uname");
String upwd=req.getParameter("pwd");
//處理請求信息
System.out.println(uname+":"+upwd);
//響應處理結果
//字符串數據
req.setAttribute("str", "今天天氣真好,適合學習,666");
//對象數據
User u=new User(1,"德瑪西亞",7,new Address("召喚師峽谷","藍色方","三狼"));
req.setAttribute("user", u);
//集合數據
//list集合
ArrayList list=new ArrayList();
//字符數據
list.add("紅海行動");
list.add("唐探2");
//對象數據
list.add(new User(2, "關曉彤",20,new Address("河南","商丘", "梁園區")));
req.setAttribute("list", list);
//map集合
HashMap hs=new HashMap();
//字符數據
hs.put("v1", "小姐姐");
hs.put("v2", "小奶狗");
//對象數據
hs.put("u", new User(3, "楊紫",24, new Address("河南","商丘", "古城區")));
req.setAttribute("hs", hs);
//請求轉發
req.getRequestDispatcher("el.jsp").forward(req, resp);
//重定向
}
}
el.jsp:
<%@ page language="java" import="java.util.*,com.bjsxt.pojo.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>El表達式學習</title>
<meta charset="utf-8"/>
</head>
<body>
<h3>使用jsp方式獲取</h3>
<ul>
<li><%=request.getParameter("uname")%></li>
<li><%=request.getAttribute("str")%></li>
<li><%=((User)request.getAttribute("user")).getAddr().getTown() %></li>
<li><%=((ArrayList)request.getAttribute("list")).get(0) %></li>
<li><%=((User)((ArrayList)request.getAttribute("list")).get(2)).getAddr().getTown() %></li>
<li><%=((HashMap)request.getAttribute("hs")).get("v1") %></li>
<li><%=((User)(((HashMap)request.getAttribute("hs")).get("u"))).getAddr().getTown() %></li>
</ul>
<h3>使用El表達式方式獲取</h3>
<ul>
<li>${param.uname}</li>
<li>${str}</li>
<li>${user.addr.town}</li>
<li>${list[0]}</li>
<li>${list[2].addr.town}</li>
<li>${hs.v1}</li>
<li>${hs.u.addr.town}</li>
</ul>
<%--
El表達式學習:
1 基本格式:
${作用域的鍵名}
注意:如果是獲取request中的用戶請求數據${param.用戶數據的鍵名}
2 作用域的查找順序
從小到大依次查找數據,找到了就不再繼續查找了
pageContext--request--session---application
注意:
可以指定作用域獲取數據${作用域名Scope.鍵名}
特殊:pageContext使用pageScope獲取
3El表達式中可以進行簡單的邏輯運算
${鍵名 邏輯運算符 鍵名}
--%>
<%
pageContext.setAttribute("hello", "hello pageContext");
request.setAttribute("hello", "hello request");
session.setAttribute("hello", "hello session");
application.setAttribute("hello","hello application");
%>
<h3>作用域的查找順序</h3>
${pageScope.hello}---${requestScope.hello}--${sessionScope.hello}--${applicationScope.hello}
<h3>El表達式的邏輯運算</h3>
${1+2}--${2*4}--${1+"3"}--${1==1}--${1>2}--${2>1?"男":"女"}--${a}
</body>
</html>
jstl學習
Jstl學習:
問題:
我們在jsp頁面中不可避免的需要對數據的顯示效果做一些邏輯處理,
但是這樣造成jsp頁面代碼的編寫特別複雜,可閱讀性極差
解決:
使用jstl
內容:
核心標籤庫
格式化標籤庫
函數標籤庫
SQL標籤庫
XML標籤庫
使用(核心標籤庫:
1 在jsp頁面導入標籤庫
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
2 在jsp頁面使用標籤
練習源碼:
jstl.jsp
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%--
Jstl學習(核心標籤庫):
基本標籤:
輸出標籤
<c:out value="${鍵名}" default="默認值"></c:out>
作用:將value的值輸出到瀏覽器,如果EL表達式沒有獲取到數據,則使用默認值。
作用域數據存儲:
<c:set var="鍵名" value="值" scope="作用域名"></c:set>
注意:
默認是存儲到pageContext作用域中的
刪除作用域數據:
<c:remove var="要刪除的鍵名" scope="作用域名" />
注意:
在不指明作用域的情況下,會將四個作用域中該鍵的數據都刪掉。
邏輯標籤
單分支判斷:
<c:if test="判斷條件">執行體</c:if>
注意:
判斷條件必須使用EL表達式來進行書寫。
多分支判斷:
<c:choose>
<c:when test=""></c:when>
<c:when test=""></c:when>
...
<c:otherwise></c:otherwise>
</c:choose>
循環標籤(重):
<c:forEach begin="開始位置" end="結束位置" var="聲明記錄每次循環結果的變量,存儲在作用域中" step="步長" varStatus="記錄循環的狀態">
循環體
</c:forEach>
注意:
使用items屬性獲取要遍歷的集合對象
<c:forEach items="${ls}" var="i" >
${i}<br />
</c:forEach>
--%>
<%
request.setAttribute("str", "out標籤學習");
request.removeAttribute("str");
%>
<h3>基本標籤學習:</h3>
<!--輸出標籤 -->
<c:out value="jstl學習"></c:out>--jstl學習 <br/>
<c:out value="${str2}" default="哈哈"></c:out>--${str2}<br/>
<!--數據存儲標籤 -->
<c:set var="hello" value="hello pageContext" scope="page"></c:set>
<c:set var="hello" value="hello request" scope="request"></c:set>
<c:set var="hello" value="hello session" scope="session"></c:set>
<c:set var="hello" value="hello application" scope="application"></c:set>
${requestScope.hello}<br/>
<!--刪除作用域數據 -->
<c:remove var="hello" scope="page"/>
-----${hello}<br/>
<h3>邏輯標籤學習:</h3>
<!--單分支 -->
<c:if test="${2>3}">
<b>明天考試,加油</b>
</c:if>
<!--多分支 -->
<c:set var="a" value="60"></c:set>
<c:choose>
<c:when test="${a>90}">
<b>獎勵蘋果X一臺</b>
</c:when>
<c:when test="${a<=90&&a>80}">
<b>獎勵王者榮耀皮膚</b>
</c:when>
<c:when test="${a>=70&&a<=80}">
<b>獎勵一千塊練習冊</b>
</c:when>
<c:otherwise>
<b>男女混合雙打</b>
</c:otherwise>
</c:choose>
<h4>循環標籤:</h4>
<!--普通遍歷:指明循環的次數。 -->
<c:forEach begin="0" end="5" var="i" step="1" varStatus="vs">
aaaa${i}---${vs.index}---${vs.count}--${vs.first}--${vs.last}<br />
</c:forEach>
<!--集合遍歷 -->
<%
ArrayList<String> ls=new ArrayList<String>();
ls.add("哈哈");
ls.add("嘿嘿");
ls.add("呵呵");
request.setAttribute("ls", ls);
%>
<c:forEach items="${ls}" var="i" >
${i}<br />
</c:forEach>
登錄小案例
com.bjsxt.dao:
UserDao.java:
package com.bjsxt.dao;
import java.util.ArrayList;
import com.bjsxt.pojo.User;
public interface UserDao {
//驗證登錄
User checkUserInfo(String uname,String upwd);
//查詢cookie
User checkUserInfoByCookie(String uid);
//查詢所有用戶信息
ArrayList<User> selAllInfo();
}
com.bjsxt.daoImpl:
UserDaoImpl.java:
package com.bjsxt.daoImpl;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import com.bjsxt.dao.UserDao;
import com.bjsxt.pojo.User;
public class UserDaoImpl implements UserDao{
//驗證登錄
@Override
public User checkUserInfo(String uname, String upwd) {
//聲明JDBC變量
Connection conn=null;
PreparedStatement ps=null;
ResultSet rs=null;
User u=null;
try {
//加載驅動
Class.forName("com.mysql.jdbc.Driver");
//創建數據庫連接對象
conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/school","root","root");
//創建SQL命令
String sql="select * from t_user where uname=? and upwd=?";
//創建SQL命令對象
ps=conn.prepareStatement(sql);
//給佔位符賦值
ps.setString(1,uname);
ps.setString(2,upwd);
//執行SQL命令
rs=ps.executeQuery();
//遍歷查詢結果
while(rs.next()){
u=new User();
u.setUid(rs.getInt("uid"));
u.setUname(rs.getString("uname"));
u.setUpwd(rs.getString("upwd"));
u.setUphone(rs.getString("uphone"));
u.setRid(rs.getInt("rid"));
}
//返回結果
} catch (Exception e) {
// TODO: handle exception
}finally{
//關閉資源
if(rs!=null){
try {
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(ps!=null){
try {
ps.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(conn!=null){
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return u;
}
@Override
public User checkUserInfoByCookie(String uid) {
//聲明JDBC變量
Connection conn=null;
PreparedStatement ps=null;
ResultSet rs=null;
User u=null;
try {
//加載驅動
Class.forName("com.mysql.jdbc.Driver");
//創建數據庫連接對象
conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/school","root","root");
//創建SQL命令
String sql="select * from t_user where uid=?";
//創建SQL命令對象
ps=conn.prepareStatement(sql);
//給佔位符賦值
ps.setString(1,uid);
//執行SQL命令
rs=ps.executeQuery();
//遍歷查詢結果
while(rs.next()){
u=new User();
u.setUid(rs.getInt("uid"));
u.setUname(rs.getString("uname"));
u.setUpwd(rs.getString("upwd"));
u.setUphone(rs.getString("uphone"));
u.setRid(rs.getInt("rid"));
}
//返回結果
} catch (Exception e) {
// TODO: handle exception
}finally{
//關閉資源
if(rs!=null){
try {
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(ps!=null){
try {
ps.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(conn!=null){
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return u;
}
@Override
public ArrayList<User> selAllInfo() {
//聲明JDBC變量
Connection conn=null;
PreparedStatement ps=null;
ResultSet rs=null;
User u=null;
ArrayList<User> list=null;
try {
//加載驅動
Class.forName("com.mysql.jdbc.Driver");
//創建數據庫連接對象
conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/school","root","root");
//創建SQL命令
String sql="select * from t_user";
//創建SQL命令對象
ps=conn.prepareStatement(sql);
//給佔位符賦值
//執行SQL命令
rs=ps.executeQuery();
list=new ArrayList<User>();
//遍歷查詢結果
while(rs.next()){
u=new User();
u.setUid(rs.getInt("uid"));
u.setUname(rs.getString("uname"));
u.setUpwd(rs.getString("upwd"));
u.setUphone(rs.getString("uphone"));
u.setRid(rs.getInt("rid"));
list.add(u);
}
//返回結果
} catch (Exception e) {
// TODO: handle exception
}finally{
//關閉資源
if(rs!=null){
try {
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(ps!=null){
try {
ps.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(conn!=null){
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return list;
}
}
com.bjsxt.pojo:
User.java:
package com.bjsxt.pojo;
public class User {
private int uid;
private String uname;
private String upwd;
private String uphone;
private int rid;
public User() {
super();
// TODO Auto-generated constructor stub
}
public User(int uid, String uname, String upwd, String uphone, int rid) {
super();
this.uid = uid;
this.uname = uname;
this.upwd = upwd;
this.uphone = uphone;
this.rid = rid;
}
@Override
public String toString() {
return "User [uid=" + uid + ", uname=" + uname + ", upwd=" + upwd
+ ", uphone=" + uphone + ", rid=" + rid + "]";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + rid;
result = prime * result + uid;
result = prime * result + ((uname == null) ? 0 : uname.hashCode());
result = prime * result + ((uphone == null) ? 0 : uphone.hashCode());
result = prime * result + ((upwd == null) ? 0 : upwd.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
User other = (User) obj;
if (rid != other.rid)
return false;
if (uid != other.uid)
return false;
if (uname == null) {
if (other.uname != null)
return false;
} else if (!uname.equals(other.uname))
return false;
if (uphone == null) {
if (other.uphone != null)
return false;
} else if (!uphone.equals(other.uphone))
return false;
if (upwd == null) {
if (other.upwd != null)
return false;
} else if (!upwd.equals(other.upwd))
return false;
return true;
}
public int getUid() {
return uid;
}
public void setUid(int uid) {
this.uid = uid;
}
public String getUname() {
return uname;
}
public void setUname(String uname) {
this.uname = uname;
}
public String getUpwd() {
return upwd;
}
public void setUpwd(String upwd) {
this.upwd = upwd;
}
public String getUphone() {
return uphone;
}
public void setUphone(String uphone) {
this.uphone = uphone;
}
public int getRid() {
return rid;
}
public void setRid(int rid) {
this.rid = rid;
}
}
com.bjsxt.service:
UserService.java:
package com.bjsxt.service;
import java.util.ArrayList;
import com.bjsxt.pojo.User;
public interface UserService {
//驗證登錄
User checkUserInfoService(String uname,String upwd);
//查詢cookie
User checkUserInfoByCookieService(String uid);
//查詢所有用戶信息
ArrayList<User> selAllInfoService();
}
com.bjsxt.serviceImpl:
UserServiceImpl.java:
package com.bjsxt.serviceImpl;
import java.util.ArrayList;
import com.bjsxt.dao.UserDao;
import com.bjsxt.daoImpl.UserDaoImpl;
import com.bjsxt.pojo.User;
import com.bjsxt.service.UserService;
public class UserServiceImpl implements UserService{
//聲明數據庫層對象
UserDao u=new UserDaoImpl();
//驗證登錄
@Override
public User checkUserInfoService(String uname, String upwd) {
return u.checkUserInfo(uname, upwd);
}
@Override
public User checkUserInfoByCookieService(String uid) {
return u.checkUserInfoByCookie(uid);
}
@Override
public ArrayList<User> selAllInfoService() {
return u.selAllInfo();
}
}
com.bjsxt.servlet:
CookieServlet.java:
package com.bjsxt.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 javax.servlet.http.HttpSession;
import com.bjsxt.pojo.User;
import com.bjsxt.serviceImpl.UserServiceImpl;
public class CookieServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
//設置請求編碼格式
req.setCharacterEncoding("utf-8");
//設置響應編碼格式
resp.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=utf-8");
//接收cookie
Cookie[] cs=req.getCookies();
//遍歷數組並找到uid
if(cs!=null){
for(Cookie c:cs){
String uid="";
if("uid".equals(c.getName())){
uid=c.getValue();
}
//查詢數據庫
UserServiceImpl us=new UserServiceImpl();
User u=us.checkUserInfoByCookieService(uid);
if(u!=null){
//將用戶數據存儲到session中
HttpSession hs=req.getSession();
hs.setAttribute("user", u);
//重定向
resp.sendRedirect("main.jsp");
}
}
}else{
//請求轉發
req.getRequestDispatcher("login.jsp").forward(req, resp);
}
}
}
MainServlet.java:
package com.bjsxt.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 com.bjsxt.pojo.User;
public class MainServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
//設置響應編碼格式
resp.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=utf-8");
resp.getWriter().write("<html>");
resp.getWriter().write("<head>");
resp.getWriter().write("<title>登錄頁面</title>");
resp.getWriter().write("<meta charset='utf-8'/>");
resp.getWriter().write("</head>");
resp.getWriter().write("<body>");
resp.getWriter().write("<h3>歡迎訪問506機場</h3>");
resp.getWriter().write("<hr />");
resp.getWriter().write("<font>"+((User)req.getSession().getAttribute("user")).getUname()+"</font>");
resp.getWriter().write("<a href='show'>點擊查看所有的用戶信息</a>");
resp.getWriter().write("</body>");
resp.getWriter().write("</html>");
}
}
ShowServlet.java:
package com.bjsxt.servlet;
import java.io.IOException;
import java.util.ArrayList;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.bjsxt.pojo.User;
import com.bjsxt.serviceImpl.UserServiceImpl;
public class ShowServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
//設置請求編碼格式
req.setCharacterEncoding("utf-8");
//設置響應編碼格式
resp.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=utf-8");
//處理請求
//創建Service對象
UserServiceImpl us=new UserServiceImpl();
ArrayList<User> list=us.selAllInfoService();
//處理響應結果
req.setAttribute("list", list);
//請求轉發
req.getRequestDispatcher("show.jsp").forward(req, resp);
}
}
UserServlet.java:
package com.bjsxt.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 javax.servlet.http.HttpSession;
import com.bjsxt.pojo.User;
import com.bjsxt.service.UserService;
import com.bjsxt.serviceImpl.UserServiceImpl;
public class UserServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
//設置請求編碼格式
req.setCharacterEncoding("utf-8");
//設置響應編碼格式
resp.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=utf-8");
//獲取用戶數據
String uname=req.getParameter("uname");
String upwd=req.getParameter("pwd");
//查詢數據庫驗證登錄
//聲明業務層對象
UserServiceImpl us=new UserServiceImpl();
User u= us.checkUserInfoService(uname, upwd);
//處理用戶數據
if(u!=null){
//創建cookie對象
Cookie c=new Cookie("uid", u.getUid()+"");
//設置過期時間3天
c.setMaxAge(3600*24*3);
//設置cookie到達路徑
c.setPath("/loginServlet/cookie");
//增加cookie
resp.addCookie(c);
//創建session並存儲用戶數據
HttpSession hs=req.getSession();
hs.setAttribute("user", u);
//重定向到main
resp.sendRedirect("main.jsp");
}else{
//攜帶信息
req.setAttribute("str", "密碼錯誤");
//請求轉發
req.getRequestDispatcher("login.jsp").forward(req, resp);
}
}
}
WebRoot:
login.jsp:
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>登錄頁面</title>
<meta charset="UTF-8"/>
</head>
<body>
<font color="red" size="15px">${str}</font>
<form action="user" method="get">
用戶名:<input type="text" name="uname" value="" /><br />
密碼:<input type="password" name="pwd" value="" /><br />
<input type="submit" value="登錄" />
</form>
</body>
</html>
main.jsp:
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'main.jsp' starting page</title>
<meta charset="utf-8"/>
</head>
<body>
<h3>歡迎訪問506機場</h3>
<hr />
${user.uname}
<a href="show">點擊查看所有用戶信息</a>
</body>
</html>
show.jsp:
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>顯示頁面</title>
<meta charset="utf-8" />
</head>
<body>
<table border="1px">
<tr>
<td>用戶ID</td>
<td>用戶名</td>
<td>用戶密碼</td>
<td>手機號</td>
<td>用戶權限</td>
</tr>
<c:forEach items="${list}" var="u">
<tr>
<td>${u.uid}</td>
<td>${u.uname}</td>
<td>${u.upwd}</td>
<td>${u.uphone}</td>
<td>${u.rid}</td>
</tr>
</c:forEach>
</table>
</body>
</html>
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>2018-3-8-loginServlet</display-name>
<servlet>
<description>This is the description of my J2EE component</description>
<display-name>This is the display name of my J2EE component</display-name>
<servlet-name>UserServlet</servlet-name>
<servlet-class>com.bjsxt.servlet.UserServlet</servlet-class>
</servlet>
<servlet>
<description>This is the description of my J2EE component</description>
<display-name>This is the display name of my J2EE component</display-name>
<servlet-name>CookieServlet</servlet-name>
<servlet-class>com.bjsxt.servlet.CookieServlet</servlet-class>
</servlet>
<servlet>
<description>This is the description of my J2EE component</description>
<display-name>This is the display name of my J2EE component</display-name>
<servlet-name>ShowServlet</servlet-name>
<servlet-class>com.bjsxt.servlet.ShowServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>UserServlet</servlet-name>
<url-pattern>/user</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>CookieServlet</servlet-name>
<url-pattern>/cookie</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>ShowServlet</servlet-name>
<url-pattern>/show</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
</web-app>
需要的資料:
mysql-connector-java-5.1.30.jar
使用時請修改數據庫連接參數並在數據庫中建表。
數據庫中的t_user表 字段爲 int uid ,varchar uname,varchar upwd,varchar uphone,int rid.
源碼地址:
鏈接:https://pan.baidu.com/s/1XuctOW6nsyjP6yYr7oDqSw 密碼:r8di
小結:
Jsp學習
El表達式
jstl學習
修改之前的小案例,都有jsp網頁代替用於顯示網頁的servlet》
jsp學習網站:http://www.runoob.com/jsp/jsp-tutorial.html
el表達式學習網站:http://www.runoob.com/jsp/jsp-expression-language.html
jstl學習網站:http://www.runoob.com/jsp/jsp-jstl.html
注意:
12、1、jsp執行的原理:http://blog.csdn.net/insistgogo/article/details/20788749
2、在訪問jsp頁面的時候服務器才把jsp轉成Servlet:
底層轉換過的servlet路徑:C:\apache-tomcat-7.0.56\work\Catalina\localhost\test\org\apache\jsp
3、<%=java代碼%>和<%java代碼%>的區別:
<%java代碼%>不會被執行,也就是不加response.getwrite().write(),所以用<%=java代碼%>輸出。
4、四大作用域:
pageContext:一個Jsp頁面
requset:一次請求
session:一次會話
Application(ServlectContext):整個項目
9大內置對象
pageContext:頁面上下文對象,此對象封存了另外八個。封存了jsp運行的所有數據。
作用域範圍:當前Jsp頁面
request:
sesssion:
application(ServlectContext):
response
out
config
page
exception
5、response和out是輸出對象。
6、EL表達式:EL(Expression Language) 是爲了使JSP寫起來更加簡單。表達式語言的靈感來自於 ECMAScript 和 XPath 表達式語言,它提供了在 JSP 中簡化表達式的方法,讓Jsp的代碼更加簡化。
作用:接收上一個頁面的數據
7、JSTL:JavaServer Pages Standard Tag Library:是一個不斷完善的開放源代碼的JSP標籤庫
作用:對數據進行邏輯處理顯示。 需要導包:<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
8、作業:
使用jsp,EL,jstl。替換昨天的servlet登錄頁面和主頁面,還有EL接收數據,JSTL處理邏輯代碼
9、<c:forEach> 基礎迭代標籤,接受多種集合類型
10、Myeclipse 集成jsp快捷鍵io.emmet.eclipse_1.0.0.201304090013.jar 放入Myeclipse的dropins文件夾下,快捷鍵補全 ctrl+E
11、Parameter是根據鍵名從HTML標籤裏獲取表單信息 Attrbute是四大對象間的數據傳遞12、EL表達式只能從作用域中取值。
13、創建一個JSP的時候需要配置上面的參數 utf-8 ,打開方式要jsp Editor
14、刪除一個servlet要把web.xml裏的東西也刪除