day13学习总结
一、ServletContex
简介:
.ServletContext 是由tomcat容器创建
ServletContext 表示全局上下文对象 获取web项目中全 部的配置信息
获取ServletContex对象:
第一种方式:
第二种方式:
获取全局配置信息:
测试:
在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">
<context-param>
<param-name>admin</param-name>
<param-value>12345</param-value>
</context-param>
<context-param>
<param-name>encoding</param-name>
<param-value>utf-8</param-value>
</context-param>
</web-app>
在servlet中获取:
package com.qf.servlet;
import javax.servlet.ServletContext;
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.util.Enumeration;
@WebServlet(name = "demo01Servlet",urlPatterns = "/demo01Servlet")
public class Demo01Servlet extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
ServletContext servletContext = req.getServletContext();
String values = servletContext.getInitParameter("admin");
System.out.println(values);
//获取所有的键
Enumeration<String> parameterNames =
servletContext.getInitParameterNames();
while (parameterNames.hasMoreElements()) {
String s = parameterNames.nextElement();
System.out.println(s+"\t"+servletContext.getInitParameter(s));
}
}
}
二、转发与重定向
转发:
概念:
一次请求
用于页面进行跳转,并实现页面之间的参数传递
语法:
req.getRequestDispatcher("转发的路径").forward(req,resp);
注意点:
A.forward(req,resp); 一定要加上
B.转发的路径可以是页面(该页面必须是本项目的页面) 也可以是servlet路径
原理图:
重定向:
概念:
至少两次请求
用于实现页面之间的跳转 一般不用于页面参数之间的传递
语法:
resp.sendRedirect("重定向路径");
注意点:
重定向的路径可以是页面(该页面可以不是本项目的) 也可以是servlet路径
原理图:
转发与重定向比较:
转发 | 重定向 |
使用对象Request | 使用对象Response |
一次请求 | 至少两次请求 |
在服务器端 | 在客户端 |
url地址不发生改变 | url地址会发生改变 |
不能实现从A项目跳转B项目 | 实现从A项目跳转到B项目 |
查询使用转发 | 增删改成功之后使用重定向 |
三、get与post的比较
get:
1.get是明文进行提交 数据没有进行加密 提交数据是不安全的
2.get提交数据有长度限制 不能超过10kb (其实是不同浏览器对get方法限制不一样)
3.get提交 对应doGet()方法
4.get一般用于下载
post:
1.post 是密文进行提交 数据进行加密 提交数据安全的
2.post提交数据没有长度限制
3.post 提交 对应doPost方法
4.post一般用于提交数据
四、内置对象
简介:
内置对象:tomcat 容器创建的对象 可以直接使用 内置对象主要用于来页面或者servlet传递参数(作 用域)
两个内置对象:
ServletContext
request
作用域:
request 只要是在一次请求之内都可以获取
ServletContext 只要服务器没有关闭 都可以获取
设置作用域的方法:
测试:
package com.qf.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;
@WebServlet(name = "servlet01",urlPatterns = "/servlet01")
public class Servlet01 extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//通过request对象设置
req.setAttribute("name","张三");
//通过全局变量对象设置
req.getServletContext().setAttribute("pwd","123456");
req.getServletContext().removeAttribute("pwd");
//转发 一次请求
//req.getRequestDispatcher("servlet02").forward(req,resp);
//重定向 至少两次请求
resp.sendRedirect("servlet02");
}
}
package com.qf.servlet;
import javax.servlet.ServletContext;
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;
@WebServlet(name = "servlet02",urlPatterns = "/servlet02")
public class Servlet02 extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//获取request设置的值
Object name = req.getAttribute("name");
System.out.println(name);
//获取全局变量设置的值
Object pwd = req.getServletContext().getAttribute("pwd");
System.out.println(pwd);
}
}
五、JSP
简介:
A.JSP是动态网页技术标准
B.JSP运行在服务器上java页面
C.JSP本质就是一个servlet
创建JSP:
jsp运行原理:
第一次运行:
第二次运行:(没有修改JSP文件中的任何代码的情况,如果修改过就是第一次的过程)
jsp本质:
1.index_jsp 继承于 HttpJspBase
2.HttpJspBase 继承于 HttpServlet
3.index_jsp是HttServlet的子类 index_jsp 本质就是一个servlet
jsp 与Servlet 比较:
A.Servlet用于处理前后端 请求与响应 jsp 主要用于做页面的展示
B.jsp本质就是一个Servlet
jsp 组成部分:
A.前端:HTML +css + js
B.脚本 表达式 声明 注释
C.指令:引入第三方的指令
page 编写在jsp的第一行 主要用声明页面的编码格式 以及语言类型
include 引入前端的一些公共的布局
taglib 引入第三方的核心的标签库
脚本:
概念:
脚本就是直接在页面中编写java代码
语法:
<% java代码 %>
例子:
在经过翻译为java文件时:
表达式:
概念:
主要用于在页面直接显示内容,直接向页面输入内容
语法:
<%=变量名%>
例子:
声明:
概念:
在java中声明成员变量与成员方法 ,在jsp中也可以声明成员变量与成员方法
语法:
<%! 成员变量
成员方法
%>
例子:
注释:
语法;
<%-- 注释内容 --%>
指令:
page :
编写在jsp中的第一行 主要用于声明页面的编码格式和语言类型
contentType="text/html;charset=UTF-8" 表示文件的内容以及编码格式
language 语言类型
errorPage 页面加载错误时跳转的指定页面
include:
引入前端的一些公共布局
taglib:
引入第三方的核心的标签库
案例:
需求:
在jsp页面上显示学生对象信息
分析:
创建学生表:
编写实体类:
package com.qf.entity;
import java.io.Serializable;
public class Student implements Serializable {
private int sid;
private String sname;
private String sex;
private String hobby;
public Student() {
}
public Student(int sid, String sname, String sex, String hobby) {
this.sid = sid;
this.sname = sname;
this.sex = sex;
this.hobby = hobby;
}
public int getSid() {
return sid;
}
public void setSid(int sid) {
this.sid = sid;
}
public String getSname() {
return sname;
}
public void setSname(String sname) {
this.sname = sname;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getHobby() {
return hobby;
}
public void setHobby(String hobby) {
this.hobby = hobby;
}
@Override
public String toString() {
return "Student{" +
"sid=" + sid +
", sname='" + sname + '\'' +
", sex='" + sex + '\'' +
", hobby='" + hobby + '\'' +
'}';
}
}
编写dao接口:
package com.qf.dao;
import com.qf.entity.Student;
import java.util.List;
public interface StudentDao {
List<Student> selectAll();
}
dao接口实现类:
package com.qf.dao.impl;
import com.qf.dao.StudentDao;
import com.qf.entity.Student;
import com.qf.utils.DBUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import java.sql.SQLException;
import java.util.List;
public class StudentDaoImpl implements StudentDao {
private QueryRunner qr = DBUtils.DB.qr;
@Override
public List<Student> selectAll() {
List<Student> studentList = null;
try {
String sql = "select * from student";
studentList = qr.query(sql, new BeanListHandler<Student>(Student.class));
} catch (SQLException e) {
e.printStackTrace();
}
return studentList;
}
}
service接口:
package com.qf.service;
import com.qf.entity.Student;
import java.util.List;
public interface StudentService {
List<Student> selectAll();
}
service接口实现类:
package com.qf.service.impl;
import com.qf.dao.StudentDao;
import com.qf.dao.impl.StudentDaoImpl;
import com.qf.entity.Student;
import com.qf.service.StudentService;
import java.util.List;
public class StudentServiceImpl implements StudentService {
private StudentDao studentDao = new StudentDaoImpl();
@Override
public List<Student> selectAll() {
return studentDao.selectAll();
}
}
BaseServlet类:
package com.qf.servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class BaseServlet 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 mark = req.getParameter("mark");
//判断方法是否为空
if (mark==null||mark==""){
//抛出异常
throw new RuntimeException("方法不存在");
}
try {
//获取class对象
Class cla = this.getClass();
//获取方法
Method method = cla.getMethod(mark, HttpServletRequest.class, HttpServletResponse.class);
//调用方法
method.invoke(this,req,resp);
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
servlet类:
package com.qf.servlet;
import com.qf.entity.Student;
import com.qf.service.StudentService;
import com.qf.service.impl.StudentServiceImpl;
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.util.List;
@WebServlet(name = "selectStu",urlPatterns = "/selectStu")
public class SelectStudentServlet extends BaseServlet {
private StudentService studentService = new StudentServiceImpl();
public void selectAll(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
List<Student> students = studentService.selectAll();
//添加到作用域
request.setAttribute("students",students);
//跳转页面
request.getRequestDispatcher("info.jsp").forward(request,response);
}
}
jsp页面:
<%@ page import="java.util.List" %>
<%@ page import="com.qf.entity.Student" %><%--
Created by IntelliJ IDEA.
User: 86182
Date: 2022/9/3
Time: 15:02
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>
<%--<%
if (request.getAttribute("students")==null){
//转发到SelectStudentServlet获取数据
request.getRequestDispatcher("selectStu").forward(request,response);
return;
}
List<Student> students = (List<Student>) request.getAttribute("students");
%>--%>
<table border="1px" width="80%" align="center" cellpadding="0px" cellspacing="0px">
<tr>
<th>编号</th>
<th>姓名</th>
<th>性别</th>
<th>爱好</th>
</tr>
<c:forEach items="${students}" var="stu">
<tr>
<td>${stu.sid}</td>
<td>${stu.sname}</td>
<td>${stu.sex}</td>
<td>${stu.hobby}</td>
</tr>
</c:forEach>
</table>
</body>
</html>
六、EL表达式
简介:
EL(Expression Language)是为了使JSP写起来更加简单。表达式语言的灵感来自于 ECMAScript 和 XPath 表 达式语言,它提供了在 JSP 中简化表达式的方法,让Jsp的代码更加简化。
作用:
A.简单jsp页面中java代码
B.避免一些错误产生
C.使用el表达式进行一些基本运算
D.EL表达式与其它的第三方表达式搭配使用
EL表达式的基础运算:
el表达式获取数据:
注意:EL表达式只能获取内置对象的作用域下的数据
<%@ page import="java.util.List" %>
<%@ page import="java.util.ArrayList" %>
<%@ page import="java.util.Map" %>
<%@ page import="java.util.HashMap" %><%--
Created by IntelliJ IDEA.
User: 86182
Date: 2022/9/3
Time: 16:02
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>
<%
String name ="班长";
request.setAttribute("name",name);
String [] arrays ={"a","b","c","d"};
request.setAttribute("arrays",arrays);
List<Integer> list = new ArrayList<>();
list.add(1);
list.add(12);
list.add(2);
request.setAttribute("list",list);
Map<String,Integer> map = new HashMap<>();
map.put("kk",1);
map.put("gg",2);
map.put("ff",3);
request.setAttribute("map",map);
%>
${name}
${arrays[1]}
${list[2]}
${map.gg}
</body>
</html>
七、JSTL表达式
简介:
A.JSTL使一个标签库
B.JSTL 取代jsp页面中java代码 从而提高程序的可读性
使用:
首先导入相关jar包:
然后在jsp页面中引入核心类库:
prefix 是给引入类库取的名字
常用标签:
测试:
<%@ page import="java.util.List" %>
<%@ page import="com.qf.entity.Student" %>
<%@ page import="java.util.ArrayList" %><%--
Created by IntelliJ IDEA.
User: yyds
Date: 2022/9/3
Time: 16:18
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:set var="upwd" value="kk" ></c:set>
<c:out value="${upwd}"></c:out>
<c:remove var="upwd"></c:remove>
<c:out value="${upwd}"></c:out>
<c:set var="score" value="60" ></c:set>
<c:if test="${score >=90}">
哈哈哈
</c:if>
<c:choose>
<c:when test="${score >=90}">
优秀
</c:when>
<c:when test="${score >=80}">良好</c:when>
<c:otherwise>合格</c:otherwise>
</c:choose>
<%
List<Student> studentList = new ArrayList<>();
studentList.add(new Student(1001,"阿星","男","看美女"));
studentList.add(new Student(1002,"阿超","男","陪看美女"));
studentList.add(new Student(1003,"王胜龙","男","偷看美女"));
studentList.add(new Student(1004,"李焕荣","男","偷看王胜龙"));
request.setAttribute("studentList",studentList);
%>
<c:forEach items="${studentList}" var="stu" begin="0" end="3" step="3"
varStatus="sta">
${stu.sid} ${sta.index}</br>
${stu.sname}</br>
${stu.sex}</br>
${stu.sdesc}</br>
</c:forEach>
</body>
</html>
八、BaseServlet封装
需求:一个servlet类中的要定义多个请求方法 怎么调用不同的请求方法
代码:看上面的在jsp页面中展示学生对象信息
注意点:一定要给mark传值