JSP
什么是JSP?
JSP全称是Java Server Pages,它和servle技术一样,都是SUN公司定义的一种用于开发动态web资源的技术。
JSP这门技术的最大的特点在于,写jsp就像在写html,但它相比html而言,html只能为用户提供静态数据,而Jsp技术允许在页面中嵌套java代码,为用户提供动态数据。
特点:简单,和HTML差不多
缺点:书写页面会很乱,HTML代码和JAVA交错;
JSP到底怎么执行的
动态请求会被分发到Web容器(Web服务器)中。
容器会去执行字节码文件,就是 .class文件。
Servlet是java类,可以直接编译成class文件。
问题?Jsp怎么编译成class文件。
于是你会想,jsp是不是会被转换成一个java类。
【IDEA注意点】
idea的Tomcat work在他自己的空间中;
C:\Users>IntelliJIdea2018.1>{用户}>IntelliJIdea2018.1>system>tomcat>Web项目>找JSP生成的Servlet
Tomcat在工作的时候,将我们的Jsp页面转换成了java类
打开这个类分析:
他继承一个类:HTTPJSPBase , 没有直接继承HttpServlet , 但是HTTPJSPBase继承了HttpServlet,所以得出结论
JSP本身就是一个servlet的方式运行的
那他怎么输出页面的呢?发现他是使用out对象输出到浏览器
那这个out对象上去的方式是什么呢?
发现,有一个_jspService可以执行操作我们的JSP,将他输出到前端页面
继续分析源码,得到一些属性;
JSP基础语法
<%@ page import="java.util.Date" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%--
JSP基础语法
1.JSP获得变量的值 <%= 表达式或者变量值 %>
2.JSP定义局部变量:写一段Java代码 <% Java代码 %>
注意点:必须严格遵守Java规范
3.JSP定义全局变量 <%! 全局变量或方法 %>
简化符:因为HTML是标记语言,我们需要一些标记
EL表达式和JSTL标签
```
${} == <%= %> 联系和区别
EL表达式一般用来输出变量的值;而不能是一个对象;
```
tomcat会在jsp解析的时候将_jspService转换成对应的doget。dopost,我们正常方式无法直接调用!
//JSP内置对象:
pageContext 作用域:
application = pageContext.getServletContext(); 应用
session = pageContext.getSession(); 会话
request = 请求
page = this; 页面
==
out.输出
--%>
<%!
int i = 0;
public int add(int a,int b){
return a+b;
}
%>
<%
//Java代码
String name = "qinjiang";
int age = 18;
int j = 0;
Date date = new Date();
out.write(
(java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate
("${name}", java.lang.String.class,
(javax.servlet.jsp.PageContext)_jspx_page_context,
name
)
);
<html>
<head>
<title>$Title$</title>
</head>
<body>
<h1>
日期:<%=new Date()%>
名字:<%=name%>
年龄:<%=age%>
i:<%=i++%>
j:<%=j++%>
</h1>
</body>
</html>
JSP使用
jsp代码可以在不同的 <%%>中实现,但是,Java代码必须保持完成,否则500
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>首页</title>
</head>
<body>
<%--在页面输出100个Hello,World--%>
<%
for (int i = 0; i < 100; i++) {
%>
<h1>Hello,World</h1>
<%
}
%>
</body>
</html>
JSP综合练习
模拟数据库
public class NewsDB {
public static List<News> list = new ArrayList<News>();
static {
list.add(new News("学习了JSP的使用以及源码分析"));
list.add(new News("学习了Servlet,简单的JSP的使用"));
list.add(new News("学习了Tomcat,Servlet的使用"));
list.add(new News("学习了Tomcat,Servlet的使用"));
}
}
实体类
//实体类,一般放在pojo包下,【 or entity or JavaBeans】
//实体类,只有属性,一般用来映射数据库中的字段 ( O R M )
//私有属性 , 无参构造,有参构造
//get/set方法
//为了方便程序打印,建议加上toString();
public class News {
private String data;
private String content;
public News() {
}
public News(String data, String content) {
this.data = data;
this.content = content;
}
public String getData() {
return data;
}
public void setData(String data) {
this.data = data;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
@Override
public String toString() {
return "News{" +
"data='" + data + '\'' +
", content='" + content + '\'' +
'}';
}
}
dao层
//dao包一般用来存放操作数据库的对象类;
public interface NewsDao {
//获得所有的新闻
public List<News> getAllNews();
}
//NewsDao的实现类
public class NewsDaoImpl implements NewsDao {
@Override
public List<News> getAllNews() {
List<News> list = NewsDB.list;
return list;
}
}
service层
//service一般存放业务类
public interface NewsService {
//获得所有的新闻
public List<News> getAllNews();
}
public class NewsServiceImpl implements NewsService {
//从dao层中取出相应的操作数据库的方法
NewsDao newsDao = new NewsDaoImpl();
@Override
public List<News> getAllNews() {
return newsDao.getAllNews();
}
}
servlet
public class NewsServlet extends HttpServlet {
NewsService newsService = new NewsServiceImpl();
@Test
public void test(){
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//写代码读取数据存到某个地方,让前端读取;
List<News> allNews = newsService.getAllNews();//从业务层去获得数据中的全部新闻
int i = 1;
for (News allNew : allNews) { //遍历获得每一个新闻
String data = allNew.getData();
String content = allNew.getContent();
//四大作用域
// page(不用它,代表当前页面)
// request(一次请求中有效): 登录注册
// session (一次会话中存在) : 购物车
// application:本质就是Context (全局,所有会话共享) : 广告
//这四个作用域用来存放一些内容或者对象
HttpSession session = req.getSession();
session.setAttribute("data"+i,data);
session.setAttribute("content"+i,content);
System.out.println(session.getAttribute("data"+i));
System.out.println(session.getAttribute("content"+i));
i++;//自增
}
//数据都读取出来了,给你放到session中了,该去访问页面了
resp.sendRedirect("index.jsp");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<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/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<servlet>
<servlet-name>newsServlet</servlet-name>
<servlet-class>com.kuang.servlet.NewsServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>newsServlet</servlet-name>
<url-pattern>/news.do</url-pattern>
</servlet-mapping>
</web-app>
index.jsp
<%@ page import="com.kuang.db.NewsDB" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>首页</title>
<%--引入css--%>
<link rel="stylesheet" href="${pageContext.request.contextPath}/statics/layui/css/layui.css">
<%--引入静态资源文件必须带上项目路径位置--%>
<Script src="${pageContext.request.contextPath}/statics/layui/layui.js"></Script>
</head>
<body>
<fieldset class="layui-elem-field layui-field-title" style="margin-top: 30px;">
<legend>常规时间线</legend>
</fieldset>
<ul class="layui-timeline">
<%
for (int i = 1; i <= NewsDB.list.size(); i++) {
%>
<li class="layui-timeline-item">
<i class="layui-icon layui-timeline-axis"></i>
<div class="layui-timeline-content layui-text">
<h3 class="layui-timeline-title">
<%=request.getSession().getAttribute("data"+i)%>
<%--${sessionScope.data1}--%>
</h3>
<p>
<%--${sessionScope.content1}--%>
<%=request.getSession().getAttribute("content"+i)%>
</p>
</div>
</li>
<%
}
%>
<li class="layui-timeline-item">
<i class="layui-icon layui-timeline-axis"></i>
<div class="layui-timeline-content layui-text">
<div class="layui-timeline-title">过去</div>
</div>
</li>
</ul>
</body>
</html>
JSP指令
JSP指令只有三个
page、include、taglib (标签)
公式:
<%@ 指定名 属性名=属性值;[属性名=属性值;属性名=属性值…] %>
page指令
autoFlush:自动刷新 (true,false:默认)
contentType:页面文本类型 “text/html”
errorPage: 如果存在错误页面,就跳转至指定的页面 【不推荐使用,推荐在XML中配置】
language:JSP中使用的语言,默认是java
pageEncoding:页面编码
import:因为jsp本质上就是一个servlet,所以需要导入相关jar包才能使用。
include指令
导入其他页面包含到本页,网站中一般有一些公用的位置,我们可以提取出来,比如网站的头部,和尾部
file属性:【要导入页面,一般都是不完整的网页,只包含部分】
taglib:标签库
在jsp中有大量的java代码十分痛苦,所以开发中我们可以使用一些现成的标签库,就相当于使用一些替代java代码的标签语言
out.print()-----> <c:out> : 这个c就是一个别人定义好的标签库,像这样的库有非常多,我们甚至可以自己定义;
include指定:包含页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<div>
<h1>我是footer</h1>
</div>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<div>
<h1>我是header</h1>
</div>
<body>
<%--使用include指定加载网页其他部分--%>
<%@include file="common/header.jsp"%>
<h1>我是index页面</h1>
<%@include file="common/footer.jsp"%>
</body>
errorPage:错误页面
<?xml version="1.0" encoding="UTF-8"?>
<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/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<!--如果网站中出现了404,就跳转到指定的页面-->
<error-page>
<error-code>404</error-code>
<location>/error/404.jsp</location>
</error-page>
<error-page>
<error-code>500</error-code>
<location>/error/500.jsp</location>
</error-page>
<error-page>
<exception-type>java.lang.NullPointerException</exception-type>
<location>/error/exception.jsp</location>
</error-page>
</web-app>
JSP标签
作用:为了避免在JSP中有大量的Java代码,造成页面不好维护
<%--
JSP标签
语法:<jsp:XXX >
jsp:include:
page属性:要包含的页面地址
jsp:include 和 @include 区别
@include 静态包含 : 他会把包含进来的页面和自己的页面融合成为一个servlet
jsp:include 动态包含 :他不会把包含进来的页面和自己的页面融合成为一个servlet 【推荐使用,容错率更高】
jsp:forward
page属性:要转发到的页面,url不变,
本质就是request的请求转发,可以携带参数;可以通过request取出来这个携带的参数
一般配合<jsp:param>使用
jsp:param
一般配合<jsp:forward>使用,携带参数
--%>
<%--
<jsp:include page="common/header.jsp"/>
<h1>我是tag页面</h1>
<jsp:include page="common/footer.jsp"/>
<jsp:forward page="index.jsp"/>
<jsp:forward page="index.jsp">
<jsp:param name="username" value="kuangshen"/>
<jsp:param name="age" value="18"/>
</jsp:forward>
index页面的取出代码
名字:<%=request.getParameter("username")%>
年龄:<%=request.getParameter("age")%>
--%>
JSTL标签库
和jsp标签一样,为了解决jsp中嵌入java代码看着不舒服
注意点:
- 项目要导入对应的jstl标签库的jar包。
- Tomcat中也需要放置对应的jar包
- 代码中,有些特殊符号需要使用转义字符;
<%@ page import="com.kuang.pojo.Student" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%--
使用jstl或者其他标签库需要先导入,需要下载对应的jar包-jstl-1.2;
prefix:需要使用的标签库名
tagdir:标签库的本地目录
uri : 对应库的网络地址
--%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<%--
<c:out 输出
<c:out value="你好啊"/>
--%>
<c:out value="你好啊"/>
<%--
<c:if
test: 需要判断的条件 ,等价于 if(exp)中的exp
if(){
}
--%>
<%
request.getSession().setAttribute("name","xiaohua");
Student student = new Student();
student.setName("xiaohua);
%>
<%=student.getName().equals("xiaohua")%>
${sessionScope.name=='qinjiang'}
<c:if test="<%=student.getName().equals(\"xiaohua\")%>">
<c:out value="admin"/>
</c:if>
</body>
</html>
EL表达式
同理,简化Jsp的代码难度;
${表达式}
${page、session、request、Application的变量}
过滤器
我们主要用它来实现过滤乱码问题!
过滤器一般就用来过滤一些违规词语,解决乱码问题;主要还是为了解耦,职责统一
写一个类实现Filter接口,必定会重写三个方法
-
初始化
-
doFilter(req,resp,doFilterChain)
doFilterChain(req,resp)