el表达式
EL是为了使JSP写起来更加简单,使代码更加简化。
用于从域对象里面取得数据(page request session application四大域对象,都可以通过setAttribute来存入数据)
写在页面部分的,不是写在java代码部分
例:el.jsp
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
Insert title here
<%
request.setAttribute("number", 2000);
session.setAttribute("user", "QP");
application.setAttribute("count", "ahodfhaif");
%>
在线人数为:${requestScope.number }
${sessionScope.user }
${applicationScope.count }
在login.jsp里用el表达式进行优化
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
Insert title here
<%-- <% --%>
<%-- %> --%>
${msg }
el表达式从map集合和对象中取得数据
注:el表达式是可以和java代码混合使用的
index.jsp
<%@page import="model.User"%>
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
Insert title here
<%
Object user=session.getAttribute("user");
if(user==null){
%>
登录
注册
<%
}else{
%>
当前登录用户名:${user.username }
<%
// out.println("当前登录用户名:"+((User)user).getUsername());
}
%>
各种商品的展示
el.jsp
<%@page import="model.User"%>
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
Insert title here
<%
request.setAttribute("number", 2000);
session.setAttribute("users", "QP");
application.setAttribute("count", "ahodfhaif");
%>
<%
User u=new User("中国","123",20,"男",false);
request.setAttribute("user", u);
%>
${user.username }
${user.password }
map就是键值对,list是集合
添加元素时候map是put方法,list是add方法
Map map =new HashMap();
List list=new ArrayList();
用el表达式从list中取值
<%@page import="java.util.Map"%>
<%@page import="java.util.ArrayList"%>
<%@page import="java.util.List"%>
<%@page import="java.util.HashMap"%>
<%@page import="model.User"%>
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
Insert title here
<%
request.setAttribute("number", 2000);
session.setAttribute("users", "QP");
application.setAttribute("count", "ahodfhaif");
%>
<%
List list=new ArrayList();
list.add(new User("中国","123",90,"男",false));
list.add(new User("中国1","123",90,"男",false));
list.add(new User("中国2","123",90,"男",false));
list.add(new User("中国3","123",90,"男",false));
request.setAttribute("list",list);
%>
${list[0].username }
${list[2].username }
el表达式还可以进行一些运算
${90+90 }
${90>80 }
${empty list }
${empty list2 }
empty用于判断一些attribute是否为空
返回值
180 true false true
el表达式不能直接访问request的,可以通过内置对象pageContext来访问request
${pageContext.request.contextPath }
<%--=request.getContextPath()--%>
引入jstl
jstl可以理解为就是一个标签库
先导入jstl的jar包
链接:https://pan.baidu.com/s/1JpVh0rCoxMwOUohR3-zaUA
提取码:02ag
引入方式,在开头加上
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
jstl用于存储相关的标签
jstl的if else语句
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
Insert title here
<%-- 18 --%>
你是成年人
你还未成年
jstl和el连用,其中取值基本都是el
jstl的循环
${i }
${u.username }:${u.password }:${u.age }
结果
1 2 3 4 5 6 7 8 9 10 中国:123:90
中国1:123:90
中国2:123:90
中国3:123:90
使用jstl和el来修改原来的页面
index.jsp
<%@page import="model.User"%>
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
Insert title here
登录
注册
当前登录用户名:${user.username }
各种商品的展示
goods_list.jsp
<%@page import="model.Goods"%>
<%@page import="java.util.List"%>
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
Insert title here
商品管理
添加
商品名 描述 价格 库存 操作
${g.name } ${g.des } ${g.price } ${g.inventory } 删除 修改
json
用于数据传输
数据格式基本和js一样
重点 对象和数组
对象:
{
"name":"QP",
"age":20,
"sex":"男"
}
数组
[1,2,3,4,5]
数组里面可以包含对象
[
{
"name":"QP",
"age":20,
"sex":"男"
} ,
{
"name":"QP",
"age":20,
"sex":"男"
} ,
{
"name":"QP",
"age":20,
"sex":"男"
}
]
json相关jar包可以从 json.org 里面找(所有语言的json解析包都有,不过可能不是最新版
https://mvnrepository.com/open-source/cloud-computing-integration 这里可以直接用名字搜新的jar包)
链接:https://pan.baidu.com/s/1-_6IJduwFNp9b3Tf-MZUVA
提取码:z3q1
fastjson的用法
package util;
import java.util.List;
import com.alibaba.fastjson.JSON;
public class JsonTest {
public static void main(String[] args) {
// 序列化
// Goods goods = new Goods("黄瓜", "好吃", 100, 400);
// String json = JSON.toJSONString(goods);
// System.out.println(json);
// 反序列化
// String s = "{\"des\":\"好吃\",\"inventory\":400,\"name\":\"黄瓜\",\"price\":100}";
// Goods goods = JSON.parseObject(s, Goods.class);
// System.out.println(goods.getName());
// 元素数组的反序列化
String s = "[" + "{" + " \"name\":\"QP\"," + " \"age\":20," + " \"sex\":\"男\"" + "} ," + "{"
+ " \"name\":\"QP\"," + " \"age\":21," + " \"sex\":\"男\"" + "} ," + "{" + " \"name\":\"QP\","
+ " \"age\":22," + " \"sex\":\"男\"" + "} " + "]";
List list = JSON.parseArray(s, UserTest.class);
for (UserTest ut : list) {
System.out.println(ut);
}
}
}
java自动将字符转义的用法:
String s=@"字符串";
会自动将冒号中的字符串转义,注意转义过将@去掉
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
Insert title here
ajaxServlet
package controller;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/ajaxrequest")
public class ajaxServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// getParameter是获取客户端通过url传过来的数据,数据储存在data属性当中
System.out.println("收到ajax请求" + req.getParameter("data"));
// 设置编码类型
resp.setContentType("text/html; charset=utf-8");
resp.getWriter().append("我是数据!");
}
}
利用ajax来实现注册请求
register.jsp
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
Insert title here
<%
if(request.getAttribute("msg")!=null)
out.println(request.getAttribute("msg")+"");
%>
VerifyUsernameServlet
package controller;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import service.UserService;
/**
* Servlet implementation class VerifyUsernameServlet
*/
@WebServlet("/verifyusername")
public class VerifyUsernameServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String username = request.getParameter("username");
UserService service = new UserService();
boolean isExist = service.isExist(username);
response.getWriter().append("{\"isSuccess\":" + !isExist + "}");
}
}
过滤器filter
用处:过滤请求,比如权限管理,中文参数,敏感词汇等。
创建filter
Test1Filter.java
package filter;
import java.io.IOException;
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.annotation.WebFilter;
/**
* Servlet Filter implementation class Test1Filter
*/
// /*表示过滤所有页面的请求
@WebFilter("/*")
public class Test1Filter implements Filter {
/**
* Default constructor.
*/
public Test1Filter() {
System.out.println("构造方法");
}
/**
* @see Filter#destroy()
*/
public void destroy() {
System.out.println("Destory");
}
/**
* @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
*/
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
System.out.println("doFilter");
// pass the request along the filter chain
chain.doFilter(request, response);
}
/**
* @see Filter#init(FilterConfig)
*/
public void init(FilterConfig fConfig) throws ServletException {
System.out.println("init");
}
}
@WebFilter("/login.jsp")
//表示只对login.jsp进行过滤
利用web.xml来配置filter的过滤路径
web.xml
web05
index.html
index.htm
index.jsp
default.html
default.htm
default.jsp
Test1Filter
filter.Test1Filter
Test1Filter
/*
这里filter的执行顺序是和web.xml里面配置的先后顺序有关的
先配置的先执行
Test2Filter.java
package filter;
import java.io.IOException;
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.annotation.WebFilter;
@WebFilter("/login.jsp")
public class Test2Filter implements Filter {
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
System.out.println("test2 Filter brfore");
chain.doFilter(request, response);
System.out.println("test2 Filter after");
}
public void init(FilterConfig fConfig) throws ServletException {
}
public void destroy() {
// TODO Auto-generated method stub
}
}
一般都是请求时候做过滤,响应的时候一般是不做过滤的,但也有情况需要用到响应过滤。
用过滤解决编码问题
EncodeFilter
package filter;
import java.io.IOException;
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.annotation.WebFilter;
/**
* Servlet Filter implementation class EncodeFilter
*/
@WebFilter("/EncodeFilter")
public class EncodeFilter implements Filter {
public void destroy() {
// TODO Auto-generated method stub
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
request.setCharacterEncoding("utf-8");
chain.doFilter(request, response);
}
public void init(FilterConfig fConfig) throws ServletException {
// TODO Auto-generated method stub
}
}
也可以直接设置初始化编码格式(在web.xml中设置)
web.xml
EncodeFilter
filter.EncodeFilter
Encoding
UTF-8
EncodeFilter
package filter;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
//@WebFilter("/EncodeFilter")
public class EncodeFilter implements Filter {
private String encoding;
public void destroy() {
// TODO Auto-generated method stub
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
request.setCharacterEncoding(encoding);
chain.doFilter(request, response);
}
public void init(FilterConfig fConfig) throws ServletException {
// 这里是从web.xml配置文件中获取名为Encoding的配置信息
encoding = fConfig.getInitParameter("Encoding");
}
}
权限管理(所有跟后台有关的页面我们规定都放在admin下面)
web.xml
AdminFilter
filter.AdminFilter
AdminFilter
/admin/*
AdminFilter
package filter;
import java.io.IOException;
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.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import model.User;
/**
* Servlet Filter implementation class AdminFilter
*/
@WebFilter("/AdminFilter")
public class AdminFilter implements Filter {
public void destroy() {
// TODO Auto-generated method stub
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest httpReq = (HttpServletRequest) request;
HttpServletResponse httpResp = (HttpServletResponse) response;
Object o = httpReq.getSession().getAttribute("user");
if (o == null) {
// 重定向的时候要加上项目名
httpResp.sendRedirect(httpReq.getContextPath() + "/index.jsp");
} else {
User u = (User) o;
if (u.isAdmin()) {
chain.doFilter(request, response);
} else {
httpResp.sendRedirect(httpReq.getContextPath() + "/index.jsp");
}
}
}
public void init(FilterConfig fConfig) throws ServletException {
// TODO Auto-generated method stub
}
}
设置过滤的请求类型
REQUEST 是普通请求
FORWORD 是转发过来的请求
INCLUDE 是用jsp标签里面include内含页面的那种请求(只有被包含那种才会被调用)
ERROR 是当页面来了一个错误的请求(比如404)
ERROR page配置
例:
web.xml
404
/dispatche1.jsp
设置过滤的请求类型
web.xml
DispatcherFilter
filter.DispatcherFilter
DispatcherFilter
/dispatcher1.jsp
REQUEST
监听器(用来监听request、session 和 application)
request 所属的类 HttpServletRequest
session 。。。 HTTPSession
application 。。。 ServletContext
监听器主要分为两大类
第一大类:监听这三个对象的创建和销毁
第二大类:监听这三个对象里面的属性
监听器也是一个类
实现监听器的接口
javax.servlet.ServletContextListener
HttpSessionListener
ServletRequestListener
ServletContextAttributeListener
HttpSessionAttributeListener
ServletRequestAttributeListener
配置
或者注解方式
@webListener
web.xml
SessionListener
设置生命周期
web.xml
1
Session绑定监听器
比如向model User中添加绑定监听器,则当Session中添加了User时该监听器触发
例:
在User里面绑定监听器
package model;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionBindingListener;
public class User implements HttpSessionBindingListener {
private String username;
private String password;
private int age;
private String sex;
private boolean isAdmin = false;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public boolean isAdmin() {
return isAdmin;
}
public void setAdmin(boolean isAdmin) {
this.isAdmin = isAdmin;
}
public User(String username, String password, int age, String sex, boolean isAdmin) {
super();
this.username = username;
this.password = password;
this.age = age;
this.sex = sex;
this.isAdmin = isAdmin;
}
@Override
public void valueBound(HttpSessionBindingEvent event) {
System.out.println("valueBound:" + event.getName() + ":" + event.getValue());
}
@Override
public void valueUnbound(HttpSessionBindingEvent event) {
System.out.println("valueUnbound");
}
}
单点登录
SessionManager.java
package util;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpSession;
public class SessionManager {
public static Map sessionMap = new HashMap();
}
SessionAttributeListener.java
package listener;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
import model.User;
import util.SessionManager;
@WebListener
public class SessionAttributeListener implements HttpSessionAttributeListener {
public SessionAttributeListener() {
// TODO Auto-generated constructor stub
}
public void attributeAdded(HttpSessionBindingEvent arg0) {
if (arg0.getName().equals("user")) {
User u = (User) arg0.getValue();
// 判断是否有其他客户端已经登录
if (SessionManager.sessionMap.containsKey(u.getUsername())) {
// 获得另外一个客户端的session
HttpSession session = SessionManager.sessionMap.get(u.getUsername());
// 把登陆信息从客户端抹除
session.removeAttribute("user");
// 从session集合里面移除对应的用户名
SessionManager.sessionMap.remove(u.getUsername());
}
SessionManager.sessionMap.put(u.getUsername(), arg0.getSession());
}
}
public void attributeRemoved(HttpSessionBindingEvent arg0) {
// TODO Auto-generated method stub
System.out.println("attributeRemoved");
}
public void attributeReplaced(HttpSessionBindingEvent arg0) {
// TODO Auto-generated method stub
System.out.println("attributeReplaced");
}
}