概念: Java Server Pages,Java服务端页面
简单理解:
- JSP = HTML + Java
- JSP作用:简化开发,避免了在Servlet中直接输出HTML标签
步骤:
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.2</version>
<scope>provided</scope>
</dependency>
JSP脚本分类:
<%...%>
:内容会直接放到 jspService()方法之中<%=...%>
:内容会放到out.print()中,作为out.print()的参数<%!...%>
:内容会放到jspService()方法之外,被类直接包含<%@ page import="com.huanglei.pojo.Brand" %>
<%@ page import="java.util.ArrayList" %>
<%@ page import="java.util.List" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
//查询数据库
List<Brand> brands = new ArrayList<Brand>();
brands.add(new Brand(1,"三只松鼠","三只松鼠",100,"三只松鼠,好吃不上火",1));
brands.add(new Brand(2,"优衣库","优衣库",200,"优衣库,服适人生",0));
brands.add(new Brand(3,"小米","小米科技有限公司",1000,"为发烧而生",1));
%>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<input type="button" value="新增"><br>
<hr>
<table border="1" cellspacing="0" width="800">
<tr>
<th>序号</th>
<th>品牌名称</th>
<th>企业名称</th>
<th>排序</th>
<th>品牌介绍</th>
<th>状态</th>
<th>操作</th>
</tr>
<%
for (int i = 0; i < brands.size(); i++) {
Brand brand = brands.get(i);
%>
<tr align="center">
<td><%=brand.getId()%></td>
<td><%=brand.getBrandName()%></td>
<td><%=brand.getCompanyName()%></td>
<td><%=brand.getOrdered()%></td>
<td><%=brand.getDescription()%></td>
<%
if (brand.getStatus() == 1){
%>
<td><%="启用"%></td>
<%
}else {
%>
<td><%="禁用"%></td>
<%
}
%>
<td><a href="#">修改</a> <a href="#">删除</a></td>
</tr>
<%
}
%>
</table>
</body>
</html>
Expression Language表达式语言,用于简化JSP页面内的Java代码
主要功能:获取数据
语法:${expression}
${brands}:
获取域中存储的key为brands的数据
JavaWeb中的四大域对象:
- page:当前页面有效
- request:当前请求有效
- session:当前会话有效
- application:当前应用有效
el表达式获取数据,会依次从这4个域中寻找,直到找到为止
jsp:
<%--
Created by IntelliJ IDEA.
User: LENOVO
Date: 2023/8/21
Time: 10:32
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
${users};
</body>
</html>
Serverlet:
package com.huanglei.Serverlets;
import com.huanglei.mapper.UserMapper;
import com.huanglei.pojo.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
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 java.io.IOException;
import java.io.InputStream;
import java.util.List;
@WebServlet("/dom1")
public class ServletDom1 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//获取数据
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> user = mapper.select();
//然后将数据传输
req.setAttribute("users",user);
req.getRequestDispatcher("/dom1.jsp").forward(req,resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doGet(req,resp);
}
}
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl<lartifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
<%@ taglib prefix= "c" uri= "http://java.sun.com/jsp/jstl/core" %>
c:if
:
<%--
Created by IntelliJ IDEA.
User: LENOVO
Date: 2023/8/22
Time: 16:20
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<c:if test="true">
正确
</c:if>
<c:if test="false">
错误,无法显示
</c:if>
</body>
</html>
:相当于for循环
items
:被遍历的容器
var
:遍历产生的临时变量
varStatus
:遍历状态对象
count
:从1开始遍历的数字
status
:从0开始遍历的数字
<%--
Created by IntelliJ IDEA.
User: LENOVO
Date: 2023/8/22
Time: 16:38
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<input type="button" value="新增"><br>
<hr>
<table border="1" cellspacing="0" width="800">
<tr>
<th>序号</th>
<th>用户名字</th>
<th>用户密码</th>
<th>用户邮箱</th>
</tr>
<%-- lists表示传输过来的数据集合,list表示的是集合当中的每一个数据--%>
<c:forEach items="${lists}" var="list">
<tr align="center">
<td>${list.userId}</td>
<td>${list.userName}</td>
<td>${list.userPassword}</td>
<td>${list.userEmail}</td>
<td><a href="#">修改</a> <a href="#">删除</a></td>
</tr>
</c:forEach>
</table>
</body>
</html>
MVC是一种分层开发的模式,其中
M
:Model,业务模型,处理业务
V
: View,视图,界面展示
C:
Controller,控制器,处理请求,调用模型和视图
MVC好处
1.
职责单一,互不影响
2.
有利于分工协作
3
.有利于组件重用
数据访问层
:对数据库的CRUD基本操作业务逻辑层
:对业务逻辑进行封装,组合数据访问层层中基本功能,形成复杂的业务逻辑功能表现层
:接收请求,封装数据,调用业务逻辑层,响应数据会话:用户打开浏览器,访问web服务器的资源,会话建立,直到有一方断开连接,会话结束。在一次会话中可以包含多次
请求和响应
会话跟踪:一种维护浏览器状态的方法,服务器需要识别多次请求是否来自于同一浏览器,以便在同一次会话的多次请求间共享数据
HTTP协议是无状态
的,每次浏览器向服务器请求时,服务器都会将该请求视为新的
请求,因此我们需要会话跟踪技术来实现会话内数据共享
实现方式:
1.客户端会话跟踪技术:Cookie
2.服务端会话跟踪技术:Session
Cookie基本使用
Cookie cookie = new Cookie("key" ,"value");
response.addCookie(cookie);
Cookie[] cookies = request.getCookies();
for(cookies:cookie){
}
cookie.getName();
cookie.getValue();
发送数据的案列(Cookie):
package com.itheima.Servlet.cookie;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.CollationKey;
@WebServlet("/aServlet")
public class AServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//1. 创建Cookie
String value = "张三";
value = URLEncoder.encode(value,"UTF-8");
Cookie cookie = new Cookie("username", value);
//2. 发送Cookie到客户端
resp.addCookie(cookie);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doGet(req, resp);
}
}
接收数据的案列(Cookie):
package com.itheima.Servlet.cookie;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/bServlet")
public class BServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//1. 获取到Cookie
Cookie[] cookies = req.getCookies();
for (Cookie cookie : cookies) {
String name = cookie.getName();
if(name.equals("username")){
String value = cookie.getValue();
System.out.println(name + ": "+ value);
break;
}
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doGet(req, resp);
}
}
Cookie的实现是基于HTTP协议的
- 默认情况下,Cookie存储在浏览器内存中,当浏览器关闭,内存释放,则Cookie被销毁
- setMaxAge(int seconds):设置Cookie存活时间
正数
:将Cookie写入浏览器所在电脑的硬盘,持久化存储。到时间自动删除
负数
:默认值,Cookie在当前浏览器内存中,当浏览器关闭,则Cookie被销毁
零
:删除对应Cookie
URL编码
//编码
value = URLEncoder.encode(value,"UTF-8");
//解码
value = URLDecoder.decode(value,"UTF-8");
代码演示:
package com.itheima.Servlet.session;
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 javax.servlet.http.HttpSession;
import java.io.IOException;
import java.net.URLDecoder;
@WebServlet("/dom1")
public class sessionDom1 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//发送数据到session
//1.创建session对象
HttpSession session = req.getSession();
String value = "张三";
//2.发送数据到session
session.setAttribute("username",value);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doGet(req, resp);
}
}
package com.itheima.Servlet.session;
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 javax.servlet.http.HttpSession;
import java.io.IOException;
@WebServlet("/dom2")
public class sessionDom2 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//接收数据
HttpSession session = req.getSession();
Object username = session.getAttribute("username");
System.out.println(username);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doGet(req, resp);
}
}
使用:
HttpSession session = request.getSession();
void setAttribute(String name, Object o)
:存储数据到session域中Object getAttribute(String name)
:根据key,获取值void removeAttribute(String name)
:根据key,删除该键值对
服务器重启后,Session中的数据是否还在?
钝化
:在服务器正常关闭后,Tomcat会自动将Session数据写入硬盘的文件中
活化
:再次启动服务器后,从文件中加载数据到Session中
<session-config>
<session-timeout>30</session-timeout>
</session-config>
Cookie和Session都是完成一次会话内多次请求间数据共享的
区别:
存储位置
:Cookie是将数据存储在客户端,Session将数据存储在服务端安全性:
Cookie不安全,Session安全数据大小
:Cookie最大3KB,Session无大小限制存储时间
:Cookie可以长期存储,Session默认30分钟服务器性能
:Cookie不占服务器资源,Session占用服务器资源