6. JSP (java Serve Page)
https://www.tutorialspoint.com/jsp/
6.1 JSP简介
JSP(全称JavaServer Pages)是由Sun Microsystems公司主导创建的一种动态网页技术标准。JSP部署于网络服务器上,可以响应客户端发送的请求,并根据请求内容动态地生成HTML、XML或其他格式文档的Web网页,然后返回给请求者。JSP技术以Java语言作为脚本语言,为用户的HTTP请求提供服务,并能与服务器上的其它Java程序共同处理复杂的业务需求。
JSP将Java代码和特定变动内容嵌入到静态的页面中,实现以静态页面为模板,动态生成其中的部分内容。JSP引入了被称为“JSP动作”的XML标签,用来调用内建功能。另外,可以创建JSP标签库,然后像使用标准HTML或XML标签一样使用它们。标签库能增强功能和服务器性能,而且不受跨平台问题的限制。JSP文件在运行时会被其编译器转换成更原始的Servlet代码。JSP编译器可以把JSP文件编译成用Java代码写的Servlet,然后再由Java编译器来编译成能快速执行的二进制机器码,也可以直接编译成二进制码。
jsp就是servlet:
<dependencies><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.12</version><scope>test</scope></dependency><dependency><groupId>javax.servlet</groupId><artifactId>javax.servlet-api</artifactId><version>4.0.1</version></dependency><dependency><groupId>javax.servlet</groupId><artifactId>jstl</artifactId><version>1.2</version></dependency></dependencies>
6.1.1 JSP脚本(片段)
<!--jsp指令-->
<%@ page language="java" import="java.util.Date,java.util.Scanner" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head><meta charset="UTF-8"><title>index</title>
</head>
<body><h2>Hello World!</h2><!--html注释--><%--jsp注释--%><%--jsp片段 脚本--%><%System.out.println("Hello World");System.out.println(new Date().getTime());%><%--脚本拼接--%><%for (int i = 0; i < 5; i++) {%><h3>Welcome to index page!!!</h3><%}%></body>
</html>
6.1.2 JSP指令
- page
- include 包含
- taglib 标签库
<%--jsp指令 包含--%>
<%--静态包含 : 在编译期会边已成为一.java文件--%>
<%@include file="header.jsp"%>
<%--编译时候分开编译,运行到这一行的时候在包含进来--%>
<jsp:include page="header.jsp"></jsp:include>
6.1.3 JSP注释
<!--jsp指令-->
<%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head><meta charset="UTF-8"><title>index</title>
</head>
<body><h2>Hello World!</h2><!--html注释--><%--jsp注释--%>
</body>
</html>
6.1.4 JSP声明
<%--jsp声明--%>
<%!String name = "lucy";
%>
6.1.5 JSP表达式
<%--jsp表达式--%>
<%=new Date()%>
6.1.6 JSP标签库
<%--Created by IntelliJ IDEA.User: chanhDate: 2020/9/3Time: 11:01To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head><title>标签</title>
</head>
<body>
<%--跳转--%><%-- <jsp:forward page="header.jsp"></jsp:forward>--%>
<%--javabean + servlet +jsp--%>
<%--score 域 ServletContext session request jsp application session request page--%>
<jsp:useBean id="car" class="com.shangguan.servlet.beans.Car" scope="page"></jsp:useBean>
<jsp:setProperty name="car" property="carName" value="宝马x6"></jsp:setProperty>
<jsp:setProperty name="car" property="carType" value="SUV"></jsp:setProperty><%--使用对象调用属性--%>
<jsp:getProperty name="car" property="carName"/>
<jsp:getProperty name="car" property="carType"/>
</body>
</html>
6.2 JSP九大内置对象
- HttpServletRequest request
- HttpServletResponse response
- PageContext
- ServletContext application
- ServletConfig config
- HttpSession session
- page=this
- Exception
<%@ page import="com.shangguan.servlet.beans.Car" %><%--Created by IntelliJ IDEA.User: chanhDate: 2020/9/3Time: 11:25To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" errorPage="404.jsp" %>
<html>
<head><title>Title</title>
</head>
<body><%Car car = new Car();car.setCarName("奔驰");car.setCarType("商务车");request.setAttribute("car",car);response.getWriter().print("<h3>Inner Object</h3>");application.setAttribute("car1",car);// out.write("<!--jsp指令-->\n");System.out.println(page);try {System.out.println(1/0);}catch (Exception e){System.out.println(e.getMessage());}%>${car}<br><%--/jsp_maven_war_exploded--%>${pageContext.request.contextPath}<br>${car1}
</body>
</html>
6.2 EL表达式(Expression Language 表达式语言)
https://docs.oracle.com/javaee/1.4/tutorial/doc/JSPIntro7.html
The web container evaluates a variable that appears in an expression by looking up its value according to the behavior of
PageContext.findAttribute(String)
. For example, when evaluating the expression${product}
, the container will look forproduct
in the page, request, session, and application scopes and will return its value. Ifproduct
is not found,null
is returned. A variable that matches one of the implicit objects described in Implicit Objects will return that implicit object instead of the variable’s value.Properties of variables are accessed using the
.
operator and can be nested arbitrarily.The JSP expression language unifies the treatment of the
.
and[]
operators.expr-a.identifier-b
is equivalent to expr-a["identifier-b"]
; that is, the expressionexpr-b
is used to construct a literal whose value is the identifier, and then the[]
operator is used with that value.
- el表达式用法${}
- el是pageContex.findAttribute() 从域对象中寻找变量对应的值
- 是按照域对象 由小到大的顺序去寻找,先在哪个里面找到就使用
- page < request <session < application
- 指定域对象
- pageScope
- requestScope
- sessionScope
- applicationScope
- el内置对象
- pageContext
- request
- session
- response
- params
- paramValues
- header
- headerValues
- cookie
- initParam
- 数据类型
- boolean
- int
- String
- null
- float
- 运算符
- 算数运算符
- 逻辑
- 比较
- 三元
- el函数库
<description>JSTL 1.1 functions library</description><display-name>JSTL functions</display-name><tlib-version>1.1</tlib-version><short-name>fn</short-name><uri>http://java.sun.com/jsp/jstl/functions</uri><function><description>Tests if an input string contains the specified substring.</description><name>contains</name><function-class>org.apache.taglibs.standard.functions.Functions</function-class><function-signature>boolean contains(java.lang.String, java.lang.String)</function-signature><example><c:if test="${fn:contains(name, searchString)}"></example></function>
<%@ page import="com.shangguan.servlet.beans.Car" %>
<%--Created by IntelliJ IDEA.User: chanhDate: 2020/9/3Time: 14:14To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<html>
<head><title>Title</title><%--绝对路径--%><%--http://localhsot:8080/jsp-maven_war_exaploed/css/style.css--%><link rel="stylesheet" href="${pageContext.request.contextPath}/css/style.css">
</head>
<body><%--el表达式获取域对象中存储的变量值--%><%application.setAttribute("hello","hello application");request.setAttribute("hello","Hello World");session.setAttribute("hello","Hello Session");Car car = new Car();car.setCarName("宝马");car.setCarType("SUV");request.setAttribute("car",car);request.setCharacterEncoding("utf8");%>${hello}<%--如果我就想使用指定域对象中的变量怎么办?--%><br>${pageScope.hello}---${requestScope.hello}---${sessionScope.hello}----${applicationScope.hello}<br>${car.carName}-----${car.carType}<%--el内置对象--%><%--上下文路径--%>${pageContext.request.contextPath}<br>encoding:${request.getCharacterEncoding}<br>${param.name}<br>${paramValues}<br>${header.Connection}<%--request.getHeader('Connection')--%><br>${cookie}<hr>
<%--el表达式运算--%>
${100 + 200} -----${100 - 200}----${200 *2}<br>
${100 > 200 and 100 < 200}-----${ not (100 > 50)}----${100 > 200 or 100 < 200}<br><%--判断是否位null--%>
${ empty student} ------------${ student}<br><%--条件运算--%>
${empty student == true?"没有student":"有stduent"}
<%--el函数库--%>
${fn:contains("Hello World","Hello" )}<br>
${fn:toUpperCase("hello expression")}<br>
${fn:trim(" hello world ")}<br>
${fn:startsWith("Hello WOrld","H" )}
</body>
</html>
6.3 JSTL标签库
- jstl.jar
- standardjar
<%@ page import="com.shangguan.servlet.beans.Student" %>
<%@ page import="java.util.*" %><%--Created by IntelliJ IDEA.User: chanhDate: 2020/9/4Time: 9:36To 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>
<%--通常jstl要结合el表达式使用--%>
<%Student student = new Student();student.setStuName("admin");student.setStuAge(18);student.setStuAddress("西安市雁塔区");request.setAttribute("student", student);
%>
<br>---------------------c:out-------------<br><c:out value="hello"/><br><c:out value="${student}"/><br>
<%--能获取到值就显示 ,没有就是用默认值--%><c:out value="${pass}" default="welcome to index" /><br>
<%--不解析html--%><c:out value="<h3>Hello Jstl tag</h3>" escapeXml="true"/><br>
<%--解析html--%><c:out value="<h3>Hello Jstl tag</h3>" escapeXml="false"/><br>
<br>---------------------c:set-------------<br><%-- <c:set value="" scope="" var="" property="" target=""></c:set>--%>
<c:set var="num" value="99999999999999999999" scope="page"></c:set>
<jsp:useBean id="stu" class="com.shangguan.servlet.beans.Student"></jsp:useBean>
<c:set value="xiaoming" target="${stu}" property="stuName"></c:set>
${num}---${num1}-------------${stu}
<br>---------------------c:if-------------<br>
<%--test的值必须是boolean--%>
<c:if test="${empty sss}">stu infos!!!
</c:if>
<br>---------------------c:choose-------------<br>
<c:choose><c:when test="${empty student}">some infos ----</c:when><c:when test="${100 < 10}">num *****</c:when><c:otherwise>any infos ++++</c:otherwise>
</c:choose>
<br>---------------------c:url-------------<br>
<c:url var="url" value="http://www.baidu.com" scope="page"></c:url><a href="${url}">百度一下</a>
<br>
<c:url var="urlpam" value="http://www.baidu.com" scope="page"><c:param name="name" value="lllll"></c:param>
</c:url>
<a href="${urlpam}">百度一下</a>
<br>---------------------c:redirect 页面重定向-------------<br>
<%--<c:redirect url="el.jsp"></c:redirect>--%>
<br>---------------------c:import -------------<br>
<c:import url="el.jsp"></c:import><br>---------------------c:foreach 遍历-------------<br>
<%List<String> list = Arrays.asList("Hello","World","JAVA","c++");request.setAttribute("list",list);Set<String> set = new HashSet<>();set.add("admin");set.add("joke");set.add("lucy");set.add("hanmeiemi");request.setAttribute("set",set);Map<Integer,String> map = new HashMap<>();map.put(1,"one");map.put(2,"two");map.put(3,"three");map.put(4,"four");map.put(5,"five");request.setAttribute("map",map);
%>
<c:forEach var="str" items="${list}" varStatus="strStatus">${str}${strStatus.first}${strStatus.last}${strStatus.count}
</c:forEach><hr>
<c:forEach var="set" items="${set}" varStatus="setStatus">${set}${setStatus.first}${setStatus.last}${setStatus.count}
</c:forEach>
<hr>
<c:forEach var="map" items="${map}" varStatus="mapStatus">${map}<br>${map.key}<br>${map.value}<br>${mapStatus.first}<br>${mapStatus.last}<br>${mapStatus.count}<br>
</c:forEach>
</body>
</html>
7. Servlet+JSP 分页
7.1 CRUDDemo
8.Lombok插件
<dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><version>1.18.10</version></dependency>
- @Data
- get
- set
- toString
- hashcode
- equals方法
- AllArgsConstrctor
- NoArgsConstrctor
- @RequiredArgsConstructor
- NoNull不能为空记在属性上
package com.shangguan.servlet.beans;import lombok.*;/*** Description:** @Author:一尘* @Version:1.0* @Date:2020-09-03-11:04*/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Car {
private String carName;private String carType;
}
9. MVC思想
我们的javaSe阶段和WEB阶段进行整合,javaSE主要负责是我们的数据库的表的建模。
- 主从复制
- 分库分表 数据库中间件 mycat
- 数据同步
- 数据库维护工程师操作。
建模意味着我们使用类进行数据库表的映射,表-----类 列-----属性
数据库的crud操作----------类的业务层: crud
web层 servlet进行业务的调度。
jsp视图展示 数据展示。
M module 模型 类 接口 接口的实现(数据库的操作)
V view 视图 展示数据的技术 (html,jsp)
C controller 控制层 调度层 (Servlet)
MVC分层:(高内聚低耦合)
src
? | beans/entity
? | dao / mapper
? | impl
? | service接口和dao种方法一致
? | impl 调用dao实现类的业务
? | servlet
开发的时候遵守MVC的开发模式进行开发。
10. 文件上传
- commons-io
- commons-fileupload
index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head><meta charset="UTF-8"><title>index</title>
</head>
<body><h2>Hello World!</h2>
<%-- 文件上传的表单必须添加这个属性 enctype--%><form action="upload" method="post" enctype="multipart/form-data"><input type="file" name="file" id="file"><br><input type="submit" value="上传"></form>
</body>
</html>
FileUploadServlet.java
package com.shangguan.upload;import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.time.LocalDate;
import java.util.UUID;/*** Description:文件上传** @Author:一尘* @Version:1.0* @Date:2020-09-07-9:47*/
@MultipartConfig
@WebServlet("/upload")
public class MyFileUpload extends HttpServlet {
@Overrideprotected void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
request.setCharacterEncoding("utf-8");response.setCharacterEncoding("utf-8");response.setContentType("text/html;charset=utf-8");//准备文件上传以后保存的实际路径String originPath = request.getServletContext().getRealPath("upload");File file = new File(originPath);if(!file.exists()){
file.mkdirs();}//接受上传的文件数据Part part = request.getPart("file");//获取原文件的扩展名//form-data; name="file"; filename="10-4.png"String header = part.getHeader("content-disposition");String sub1 = header.substring(header.lastIndexOf("=")+1);//文件扩展名String lastEx = sub1.substring(sub1.lastIndexOf("."),sub1.length()-1);//最终的文件路径File finalPath = new File(originPath,File.separator+ LocalDate.now()+File.separator+System.currentTimeMillis()+ UUID.randomUUID()+lastEx);if(!finalPath.exists()){
finalPath.mkdirs();}part.write(finalPath.toString());System.out.println("-----上传完了-----");if(finalPath.exists()){
System.out.println("--------上传成功---------");}}@Overrideprotected void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
doGet(request,response);}
}
11. 过滤器
我们在项目中有对全限的控制,什么全限的用户访问不同的资源,怎么去控制呢?
web.xml
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaeehttp://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"version="4.0"><display-name>Archetype Created Web Application</display-name><filter><filter-name>encodingFilter</filter-name><filter-class>com.shangguan.filter.MyEncodinglFilter</filter-class><init-param><param-name>encoding</param-name><param-value>utf-8</param-value></init-param></filter><filter-mapping><filter-name>encodingFilter</filter-name><!--所有请求--><url-pattern>/*</url-pattern><!-- <servlet-name>/login</servlet-name>--></filter-mapping>
</web-app>
注解开发
全局的乱码过滤器
MyEncodingFIlter.java
package com.shangguan.filter;import com.shangguan.util.MyHttpServletRequest;import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;/*** Description:乱码处理** @Author:一尘* @Version:1.0* @Date:2020-09-07-11:09*/
@WebFilter(urlPatterns = "/*",initParams = {
@WebInitParam(name = "encoding",value = "utf-8")
})
public class MyEncodinglFilter implements Filter {
private String encoding = "";@Overridepublic void init(FilterConfig filterConfig) throws ServletException {
this.encoding = filterConfig.getInitParameter("encoding");}@Overridepublic void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)throws IOException, ServletException {
//http协议HttpServletRequest servletRequest = (HttpServletRequest) request;HttpServletResponse servletResponse = (HttpServletResponse) response;//post请求的乱码servletRequest.setCharacterEncoding(encoding);servletResponse.setCharacterEncoding(encoding);servletResponse.setContentType("text/html;charset=utf-8");//get请求处理怎么做/* String name = request.getParameter("name");String newName = new String(name.getBytes("utf-8"),"utf-8");*///放行MyHttpServletRequest myHttpServletRequest = new MyHttpServletRequest(servletRequest);chain.doFilter(myHttpServletRequest,servletResponse);}
}
MyHttpServletRequest.java
package com.shangguan.util;import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.UnsupportedEncodingException;
import java.util.Enumeration;/*** Description:** @Author:一尘* @Version:1.0* @Date:2020-09-07-11:23*/
public class MyHttpServletRequest extends HttpServletRequestWrapper {
private HttpServletRequest httpServletRequest = null;public MyHttpServletRequest(HttpServletRequest request) {
super(request);this.httpServletRequest = request;Enumeration<String> parameterNames = request.getParameterNames();while(parameterNames.hasMoreElements()){
String name = parameterNames.nextElement();getParameter(name);}}@Overridepublic String getParameter(String name) {
String value = httpServletRequest.getParameter(name);String newValue = "";//乱码处理try {
newValue= new String(value.getBytes("utf-8"),"utf-8");} catch (UnsupportedEncodingException e) {
e.printStackTrace();}return newValue ;}
}
登录过滤
index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head><meta charset="UTF-8"><title>index</title>
</head>
<body><h2>Hello World!</h2><a href="login?name=张三&role=总经理">LoginServlet</a>
</body>
</html>
LoginServlet.jsp
package com.shangguan.servlet;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;/*** Description:** @Author:一尘* @Version:1.0* @Date:2020-09-07-11:33*/
@WebServlet(urlPatterns = "/login",name = "loginServlet")
public class LoginServlet extends HttpServlet {
@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String name = req.getParameter("name");System.out.println(name);}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req,resp);}
}
RoleFilter.java
package com.shangguan.filter;import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;/*** Description:** @Author:一尘* @Version:1.0* @Date:2020-09-07-11:40*/
@WebFilter(servletNames = "loginServlet")
public class RoleFilter implements Filter {
@Overridepublic void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest servletRequest = (HttpServletRequest) request;HttpServletResponse servletResponse = (HttpServletResponse) response;String role = servletRequest.getParameter("role");if(role.equals("普通员工")){
servletResponse.sendRedirect("Home.html");}else{
servletResponse.sendRedirect("Main.html");}chain.doFilter(servletRequest,servletResponse);}
}
12. 监听器
Java事件监听器属性的新增、删除和修改划分成三种,分别针对于ServletContext、HttpSession、ServletRequest对象。
- ServletContext
- HttpSeesion
- ServletRequest
package com.shangguan.listener;import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;/*** Description:** @Author:一尘* @Version:1.0* @Date:2020-09-07-16:17*/
@WebListener
public class MyServletContextListener implements ServletContextListener {
@Overridepublic void contextInitialized(ServletContextEvent sce) {
sce.getServletContext().setAttribute("msg","项目启动成功了!");System.out.println("------------项目初始化完成-----------");}@Overridepublic void contextDestroyed(ServletContextEvent sce) {
}
}
package com.shangguan.servlet;import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;/*** Description:** @Author:一尘* @Version:1.0* @Date:2020-09-07-16:28*/
@WebListener
public class MyHttpSessionListener implements HttpSessionListener {
private int count = 0;@Overridepublic void sessionCreated(HttpSessionEvent se) {
System.out.println("-----------session create--------------");HttpSession session = se.getSession();session.setAttribute("count",1);int num = (Integer) session.getAttribute("count");session.setAttribute("ll","Hello World");if(num == 0){
session.setAttribute("count",1);}else{
session.setAttribute("count", this.count +=1);}System.out.println(session.getAttribute("count"));}@Overridepublic void sessionDestroyed(HttpSessionEvent se) {
HttpSession session = se.getSession();int num = (Integer) session.getAttribute("count");if(num > 0){
session.setAttribute("count",count-=1);}}
}
package com.shangguan.servlet;import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;/*** Description:** @Author:一尘* @Version:1.0* @Date:2020-09-07-16:57*/
@WebListener
public class MyServletRequestListener implements ServletRequestListener {
private Map<String,Integer> map = new HashMap<>();@Overridepublic void requestDestroyed(ServletRequestEvent sre) {
}@Overridepublic void requestInitialized(ServletRequestEvent sre) {
HttpServletRequest request = (HttpServletRequest) sre.getServletRequest();String requestURI = request.getRequestURI();System.out.println(requestURI);// map.put(requestURI,0);int s = 0;if(requestURI.equals("/filter_listener_servlet_war_exploded/login")){
if(requestURI==null){
s = 0;}else{
s = map.get(requestURI);}if(s == 0){
map.put(requestURI,1);}else {
map.put(requestURI,s+=1);}System.out.println(map.get(requestURI));request.getSession().setAttribute("login",map.get(requestURI));}}
}