目录
网页内右键“审查元素”
在Java中,动态web资源开发的技术统称为JavaWeb;
web应用程序:可以提供浏览器访问的程序;
这个统一的web资源会被放在同一个文件夹下,web应用程序-->Tomcat:服务器
一个web应用由多部分组成 (静态web,动态web)
- html,css,js
- jsp,servlet
- Java程序
- jar包
- 配置文件 (Properties)
web应用程序编写完毕后,若想提供给外界访问:需要一个服务器来统一管理;
静态
web
动态web:页面会动态展示: “Web的页面展示的效果因人而异”;
web服务器:服务器是一种被动的操作,用来处理用户的一些请求和给用户一些响应信息;
技术讲解
ASP: 在ASP开发中,基本一个页面都有几千行的业务代码,页面极其换乱;维护成本高!
php:PHP开发速度很快,功能很强大,跨平台,代码很简单 (70% , WP);无法承载大访问量的情况(局限性)
JSP/Servlet :
B/S:浏览和服务器
C/S: 客户端和服务器
IIS
微软的; ASP...,Windows中自带的
Tomcat
Tomcat是Apache 软件基金会(Apache Software Foundation)的Jakarta 项目中的一个核心项目,最新的Servlet 和JSP 规范总是能在Tomcat 中得到体现,因为Tomcat 技术先进、性能稳定,而且
免费,因而深受Java 爱好者的喜爱并得到了部分软件开发商的认可,成为目前比较流行的Web 应用服务器。
Tomcat 服务器是一个免费的开放源代码的Web 应用服务器,属于轻量级应用服务器,在中小型系统和并发访问用户不是很多的场合下被普遍使用,是开发和调试JSP 程序的首选。
Tomcat 实际上运行JSP 页面和Servlet。Tomcat最新版本为
9.0
。
Tomcat
可以配置启动的端口号
- tomcat的默认端口号为:8080
- mysql:3306
- http:80
- https:443
<Connector port="8081" protocol="HTTP/1.1"
connectionTimeout="20000" redirectPort="8443" />
可以配置主机的名称
- 默认的主机名为:localhost->127.0.0.1
- 默认网站应用存放的位置为:webapps
<Host name="www.qinjiang.com" appBase="webapps"
unpackWARs="true" autoDeploy="true">
请你谈谈网站是如何进行访问的!
1. 输入一个域名;回车
2. 检查本机的 C:\Windows\System32\drivers\etc\hosts配置文件下有没有这个域名映射;
1. 有:直接返回对应的ip地址,这个地址中,有我们需要访问的web程序,可以直接访问;
2. 没有:去DNS服务器找,找到的话就返回,找不到就返回找不到;
发布一个web网站
将自己写的网站,放到服务器(Tomcat)中指定的web应用的文件夹(webapps)下,就可以访问了
//网站应该有的结构
--webapps :Tomcat服务器的web目录
-ROOT -kuangstudy :网站的目录名
- WEB-INF -classes : java程序
-lib:web应用所依赖的jar包
-web.xml :网站配置文件
- index.html 默认的首页
- static
-css
-style.css
-js
-img
-.....
HTTP
HTTP(超文本传输协议)是一个简单的请求-响应协议,它通常运行在TCP之上。
HTTP请求
- 客户端---发请求(Request)---服务器
Request URL:https://www.baidu.com/ 请求地址
Request Method:GET get方法/post方法
Status Code:200 OK 状态码:200
Remote(远程) Address:14.215.177.39:443
Accept:text/html
Accept-Encoding:gzip, deflate, br
Accept-Language:zh-CN,zh;q=0.9 语言
Cache-Control:max-age=0
Connection:keep-alive
1、请求行
- 请求行中的请求方式:GET
- 请求方式:Get,Post,HEAD,DELETE,PUT,TRACT…
get:请求能够携带的参数比较少,大小有限制,会在浏览器的URL地址栏显示数据内容,不安全,但高效
post:请求能够携带的参数没有限制,大小没有限制,不会在浏览器的URL地址栏显示数据内
容,安全,但不高效。
2、消息头
Accept:告诉浏览器,它所支持的数据类型
Accept-Encoding:支持哪种编码格式 GBK UTF-8 GB2312 ISO8859-1
Accept-Language:告诉浏览器,它的语言环境
Cache-Control:缓存控制
Connection:告诉浏览器,请求完成是断开还是保持连接
HOST:主机..../.
Http响应
1.响应体
2、响应状态码
Maven
阿里云镜像
本地仓库
HelloServlet
//子类 pom.xml
<parent>
<groupId>org.example</groupId>
<artifactId>javaweb-3-7-servlet</artifactId>
<version>1.0-SNAPSHOT</version>
</parent>
//父类 pom.xml
<modules>
<module>servlet-3-7</module>
</modules>
//HelloServlet类
package 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.io.PrintWriter;
import java.io.Writer;
public class HelloServlet extends HttpServlet {
//由于get或者post只是请求实现的不同的方式,可以相互调用,业务逻辑都一样
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("doGet方法");
PrintWriter writer = resp.getWriter();
writer.print("HelloServlet");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
}
//子类 web.xml
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>Archetype Created Web Application</display-name>
<!--注册Servlet-->
<servlet>
<servlet-name>hello</servlet-name>
<servlet-class>servlet.HelloServlet</servlet-class>
</servlet>
<!-- servlet的请求路径-->
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
</web-app>
Tomcat配置
运行
Mapping问题
1. 一个Servlet可以指定一个映射路径
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
2. 一个Servlet可以指定多个映射路径
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/hello2</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/hello3</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/hello4</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/hello5</url-pattern>
</servlet-mapping>
3. 一个Servlet可以指定通用映射路径
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/hello/*</url-pattern>
</servlet-mapping>
4. 默认请求路径
<!--默认请求路径-->
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
5. 指定一些后缀或者前缀等等….
<!--可以自定义后缀实现请求映射 注意点,*前面不能加项目映射的路径 hello/sajdlkajda.qinjiang -->
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>*.qinjiang</url-pattern>
</servlet-mapping>
6. 优先级问题
指定了固有的映射路径优先级最高,如果找不到就会走默认的处理请求;
<!--404-->
<servlet>
<servlet-name>error</servlet-name>
<servlet-class>com.kuang.servlet.ErrorServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>error</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
ServletContext
共享数据
我在这个Servlet中保存的数据,可以在另外一个servlet中拿到;
public class HelloServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//this.getInitParameter() 初始化参数
//this.getServletConfig() Servlet配置
//this.getServletContext() Servlet上下文
ServletContext context = this.getServletContext();
String username = "秦疆"; //数据
context.setAttribute("username",username); //将一个数据保存在了 ServletContext中,名字为:username 。值 username } }
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class GetServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext context = this.getServletContext();
String username = (String) context.getAttribute("username");
resp.setContentType("text/html");
resp.setCharacterEncoding("utf-8");
resp.getWriter().print("name"+username);
resp.getWriter().print(username);
}
}
<?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"
metadata-complete="true">
<servlet>
<servlet-name>hello</servlet-name>
<servlet-class>HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>get</servlet-name>
<servlet-class>GetServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>get</servlet-name>
<url-pattern>/get</url-pattern>
</servlet-mapping>
</web-app>
获取初始化参数
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext context = this.getServletContext();
String url = context.getInitParameter("url");
resp.getWriter().print(url);
}
<!-- 配置一些web应用初始化参数-->
<context-param>
<param-name>url</param-name>
<param-value>jdbc:mysql://localhost:3306/mybatics</param-value>
</context-param>
<servlet>
<servlet-name>gp</servlet-name>
<servlet-class>ServlerDemo01</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>gp</servlet-name>
<url-pattern>/gp</url-pattern>
</servlet-mapping>
请求转发
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext context = this.getServletContext();
System.out.println("进入了ServletDemo03");
//RequestDispatcher requestDispatcher = context.getRequestDispatcher("/gp");//转发的请求路径
//requestDispatcher.forward(req,resp);
context.getRequestDispatcher("/gp").forward(req,resp);
}
读取资源文件
Properties
- 在java目录下新建properties
- 在resources目录下新建properties
发现:都被打包到了同一个路径下:classes,我们俗称这个路径为classpath:
//db.properties
username=root
password=123
public class ServletDemo04 extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
InputStream stream = this.getServletContext().getResourceAsStream("/WEB-INF/classes/db.properties");//第一个/代表当前web项目
Properties prop = new Properties();
prop.load(stream);
String username = prop.getProperty("username");
String password = prop.getProperty("password");
resp.getWriter().print("username"+":"+username);
resp.getWriter().print("password"+":"+password);
}
}
HttpServletResponse
web服务器接收到客户端的http请求,针对这个请求,分别创建一个代表请求HttpServletRequest对象,代表响应的一个HttpServletResponse;
- 如果要获取客户端请求过来的参数:找HttpServletRequest
- 如果要给客户端响应一些信息:找HttpServletResponse
简单分类
//负责向浏览器发送数据的方法
ServletOutputStream getOutputStream() throws IOException;
PrintWriter getWriter() throws IOException;
//负责向浏览器发送响应头的方法
void setCharacterEncoding(String var1);
void setContentLength(int var1);
void setContentLengthLong(long var1);
void setContentType(String var1);
void setDateHeader(String var1, long var2);
void addDateHeader(String var1, long var2);
void setHeader(String var1, String var2);
void addHeader(String var1, String var2);
void setIntHeader(String var1, int var2);
void addIntHeader(String var1, int var2);
//响应的状态码
int SC_OK = 200;
int SC_CREATED = 201;
int SC_ACCEPTED = 202;
int SC_BAD_REQUEST = 400;
int SC_NOT_FOUND = 404;
int SC_INTERNAL_SERVER_ERROR = 500;
下载文件
1. 向浏览器输出消息
2. 下载文件
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
public class FileServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//1要获取下载文件的路径
String realPath = "D:\\IDEA\\javaweb-3-7-servlet\\response\\src\\main\\resources\\1.jpg";
System.out.println("下载文件的路径"+realPath);
//2下载的文件名
String fileName = realPath.substring(realPath.lastIndexOf("\\") + 1);
//3设置让浏览器能够支持(Content-Disposition)下载我们需要的东西;中文文件名用URLEncoder.encode(fileName,"UTF-8"));编码,否则有可能乱码
resp.setHeader("Content-Disposition","attachment;filename="+fileName);
//4获取下载文件的输入流
FileInputStream in = new FileInputStream(realPath);
//创建缓冲区
int len = 0;
byte[] buffer = new byte[1024];
//6获取OutputStream对象
ServletOutputStream out = resp.getOutputStream();
//7将FileOutputStream流写入到buffer缓冲区,使用OutputStream将缓冲区中的数据输入到客户端
while((len=in.read(buffer))>0){
out.write(buffer,0,len);
}
in.close();
out.close();
}
}
验证码功能
public class ImageServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//让浏览器3秒自动刷新一次
resp.setHeader("refresh","3");
//在内存中创建一个图片
BufferedImage image = new BufferedImage(80, 20, BufferedImage.TYPE_INT_RGB);
//得到图片
Graphics2D g = (Graphics2D) image.getGraphics();//画笔
//设置图片的背景颜色
g.setColor(Color.cyan);
g.fillRect(0,0,80,20);
//给图片写数据
g.setColor(Color.BLACK);
g.setFont(new Font(null,Font.BOLD,20));
g.drawString(makeNum(),0,20);
//告诉浏览器,这个请求用图片的方式打开
resp.setContentType("image/jpg");
//网站存在缓存,不让浏览器缓存
resp.setDateHeader("expirer",-1);
resp.setHeader("Cache-Control","no-cache");
resp.setHeader("Pragma","no-cache");
//把图片写给浏览器
ImageIO.write(image,"jpg",resp.getOutputStream());
}
//生成随机数
private String makeNum(){
Random random = new Random();
String num = random.nextInt(9999999)+"";
StringBuffer sb = new StringBuffer();
for (int i = 0; i < 7-num.length(); i++) {
sb.append("0");//不足7位数用0填充
}
num = sb.toString()+num;
return num;
}
}
实现重定向
一个web资源(B)收到客户端(A)请求后,B会通知客户端(A)去访问另外一个web资源(C),这个过程叫重定向
public class RedirectServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//resp.setHeader("Location","/response_war/Image");
//resp.setStatus(302);
resp.sendRedirect("/response_war/Image");
}
}
简单实现登录重定向
public class requestText extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//处理请求
String username = req.getParameter("username");
String password = req.getParameter("password");
System.out.println(username+":"+password);
//重定向一定要注意路径问题 ,否则404
resp.sendRedirect("/response_war/success.jsp");
}
}
<servlet>
<servlet-name>rt</servlet-name>
<servlet-class>requestText</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>rt</servlet-name>
<url-pattern>/rt</url-pattern>
</servlet-mapping>
//index.jsp
<html>
<body>
<h2>Hello World!</h2>
<%--这里提交的路径,需要寻找到项目的路径--%>
<%--${pageContext.request.contextPath}代表当前的项目--%>
<form action="${pageContext.request.contextPath}/rt" method="get">
用户名:<input type="text" name="username"><br>
密码:<input type="password" name="password"><br>
<input type="submit">
</form>
</body>
</html>
//success.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>success</title>
</head>
<body>
<h1>success</h1>
</body>
</html>
HttpServletRequest
HttpServletRequest代表客户端的请求,用户通过Http协议访问服务器,HTTP请求中的所有信息会被封装到HttpServletRequest,通过这个HttpServletRequest的方法,获得客户端的所有信息;
获取参数,请求转发
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setCharacterEncoding("UTF-8");//解决乱码
req.setCharacterEncoding("UTF-8");//解决乱码
String username = req.getParameter("username");
String password = req.getParameter("password");
String[] hobbies = req.getParameterValues("hobby");
System.out.println(username);
System.out.println(password);
System.out.println(Arrays.toString(hobbies));
//通过请求转发
req.getRequestDispatcher(req.getContextPath()+"/success.jsp").forward(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"
metadata-complete="true">
</web-app>
<dependencies>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
</dependencies>
Cookie、Session
1. 服务端给客户端一个 信件,客户端下次访问服务端带上信件就可以了; cookie
2. 服务器登记你来过了,下次你来的时候我来匹配你; seesion
保存会话的两种技术
cookie
客户端技术 (响应,请求)
session
服务器技术,利用这个技术,可以保存用户的会话信息? 我们可以把信息或者数据放在Session
中!
Cookie
1. 从请求中拿到cookie信息
2. 服务器响应给客户端cookie
Cookie[] cookies = req.getCookies(); //获得Cookie
cookie.getName(); //获得cookie中的key
cookie.getValue(); //获得cookie中的vlaue
new Cookie("lastLoginTime", System.currentTimeMillis()+""); //新建一个cookie
cookie.setMaxAge(24*60*60); //设置cookie的有效期
resp.addCookie(cookie); //响应给客户端一个cookie
import javax.servlet.ServletException;
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.io.PrintWriter;
import java.util.Date;
//保存用户上一次访问的时间
public class cookieDemo01 extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//服务器告知用户到来的时间,并把这个时间封装成为一个信件,用户下次再来,服务器就会知道用户来了
//解决中文乱码
req.setCharacterEncoding("utf-8");
resp.setCharacterEncoding("utf-8");
PrintWriter out = resp.getWriter();
//Cookie 服务器端从客户端获取
Cookie[] cookies = req.getCookies();
//判断Cookie是否存在
if(cookies!=null){
out.write("你上一次访问的时间是");
for (int i = 0; i < cookies.length; i++) {
Cookie cookie = cookies[i];
//获取cookie的名字
if(cookie.getName().equals("lastLoginTime")){
//获取cookie中的值
long lastLoginTime = Long.parseLong(cookie.getValue());
Date date = new Date(lastLoginTime);
out.write(date.toLocaleString());
}
}
}else{
out.write("this is you first come!");
}
//服务器端给客户端响应一个cookie
Cookie cookie = new Cookie("lastLoginTime", System.currentTimeMillis()+"");
resp.addCookie(cookie);
}
}
删除
Cookie
;
- 不设置有效期,关闭浏览器,自动失效;
- 设置有效期时间为 0 ;
Session(重点)
Session和cookie的区别:
- Cookie是把用户的数据写给用户的浏览器,浏览器保存 (可以保存多个)
- Session把用户的数据写到用户独占Session中,服务器端保存 (保存重要的信息,减少服务器资源的浪费)
- Session对象由服务创建;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
public class SessionDemo01 extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//解决乱码问题
req.setCharacterEncoding("UTF-8");
resp.setCharacterEncoding("UTF-8");
resp.setContentType("text/html;charset=UTF-8");
//得到Session
HttpSession session = req.getSession();
//给Session中存东西
session.setAttribute("name",new person("kk",1));
//获取Session的ID
String id = session.getId();
//判断Session是不是新创建
if (session.isNew()){
resp.getWriter().write("Session成功创建,ID:"+id);
}else {
resp.getWriter().write("Session已经在服务器中存在了,ID:"+id);
}
}
}
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
public class SessionDemo02 extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//解决乱码问题
req.setCharacterEncoding("UTF-8");
resp.setCharacterEncoding("UTF-8");
resp.setContentType("text/html;charset=UTF-8");
//得到Session
HttpSession session = req.getSession();
person person = (person) session.getAttribute("name");
System.out.println(person);
}}
public class person {
private String name;
private int age;
public person(String name, int age) {
this.name = name;
this.age = age;
}
public person() {
}
@Override
public String toString() {
return "Person{"+
"name='"+name+'\''+
",age="+age+
'}';
}
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
注销
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
public class SessionDemo03 extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
HttpSession session = req.getSession();
session.removeAttribute("name");
session.invalidate();//手动注销Session 01-02-03显示500
}
}
//web.xml
<!-- 设置Session默认的失效时间-->
<session-config>
<!-- 15min后自动失效-->
<session-timeout>15</session-timeout>
</session-config>
</web-app>
JSP
浏览器向服务器发送请求,不管访问什么资源,其实都是在访问
Servlet
!
JSP最终也会被转换成为一个Java类!
JSP
本质上就是一个
Servlet
在JSP页面中;
只要是 JAVA代码就会原封不动的输出;
如果是HTML代码,就会被转换为:
out.write("<html>\r\n");
JSP基础语法
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Text01</title>
</head>
<body>
<%--JSP表达式
作用:用来将程序的输出,输出到客户端--%>
<%= new java.util.Date()%>
<hr>
<%--JSP脚本片段--%>
<%
int sum = 0;
for (int i = 0; i < 100; i++) {
sum+=i;
}
out.println("<h1>Sum="+sum+"</h1>");
%>
<%-- 在代码中镶嵌HTML元素--%>
<%
for(int i = 0; i < 5; i++){
%>
<h1>hello<%=i%></h1>
<%--打印出了5个hello--%>
<%
}
%>
<hr>
<%!
static{
System.out.println("Loading Servlet!");
}
private int globalVar = 0;
public void k(){
System.out.println("进入了方法k");
}
%>
<!--HTML注释可以被查看-->
<%--JSP注释--%>
</body>
</html>
JSP指令
<%@page args.... %>
<%@include file=""%>
<%--@include会将两个页面合二为一--%>
<%@include file="common/header.jsp"%>
<h1>网页主体</h1>
<%@include file="common/footer.jsp"%>
<hr>
<%--jSP标签 jsp:include:拼接页面,本质还是三个 --%>
<jsp:include page="/common/header.jsp"/>
<h1>网页主体</h1>
<jsp:include page="/common/footer.jsp"/>
pom.xml
<dependencies>
<!-- servlet的依赖-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
<!-- jsp的依赖-->
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.3</version>
</dependency>
<!-- jstl表达式的依赖-->
<dependency>
<groupId>javax.servlet.jsp.jstl</groupId>
<artifactId>jstl-api</artifactId>
<version>1.2</version>
</dependency>
<!-- standard标签库-->
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
<!-- 连接数据库-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
</dependencies>
内置对象
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<%--内置对象--%>
<%
pageContext.setAttribute("name1","1");//保存的数据只在一个页面中有效
request.setAttribute("name2","2");//保存的数据只在一次请求中有效,请求转发会携带这个数据
session.setAttribute("name3","3");//保存的数据只在一次会话中有效,从打开浏览器到关闭浏览器
application.setAttribute("name4","4");//保存的数据只在服务器中有效,从打开服务器到关闭服务器
%>
<%--脚本片段中的代码,会原封不动生成到.jsp.java
要求:这里面的代码必须保证java语法的正确性--%>
<%
//从pageContext取出,我们通过寻找的方式来
//从底层到高层:作用域
String name1 = (String) pageContext.findAttribute("name1");
String name2 = (String) pageContext.findAttribute("name2");
String name3 = (String)pageContext.findAttribute("name3");
String name4 = (String)pageContext.findAttribute("name4");
String name5 = (String) pageContext.findAttribute("name5");//不存在
%>
<%--使用EL表达式输出 ${} --%>
<h1>取出的值为:</h1>
<h3>${name1}</h3>
<h3>${name2}</h3>
<h3>${name3}</h3>
<h3>${name4}</h3>
<h3>${name5}</h3>
<h3><%=name5%></h3>
</body>
</html>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<%
//从pageContext取出,我们通过寻找的方式来
//从底层到高层:作用域
String name1 = (String) pageContext.findAttribute("name1");
String name2 = (String) pageContext.findAttribute("name2");
String name3 = (String)pageContext.findAttribute("name3");
String name4 = (String)pageContext.findAttribute("name4");
String name5 = (String) pageContext.findAttribute("name5");//不存在
%>
<%--使用EL表达式输出 ${} --%>
<h1>取出的值为:</h1>
<h3>${name1}</h3>
<h3>${name2}</h3>
<h3>${name3}</h3>
<h3>${name4}</h3>
<h3>${name5}</h3>
<h3><%=name5%></h3>
</body>
</html>
JSP标签、JSTL标签、EL表达式
JSP标签
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<%--<jsp:include page=""></jsp:include>--%>
<jsp:forward page="jsptag02.jsp">
<jsp:param name="name" value="kd"></jsp:param>
<jsp:param name="age" value="18"></jsp:param>
</jsp:forward>
</body>
</html>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<%--取出参数--%>
名字:<%=request.getParameter("name")%>
年龄:<%=request.getParameter("age")%>
</body>
</html>
EL表达式: ${ }
获取数据
执行运算
获取
web
开发的常用对象
JSTL表达式
JSTL标签库的使用就是为了弥补HTML标签的不足;
它自定义许多标签,可以供我们使用,标签的功能和Java代码一样!
- 格式化标签
- SQL标签
- XML 标签
- 核心标签 (掌握部分)菜鸟教程
JSTL
标签库使用步骤
- 引入对应的 taglib
- 使用其中的方法
- 在Tomcat 也需要引入 jstl的包,否则会报错:JSTL解析错误
c:if
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%--引入JSTL核心标签库,我们才能使用JSTL核心标签--%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h4>if测试</h4>
<form action="coreif.jsp" method="get">
<%--
EL表达式获取表单中的数据
${param,参数名}
--%>
<input type="text" name="username" value="${param.username}">
<input type="submit" value="登录">
</form>
</body>
</html>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%--引入JSTL核心标签库,我们才能使用JSTL核心标签--%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@taglib prefix="x" uri="http://java.sun.com/jsp/jstl/xml" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h4>if测试</h4>
<form action="coreif.jsp" method="get">
<%--
EL表达式获取表单中的数据
${param,参数名}
--%>
<input type="text" name="username" value="${param.username}">
<input type="submit" value="登录">
</form>
<%--判断如果提交的用户名是管理员,则登陆成功--%>
<%--
<%
if(request.getParameter("username").equals("admin")){
out.print("登陆成功");
}
%>
--%>
<c:if test="${param.username=='admin'}" var="isAdmin">
<c:out value="欢迎登录"></c:out>
</c:if>
<c:out value="${isAdmin}"></c:out>
</body>
</html>
c:choose c:when
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<%--定义一个变量score 值为85--%>
<%--注意自闭和标签--%>
<c:set var="score" value="85"/>
<c:choose>
<c:when test="${score>=90}">
优秀
</c:when>
<c:when test="${score<=60}">
不及格
</c:when>
<c:when test="${score>=80}">
良好
</c:when>
<c:when test="${score>=60}">
及格
</c:when>
</c:choose>
</body>
</html>
c:forEach
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page import="java.util.ArrayList" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<%
ArrayList<String> people = new ArrayList<>();
people.add(0,"q");//list 从0开始
people.add(1,"w");
people.add(2,"e");
people.add(3,"r");
people.add(4,"t");
request.setAttribute("list",people);
%>
<%--
var 每一次遍历出来的变量
items 要遍历的对象
默认 :begin为first end为last step为1
--%>
<c:forEach var="people" items="${list}">
<c:out value="${people}"/><br>
</c:forEach>
<hr>
<c:forEach var="people" items="${list}" begin="1" end="3" step="2">
<c:out value="${people}"/><br><%--w,r--%>
</c:forEach>
</body>
</html>
JavaBean
连接数据库
package com.pojo;
//实体类:一般和数据库中表结构一一对应
public class people {
private int id;
private String name;
private int age;
private String address;
public people() {
}
public people(int id, String name, int age, String address) {
this.id = id;
this.name = name;
this.age = age;
this.address = address;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Override
public String toString() {
return "people{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
", address='" + address + '\'' +
'}';
}
}
JavaBean有特定的写法:
必须要有一个无参构造
属性必须私有化
必须有对应的get/set方法;
一般用来和数据库的字段做映射 ORM;
<%@ page import="com.pojo.people" %><%--
Created by IntelliJ IDEA.
User: Administrator
Date: 2022/8/3
Time: 11:58
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>
<%
//people people = new people();
//people.setId(1);
//people.setAge(12);
//people.setName("啦啦");
//people.setAddress("啦啦啦");
%>
<jsp:useBean id="people" class="com.pojo.people" scope="page"/>
<jsp:setProperty name="people" property="id" value="1"/>
<jsp:setProperty name="people" property="age" value="2"/>
<jsp:setProperty name="people" property="name" value="啦啦"/>
<jsp:setProperty name="people" property="address" value="啦啦啦"/>
<jsp:getProperty name="people" property="id"/>
<jsp:getProperty name="people" property="name"/>
<jsp:getProperty name="people" property="age"/>
<jsp:getProperty name="people" property="address"/>
</body>
</html>
MVC三层架构
Model
- 业务处理 :业务逻辑(Service)
- 数据持久层:CRUD (Dao)
View
- 展示数据
- 提供链接发起Servlet请求 (a,form,img…)
Controller (Servlet)
- 接收用户的请求 :(req:请求参数、Session信息….)
- 交给业务层处理对应的代码
- 控制视图的跳转
Filter
Filter:过滤器 ,用来过滤网站的数据;
- 处理中文乱码
- 登录验证….
导包
实现Filter接口,重写对应的方法
package com.Filter;
import javax.servlet.*;
import java.io.IOException;
public class CharacterEncodingFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
//初始化:web服务器启动就已经初始化了,随时等待过滤对象出现
System.out.println("CharacterEncodingFilter初始化");
}
@Override
/*Chain:链
1.过滤器中的所有代码,在过滤特定请求的时候都会执行
2.必须让过滤器继续同行 filterChain.doFilter(servletRequest, servletResponse);*/
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
servletRequest.setCharacterEncoding("utf-8");
servletResponse.setCharacterEncoding("utf-8");
servletResponse.setContentType("text/html;charaest=UTF-8");
System.out.println("CharacterEncodingFilter执行前");
filterChain.doFilter(servletRequest, servletResponse);//让请求继续走;如果不写程序将被拦截停止
System.out.println("CharacterEncodingFilter执行后");
}
@Override
public void destroy() {
//销毁:web服务器关闭的时候,过滤器会被销毁
System.out.println("CharacterEncodingFilter销毁");
}
}
在web.xml中配置 Filter
<servlet>
<servlet-name>showServlet</servlet-name>
<servlet-class>Servlet.showServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>showServlet</servlet-name>
<url-pattern>/servlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>showServlet</servlet-name>
<url-pattern>/show/servlet</url-pattern>
</servlet-mapping>
<filter>
<filter-name>CharacterEncodingFilter</filter-name>
<filter-class>com.Filter.CharacterEncodingFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<!--只要是/show的任何请求,会经过这个过滤器-->
<url-pattern>/show/*</url-pattern>
</filter-mapping>
监听器
编写一个监听器
实现监听器的接口…
package Listener;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
//统计网站在线人数:统计session
public class OnlinePeopleListener implements HttpSessionListener {
//创建session监听:看一举一动
//一旦创建session就会触发一次这个事件
@Override
public void sessionCreated(HttpSessionEvent httpSessionEvent) {
ServletContext ctx = httpSessionEvent.getSession().getServletContext();
Integer onlineCount = (Integer) ctx.getAttribute("OnlineCount");
if(onlineCount==null){
onlineCount = new Integer(1);
}else {
int count=onlineCount.intValue();
onlineCount = new Integer(count+1);
}
ctx.setAttribute("OnlineCount",onlineCount);
}
@Override
//销毁session监听
//一旦销毁session就会触发一次这个事件
public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {
ServletContext ctx = httpSessionEvent.getSession().getServletContext();
Integer onlineCount = (Integer) ctx.getAttribute("OnlineCount");
if(onlineCount==null){
onlineCount = new Integer(0);
}else {
int count=onlineCount.intValue();
onlineCount=new Integer(count-1);
}
ctx.setAttribute("OnlineCount",onlineCount);
}
}
web.xml中注册监听器
<!--注册监听器-->
<listener>
<listener-class>Listener.OnlinePeopleListener</listener-class class>
</listener>
index.jsp
当前有<span>
<%=this.getServletConfig().getServletContext().getAttribute("OnlineCount")%>
</span>人在线
过滤器、监听器常见应用
监听器:
GUI
编程中经常使用;
public class TestPanel {
public static void main(String[] args) {
Frame frame = new Frame("中秋节快乐"); //新建一个窗体
Panel panel = new Panel(null); //面板
frame.setLayout(null); //设置窗体的布局
frame.setBounds(300,300,500,500);
frame.setBackground(new Color(0,0,255)); //设置背景颜色
panel.setBounds(50,50,300,300);
panel.setBackground(new Color(0,255,0)); //设置背景颜色
frame.add(panel);
frame.setVisible(true); //监听事件,监听关闭事件
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
super.windowClosing(e); }
}); } }
JDBC
Java连接数据库
导入数据库依赖
<dependencies>
<!--mysql的驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
</dependencies>
JDBC
固定步骤:
1. 加载驱动
2. 连接数据库,代表数据库
3. 向数据库发送SQL的对象Statement : CRUD
4. 编写SQL (根据业务,不同的SQL)
5. 执行SQL
6. 关闭连接
package com.text;
import java.sql.*;
public class TextJdbc {
public static void main(String[] args) throws SQLException {
//配置信息 useUnicode=true&characterEncoding=utf-8解决中文乱码
String url="jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8";
String username="root";
String password="123456";
//1.加载驱动
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
//2.连接数据库,代表数据库
Connection connection = DriverManager.getConnection(url,username,password);
//3.向数据库发送SQL的对象Statement:CRUD
Statement statement = connection.createStatement();
//4.编写SQL
String sql="select * from users";
String sql1 = "delete from users where id = 1";
//受影响的行数---executeUpdate增删改
int i = statement.executeUpdate(sql1);
//5.执行查询Sql,返回结果集对象
ResultSet rs = statement.executeQuery(sql);
while(rs.next()){
System.out.println("id="+rs.getObject("id"));
System.out.println("name="+rs.getObject("name"));
System.out.println("password="+rs.getObject("password"));
System.out.println("email"+rs.getObject("email"));
System.out.println("birthday="+rs.getObject("birthday"));
}
//6.关闭连接,释放资源(先开后关)
rs.close();
statement.close();
connection.close();
}
}
预编译
SQL
package com.text;
import java.sql.*;
public class TextJdbc2 {
public static void main(String[] args) throws Exception {
//配置信息 useUnicode=true&characterEncoding=utf-8解决中文乱码
String url = "jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8";
String username = "root";
String password = "123456";
//1.加载驱动
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
//2.连接数据库,代表数据库
Connection connection = DriverManager.getConnection(url, username, password);
//3.编写SQL
String sql;
sql = "insert into users (id, name, password, email, birthday) values(?,?,?,?,?)";
//4.预编译
PreparedStatement preparedStatement = connection.prepareStatement(sql);
preparedStatement.setInt(1,4);//给第一个占位符? 的值赋值为4
preparedStatement.setString(2,"ss");
preparedStatement.setString(3,"4554");
preparedStatement.setString(4,"gg@qq.com");
preparedStatement.setDate(5,new Date(new java.util.Date().getTime()));
//5.执行sql
int i = preparedStatement.executeUpdate(sql);
if(i>0){
System.out.println("scuess");
}
//6.关闭连接,释放资源(先开后关)
preparedStatement.close();
connection.close();
}
}
JDBC事务
Junit
单元测试
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
package com.text;
import org.junit.Test;
public class TextJDBC3 {
@Test
public void text(){
System.out.println("hh");
}
}
简单使用
@Test注解只有在方法上有效,只要加了这个注解的方法,就可以直接运行!
package com.text;
import org.junit.Test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class TextJDBC3 {
@Test
public void text() {
//配置信息 useUnicode=true&characterEncoding=utf-8解决中文乱码
String url = "jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8";
String username = "root";
String password = "123456";
Connection connection = null;
try {//1.加载驱动
Class.forName("com.mysql.jdbc.Driver");
//2.连接数据库,代表数据库
connection = DriverManager.getConnection(url, username, password);
//3.通知数据库开启事务 false:开启
connection.setAutoCommit(false);
String sql ="update account set money = money-100 where name = 'A'";
connection.prepareStatement(sql).executeUpdate();
//制造错误
// int i =1/0;
String sql2="update account set money = money-100 where name = 'B'";
connection.prepareStatement(sql2).executeUpdate();
connection.commit();//以上两条sql语句执行成功,提交事务
System.out.println("scuess");
} catch (Exception e) {
try {
connection.rollback();
} catch (SQLException ex) {
ex.printStackTrace();
}
}finally {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}