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里的东西也删除