JavaWeb
1.Servlet
<?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>
<servlet-name>hello</servlet-name>
<servlet-class>com.jf.servlet.HelloServlet</servlet-class>
</servlet>
<!--Servlet的请求路径-->
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>error</servlet-name>
<servlet-class>com.jf.servlet.ErrorServlet</servlet-class>
<!--可以自定义后缀实现请求映射,注意*前面不能加项目映射的路径-->
<!--优先级问题,指定了固有的映射路径优先级最高,如果找不到就会走默认的处理请求-->
</servlet>
<servlet-mapping>
<servlet-name>error</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
</web-app>
package com.jf.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;
public class ErrorServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html");
resp.setCharacterEncoding("utf-8");
PrintWriter writer = resp.getWriter();
writer.print("<h1>404</h1>");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doPost(req, resp);
}
}
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//
package com.jf.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class HelloServlet extends HttpServlet {
public HelloServlet() {
}
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("进入doGet方法");
PrintWriter writer = resp.getWriter();
writer.print("Hello,Servlet");
}
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doPost(req, resp);
}
}
2.ServletContext
web容器在启动的时候,它会为每个web程序都创建一个对应的ServletContext对象,它代表了当前
的web应用:
1.共享数据
我在这个Servet中保存的数据,可以在另外一个servlet中拿到:
package com.jf.servlet;
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 HelloServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext context = this.getServletContext();
String username="张飞";//数据
context.setAttribute("username",username);//将一个数据保存在了ServletContext中,名字为;username,值username
}
}
package com.jf.servlet;
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 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("名字"+username);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
<servlet>
<servlet-name>hello</servlet-name>
<servlet-class>com.jf.servlet.HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>getc</servlet-name>
<servlet-class>com.jf.servlet.GetServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>getc</servlet-name>
<url-pattern>/getc</url-pattern>
</servlet-mapping>
2.获取初始化参数
<!--配置一些web应用初始化参数-->
<context-param>
<param-name>url</param-name>
<param-value>jdbc:mysql://localhost:3306/mybatis</param-value>
</context-param>
package com.jf.servlet;
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 ServletDemo03 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext context = this.getServletContext();
String url = context.getInitParameter("url");
resp.getWriter().print(url);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
<servlet>
<servlet-name>gp</servlet-name>
<servlet-class>com.jf.servlet.ServletDemo03</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>gp</servlet-name>
<url-pattern>/gp</url-pattern>
</servlet-mapping>
3.请求转发
package com.jf.servlet;
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 ServletDemo04 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext context = this.getServletContext();
context.getRequestDispatcher("/gp").forward(req,resp);//请求转发
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
<servlet>
<servlet-name>sd4</servlet-name>
<servlet-class>com.jf.servlet.ServletDemo04</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>sd4</servlet-name>
<url-pattern>/sd4</url-pattern>
</servlet-mapping>
4.读取资源文件
Properties
在java日录下新建properties
在resources日录下新建properties
发现:都被打包到了同一个路径下:classes,我们俗称这个路径为classpath:
maven由于他的约定大于配置,我们之后可以能遇到我们写的配置文件,无法被导出或者生效的问题,解决方案:
需要一个文件流
username=root
password=123456
<!--在build中配置resources,来防止资源导出失败的问题-->
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
</build>
package com.jf.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.InputStream;
import java.util.Properties;
public class ServletDemo05 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
InputStream is = this.getServletContext().getResourceAsStream("/WEB-INF/classes/db.properties");
Properties prop = new Properties();
prop.load(is);
String user = prop.getProperty("username");
String pwd = prop.getProperty("password");
resp.getWriter().print(user+":"+pwd);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
<servlet>
<servlet-name>sd5</servlet-name>
<servlet-class>com.jf.servlet.ServletDemo05</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>sd5</servlet-name>
<url-pattern>/sd5</url-pattern>
</servlet-mapping>
3.HttpServletResponse
web服务器接收到客户端的http请求,针对这个请求,分别创建一个代表请求的HttpServletRequest对象,代表响应的一个HttpServletResponse。
如果要获取客户端请求过来的参数:找HttpServletRequest
如果要给客户端响应一些信息:找HttpServletResponse
1.下载文件
package com.jf.servlet;
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;
import java.net.URLEncoder;
public class FileServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 1.要获取下载文件的路径
String realPath = "D:\\code\\maven\\java-14-maven\\response\\src\\main\\resources\\zhangsan.png";
System.out.println("下载文件的路径:"+realPath);
// 2.下载的文件名是啥
String fileName = realPath.substring(realPath.lastIndexOf("\\") + 1);
// 3.设置想办法让浏览器能够支持下载我们需要的东西,中文文件名URLEncoder.encode编码,否则有可能乱码
resp.setHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode(fileName,"UTF-8"));
// 4.获取下载文件的输入流
FileInputStream in = new FileInputStream(realPath);
// 5.创建缓冲区
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();
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
<servlet>
<servlet-name>filedown</servlet-name>
<servlet-class>com.jf.servlet.FileServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>filedown</servlet-name>
<url-pattern>/down</url-pattern>
</servlet-mapping>
2.验证码功能
package com.jf.servlet;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
public class ImageServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//如何让浏览器5秒刷新一次
resp.setHeader("refresh","5");
//在内存中创建一个图片
BufferedImage image = new BufferedImage(80,20,BufferedImage.TYPE_INT_RGB);
//得到图片
Graphics2D g = (Graphics2D) image.getGraphics();//笔
//设置图片的背景颜色
g.setColor(Color.white);
g.fillRect(0,0,80,20);
//给图片写数据
g.setColor(Color.BLUE);
g.setFont(new Font(null,Font.BOLD,20));
g.drawString(makeNum(),0,20);
//告诉浏览器,这个请求用图片的方式打开
resp.setContentType("image/jpg");
//浏览器有缓存,不让浏览器缓存
resp.setDateHeader("expires",-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");
}
num = sb.toString() + num;
return num;
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
<servlet>
<servlet-name>ImageServlet</servlet-name>
<servlet-class>com.jf.servlet.ImageServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ImageServlet</servlet-name>
<url-pattern>/img</url-pattern>
</servlet-mapping>
3.重定向
B一个web资源收到客户端A请求后,B会通知A客户端去访问另外一个web资源C,这个过程就叫重定向
常见场景:
- 用户登录
void sendRedirect(String var1) throws IOException;
测试:
package com.jf.servlet;
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 RedirectServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// resp.setHeader(" Location","/response_war/img");
// resp.setStatus(302);
resp.sendRedirect("/response_war/img");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
重定向和转发的不同点:
-
相同点:
页面都会跳转
-
不同点:
请求转发的url不会发生变化
重定向时候,url地址栏会发生变化
Demo:
package com.jf.servlet;
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 Request extends HttpServlet {
@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");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
<html>
<body>
<!--这里提交的路径,需要寻找项目的路径-->
<%--${pageContext.request.contextPath}代表当前的项目--%>
<h2>Hello World!</h2>
<form action="${pageContext.request.contextPath}/login" method="get">
用户名:<input type="text" name="username"><br>
密码:<input type="password" name="password"><br>
<input type="submit">
</form>
</body>
</html>
<%--
Created by IntelliJ IDEA.
User: hjf
Date: 2024/8/19
Time: 16:50
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
<h1>Success</h1>
</head>
<body>
</body>
</html>
4.HttpServletRequest
HttpServletRequest代表客户端的请求,用户通过http协议访问服务器,HTTP请求中的所有的信息会被封装到HttpServletRequest,通过这个HttpServletRequest方法,获得客户端的所有信息。
获取参数,请求转发:
package com.jf.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.Array;
import java.util.Arrays;
public class LoginServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
resp.setCharacterEncoding("utf-8");
String username = req.getParameter("username");
String password = req.getParameter("password");
String[] hobbies = req.getParameterValues("hobbies");
System.out.println("===============");
System.out.println(username);
System.out.println(password);
System.out.println(Arrays.toString(hobbies));
System.out.println("======================");
//通过请求转发
//这里的/代表当前的web应用
req.getRequestDispatcher("/success.jsp").forward(req,resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>登录</title>
</head>
<body>
<div>
<form action="${pageContext.request.contextPath}/login" method="post">
用户名:<input type="text" name="username"><br>
密码:<input type="password" name="password"><br>
爱好:
<input type="checkbox" name="hobbies" value="电影">电影
<input type="checkbox" name="hobbies" value="代码">代码
<input type="checkbox" name="hobbies" value="旅游">旅游
<input type="checkbox" name="hobbies" value="独处">独处
<br>
<input type="submit">
</form>
</div>
</body>
</html>
<%--
Created by IntelliJ IDEA.
User: hjf
Date: 2024/8/19
Time: 17:33
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>
<h1>登录成功</h1>
</body>
</html>
5.Cookie Session
5.1 保存回话的两种技术
cookie
- 客户端技术(响应,请求)
session
- 服务端技术,利用这个技术,可以保存用户的会话信息
5.2 cookie
1.从请求中拿到cookie信息
2.服务器响应给客户端cookie
- 一个Cookie只能保存一个信息
- 一个web站点可以给浏览器发送多个cookie,最多可以保存20个cookie
- Cookie大小有限制为4kb
- 300个cookie浏览器上限
删除Cookie;
- 不设置有效期,关闭浏览器,自动失效
- 设置有效期为0
编码和解码
URLEncoder.encode("张飞","utf-8")
URLDecoder.decode(cookie.getValue(),"utf-8")
package com.jf.servlet;
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 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
//判断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("这是你第一次访问本站");
}
//服务给客户端响应一个cookie
Cookie cookie = new Cookie("lastLoginTime",System.currentTimeMillis()+"");
//cookie有效期为1天
cookie.setMaxAge(24*60*60);
resp.addCookie(cookie);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
package com.jf.servlet;
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.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Date;
//中文数据传递
public class CookieDemo03 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//解决中文乱码问题
req.setCharacterEncoding("utf-8");
resp.setCharacterEncoding("utf-8");
//Cookie,服务器从客户端拿取
Cookie[] cookies = req.getCookies();//这里返回数组,说明存在多个cookie
PrintWriter out = resp.getWriter();
//判断cookie是否存在
if(cookies!=null){
//如果存在
out.write("你上一次访问的时间是:");
for (int i = 0; i < cookies.length; i++) {
Cookie cookie = cookies[i];
//获取cookie的名字
if(cookie.getName().equals("name")){
//解码
out.write(URLDecoder.decode(cookie.getValue(),"utf-8"));
}
}
}else {
out.write("这是你第一次访问本站");
}
//编码
Cookie cookie = new Cookie("name", URLEncoder.encode("张飞","utf-8"));
resp.addCookie(cookie);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doPost(req, resp);
}
}
5.3 Session(重点)
什么是session
- 服务器会给每一个用户创建一个Session对象
- 一个session 独占一个浏览器,只要浏览器没有关闭,这个session就存在
- 用户登录网站,整个网站都可以访问----》保存用户的信息
session和cookie的区别
- cookie就是把用户的数据写给浏览器,浏览器保存(可以保存多个)
- session把用户的数据写到用户独占Session中,服务器保存(保存重要的信息,减少服务器资源的浪费)
- session对象是由服务创建
使用场景
- 保存一个登陆用户的信息
- 购物车信息
- 在整个网站中经常使用的数据,将它保存在Session中;
package com.jf.servlet;
import com.jf.pojo.Person;
import javax.servlet.ServletException;
import javax.servlet.http.*;
import java.io.IOException;
public class SessionDemo01 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//解决乱码问题
resp.setCharacterEncoding("utf-8");
req.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=utf-8");
//得到session
HttpSession session = req.getSession();
//给session存信息
session.setAttribute("name",new Person("张飞",15));
//获取session的id
String sessionId = session.getId();
//判断Seesion是不是新创建的
if(session.isNew()){
resp.getWriter().write("session创建成功,ID:"+sessionId);
}else {
resp.getWriter().write("session已经在服务器中存在了,ID:"+sessionId);
}
//session创建的时候做了:
// Cookie cookie = new Cookie("JSESSIONID",sessionId);
// resp.addCookie(cookie);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
得到session
package com.jf.servlet;
import com.jf.pojo.Person;
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 doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//解决乱码问题
resp.setCharacterEncoding("utf-8");
req.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.toString());
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
手动注销
package com.jf.servlet;
import com.jf.pojo.Person;
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 doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
HttpSession session = req.getSession();
session.removeAttribute("name");
session.invalidate();//注销
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
自动注销在web.xml中配置
<!--设置session的失效时间-->
<session-config>
<!--15分钟后失效,以分钟为单位-->
<session-timeout>15</session-timeout>
</session-config>
6.JSP
什么是jsp
- java server page:java服务器端页面,也和servlet一样,用于动态Web页面
最大的特点:
- 写JSP和HTML一样
- 区别:
- HTML只给用户提供静态的数据
- JSP页面可以嵌入java代码,为用户提供动态数据
浏览器向服务器发送请求,不管访问什么资源,其实都是访问Servlet
JSP最终也会被装换一个java类
//初始化
public void _jspInit() {
}
//销毁
public void _jspDestroy() {
}
//JSPService
public void _jspService(HttpServletRequest request,HttpServletResponse response)
final javax.servlet.jsp.PageContext pageContext;//页面上下文
final javax.servlet.ServletContext application;//applicationContext
final javax.servlet.ServletConfig config;//config
javax.servlet.jsp.JspWriter out = null;//out
final java.lang.Object page = this;//page:当前页
javax.servlet.jsp.JspWriter _jspx_out = null;
javax.servlet.jsp.PageContext _jspx_page_context = null;
HttpServletRequest request//请求
HttpServletResponse response//响应
输出页面前增加的代码
response.setContentType("text/html; charset=UTF-8");//设置响应的类型
pageContext = _jspxFactory.getPageContext(this, request, response,
null, false, 8192, true);
_jspx_page_context = pageContext;
application = pageContext.getServletContext();
config = pageContext.getServletConfig();
out = pageContext.getOut();
_jspx_out = out;
以上的这些对象都可以在JSP中使用
在JSP页面中,只要是JAVA代码就会原封不动的输出
如果是HTML代码,就会封装为:
out.write("<html>\r\n")
这样的格式,输出到前端
6.1 JSP基础语法
JSP表达式
<%-- JSP表达式
作用:用来将程序的输出,输出到客户端
--%>
<%= new java.util.Date()%>
JSP脚本片段
<%-- JSP脚本片段--%>
<%
int sum = 0;
for (int i = 0; i <=100; i++) {
sum+=i;
}
out.print("<h1>Sum="+sum+"</h1>");
%>
JSP片段的再实现
<%-- JSP脚本片段--%>
<%
int sum = 0;
for (int i = 0; i <=100; i++) {
sum+=i;
}
out.print("<h1>Sum="+sum+"</h1>");
%>
<%
int x=10;
out.println(x);
%>
<%
int y=2;
out.println(y);
%>
<%--在代码中嵌入HTML代码--%>
<%
for (int i = 0; i <=5; i++) {
%>
<h1>hello world</h1>
<%
}
%>
JSP声明
<%!
static {
System.out.println("Loading Servlet!");
}
private int globVar= 0 ;
public void k(){
System.out.println("进入了K方法");
}
%>
JSP声明:会被编译到JSP生成Java的类中,其他的就会被生成到_jspService方法中。
JSP注释不会在客户端中显示,html就会显示。
6.2 JSP指令
jsp导包
<%@ page import="java.util.Date" %>
jsp定制错误页面
方法一:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page errorPage="error/500.jsp" %>
<html>
<%--定制错误页面--%>
<head>
<title>Title</title>
</head>
<body>
<%
int x =1/0;
%>
</body>
</html>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<img src="../img/500.png" alt="500">
</body>
</html>
方法二:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<%--定制错误页面--%>
<head>
<title>Title</title>
</head>
<body>
<%
int x =1/0;
%>
</body>
</html>
在web.xml中
<error-page>
<error-code>500</error-code>
<location>/error/500.jsp</location>
</error-page>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<img src="../img/500.png" alt="500">
</body>
</html>
JSP拼接页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<%--@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"/>
</body>
</html>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<h1>我是footer</h1>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1>我是header</h1>
</body>
</html>
6.3 9大内置对象
- PageContext 存东西
- Request 存东西
- Response
- Session 存东西
- Application [ServletContext] 存东西
- config [ServletConfig]
- out
- page
- exception
Request :客户端向服务器发送请求,产生的数据,用户看完就没用了,比如:新闻
Session :客户端向服务器发送请求,产生的数据,用户用完一会还有用,比如购物车
Application:客户端向服务器发送请求,产生的数据,一个用户用完了,其他用户还可能使用,比如聊天数据
常见场景:
<%@ 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取出,我们通过寻找的方式来
//从底层到高层(作用域)page-->request-->session-->application
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");
pageContext.forward("/pageDemo03.jsp");
%>
<%--使用EL表达式输出--%>
<h1>取出的值:</h1>
<h2>${name1}</h2>
<h2>${name2}</h2>
<h2>${name3}</h2>
<h2>${name4}</h2>
<h2><%= name5%></h2>
</body>
</html>
7 JSP标签,JSTL标签,EL表达式
<!-- jsp表达式的依赖-->
<groupId>javax.servlet.jsp.jstl</groupId>
<artifactId>jstl-api</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<!-- standard标签 -->
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
EL表达式:${}
作用:
- 获取数据
- 执行运算
- 获取web开发的常用对象
JSP标签:
<jsp:forward page="jspTag2.jsp">
<jsp:param name="name" value="js"/>
<jsp:param name="age" value="15"/>
</jsp:forward>
JSTL表达式:
JSTL标签的使用是为了弥补HTML的不足,它自定义了许多标签,标签的代码和java代码一样
核心标签:
<%@ 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>
<h4>测试</h4>
<form action="coreif.jsp" method="get">
<%-- EL表达式获取表单中的数据
${param.参数名}
--%>
<input type="text" name="username" value="${param.username}">
<input type="submit" value="登录">
</form>
<%--判断如果提交的用户是管理员,则登录成功--%>
<c:if test="${param.username=='admin'}" var="isAdmin">
<c:out value="管理员欢迎您"></c:out>
</c:if>
<c:out value="${isAdmin}"></c:out>
</body>
</html>
<%@ 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>
<%--定义一个变量score,值为85--%>
<c:set var="score" value="85"></c:set>
<c:choose>
<c:when test="${score>=90}">
你的成绩为优秀
</c:when>
<c:when test="${score>=80}">
你的成绩为良好
</c:when>
</c:choose>
</body>
</html>
<%@ page import="java.util.ArrayList" %>
<%@ 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>
<%
ArrayList<String> people = new ArrayList<>();
people.add(0,"张飞");
people.add(1,"张2");
people.add(2,"张3");
people.add(3,"张4");
request.setAttribute("list",people);
%>
<%--
var 每一次遍历的变量
items 要遍历的对象
begin 哪里开始
end 到哪里
step 步长
--%>
<c:forEach var="people" items="${list}">
<c:out value="${people}"></c:out>
</c:forEach>
<hr>
<c:forEach var="people" items="${list}" begin="1" end="2" step="1">
<c:out value="${people}"></c:out>
</c:forEach>
</body>
</html>
8 MVC三层架构
Model
- 业务处理:业务逻辑(Service)
- 数据持久层:CRUD (Dao)
View
- 展示数据
- 提供链接发起Servlet请求(a,img,form...)
Controller
- 接收用户的请求:(req:请求参数,Session信息...)
- 交给业务层处理对应的代码
- 控制视图的跳转
登录-->接收用户的登录请求-->处理用户的请求(获取用户登录的参数,username,password)-->交给业务层处理登录业务(判断用户名和密码是否正确:事务)-->Dao层查询用户名和密码是否正确-->数据库
9 Filter
Filter:过滤器,用来过滤网站的数据
- 用来处理中文乱码
- 用来登录验证
步骤:
1.导包
2.编写过滤器
package com.jf.filter;
import javax.servlet.*;
import java.io.IOException;
public class CharacterEncodingFilter implements Filter {
//初始化 web服务器启动,就已经初始化了
@Override
public void init(FilterConfig filterConfig) throws ServletException {
System.out.println("CharacterEncodingFilter已经初始化了");
}
//chain :链
/*
* 1.过滤中的所有的代码,在过滤特定请求的时候都会执行
* 2.必须要让过滤器继续同行
* chain.doFilter(request,response);
* */
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=UTF-8");
System.out.println("CharacterEncodingFilter执行前");
chain.doFilter(request,response);//让我们的请求继续执行,如果不写,程序就会停止
System.out.println("CharacterEncodingFilter执行后");
}
//销毁 web服务器停止了,过滤就会销毁
@Override
public void destroy() {
System.out.println("CharacterEncodingFilter销毁");
}
}
在web.xml中设置:
<filter>
<filter-name>CharacterEncodingFilter</filter-name>
<filter-class>com.jf.filter.CharacterEncodingFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/servlet/*</url-pattern>
</filter-mapping>
10.监听器
1.编写监听器接口
package com.jf.listener;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
//统计网站的在线人数:
public class OnlineCountListener implements HttpSessionListener {
//创建session监听
//一旦创建session就会触发一次事件
@Override
public void sessionCreated(HttpSessionEvent se) {
ServletContext ctx = se.getSession().getServletContext();
System.out.println(se.getSession().getId());
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);
}
//销毁session监听
//一旦销毁session就会触发一次事件
@Override
public void sessionDestroyed(HttpSessionEvent se) {
ServletContext ctx = se.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);
}
/*
* session销毁
* 手动销毁: se.getSession().invalidate();
* 自动销毁在web.xml中设置:<session-config>
<session-timeout>1</session-timeout>
</session-config>
* */
}
2.在web.xml注册监听器
<listener>
<listener-class>com.jf.listener.OnlineCountListener</listener-class>
</listener>
11.监听器和过滤器的常见应用
在GUI中监听器的应用:
package com.jf.listener;
import java.awt.*;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
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 WindowListener() {
@Override
public void windowOpened(WindowEvent e) {
System.out.println("打开");
}
@Override
public void windowClosing(WindowEvent e) {
System.out.println("关闭img");
System.exit(0);
}
@Override
public void windowClosed(WindowEvent e) {
System.out.println("关闭ed");
}
@Override
public void windowIconified(WindowEvent e) {
}
@Override
public void windowDeiconified(WindowEvent e) {
}
@Override
public void windowActivated(WindowEvent e) {
System.out.println("激活");
}
@Override
public void windowDeactivated(WindowEvent e) {
System.out.println("未激活");
}
});
}
}
用户登录之后才能进入主页,用户注销后就不能进入主页
1.用户登录之后,向session中放入用户的数据
2.进入主页的时候判断用户是否登录
package com.jf.listener;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class SysFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) resp;
if(request.getSession().getAttribute("USER_SESSION")==null){
response.sendRedirect("/error.jsp");
}
chain.doFilter(request,response);
}
@Override
public void destroy() {
}
}
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<form action="/servlet/login" method="post">
<input type="text" name="username">
<input type="submit">
</form>
</body>
</html>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1>错误</h1>
<h1>没有权限,密码错误</h1>
<p><a href="/Login.jsp">返回登录页面</a></p>
</body>
</html>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1>主页</h1>
<p><a href="/servlet/logout">注销</a></p>
</body>
</html>
package com.jf.servlet;
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 LoginServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//获取前端请求的参数
String username = req.getParameter("username");
if(username.equals("admin")){//登录成功
req.getSession().setAttribute("USER_SESSION",req.getSession().getId());
resp.sendRedirect("/sys/success.jsp");
}else {//登录失败
resp.sendRedirect("/error.jsp");
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
package com.jf.servlet;
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 LogoutServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Object user_session = req.getSession().getAttribute("USER_SESSION");
if(user_session!=null){
req.getSession().removeAttribute("USER_SESSION");
resp.sendRedirect("/Login.jsp");
}else {
resp.sendRedirect("/Login.jsp");
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
12.JDBC
JDBC:java连接数据库
需要jar包:
- java.sql
- javax.sql
- mysql-conneter-java
package com.jf.test;
import java.sql.*;
public class TestJdbc {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
//解决中文乱码useUnicode=true&characterEncoding=utf-8
String url = "jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=utf-8&useSSL=true";
String username = "root";
String password = "123456";
//1.加载驱动
Class.forName("com.mysql.jdbc.Driver");
//2.连接数据库
Connection connection = DriverManager.getConnection(url, username, password);
//3.向数据库发送sql的对象
Statement statement = connection.createStatement();
//4.编写sql
String sql="select * from users";
//5.执行sql,返回一个rs:结果集
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.jf.test;
import java.sql.*;
public class TestJdbc2 {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
//解决中文乱码useUnicode=true&characterEncoding=utf-8
String url = "jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=utf-8&useSSL=true";
String username = "root";
String password = "123456";
//1.加载驱动
Class.forName("com.mysql.jdbc.Driver");
//2.连接数据库
Connection connection = DriverManager.getConnection(url, username, password);
//3.编写sql
String sql="insert into users(id, name, password, email, birthday) values (?,?,?,?,?)";
//4.预编译
PreparedStatement preparedStatement = connection.prepareStatement(sql);
preparedStatement.setInt(1,5);//给第一个占位符?的值赋值为1
preparedStatement.setString(2,"java张三");//给第二个占位符?的值赋值为java张三
preparedStatement.setString(3,"123456");//给第三个位符?的值赋值为123456
preparedStatement.setString(4,"[email protected]");//给第四个占位符?的值赋值为[email protected]
preparedStatement.setDate(5,new Date(new java.util.Date().getTime()));//给第五个占位符?的值赋值为new Date(new java.util.Date().getTime())
//5.执行sql
int i = preparedStatement.executeUpdate();
if(i>0){
System.out.println("插入成功");
}
preparedStatement.close();
connection.close();
}
}
junit单元测试
依赖:
<!-- 单元测试-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
简答使用
@Test注解只有在方法上有效,只要加了这个注解的方法,就可以直接使用
@Test
public void test(){
System.out.println("hello");
}
事务:
package com.jf.test;
import org.junit.Test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class TestJdbc3 {
@Test
public void test(){
//解决中文乱码useUnicode=true&characterEncoding=utf-8
String url = "jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=utf-8&useSSL=true";
String username = "root";
String password = "123456";
Connection connection = null;
//1.加载驱动
try {
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();
//4.制作错误
//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("提交成功");
} catch (Exception e) {
try {
//如果出现异常,就通知数据库回滚事务
connection.rollback();
} catch (SQLException e1) {
e1.printStackTrace();
}
e.printStackTrace();
}finally {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
13.邮件发送
import com.sun.mail.util.MailSSLSocketFactory;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.security.GeneralSecurityException;
import java.util.Properties;
public class Test {
//简单邮件:没有附件和图片,纯文本邮件
//复杂邮件:有附件和图片
//要发送邮件,需要获得协议和支持,开启服务POP3/STMP
//jlljptqkgezoihic
public static void main(String[] args) throws Exception {
Properties prop = new Properties();
prop.setProperty("mail.host","smtp.qq.com");
prop.setProperty("mail.transport.protocol","smtp");
prop.setProperty("mail.smtp.auth","true");//验证用户密码
MailSSLSocketFactory sf =new MailSSLSocketFactory();
sf.setTrustAllHosts(true);
prop.put("mail.smtp.ssl.enable","true");
prop.put("mail.smtp.ssl.socketFactory",sf);
//使用JavaMial发送邮件的5个步骤
//1.创建定义整个应用程序所需的环境信息的Session对象
Session session = Session.getDefaultInstance(prop, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("[email protected] ", "jlljptqkgezoihic");
}
});
session.setDebug(true);
//2.通过session获得transport对象
Transport ts = session.getTransport();
//3.使用邮箱的用户名和授权码连上邮件服务器
ts.connect("smtp.qq.com","[email protected]","jlljptqkgezoihic");
//4.创建邮件
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress("[email protected]"));//发件人
message.setRecipient(Message.RecipientType.TO,new InternetAddress("[email protected]"));//收件人
message.setSubject("HELLO");
message.setContent("<h1 style='color:red'>你好</h1>","text/html;charset=UTF-8");
//5.发送邮件
ts.sendMessage(message,message.getAllRecipients());
//6.关闭链接
ts.close();
}
}
标签:HttpServletRequest,JavaWeb,resp,req,import,servlet,javax
From: https://www.cnblogs.com/huangjiangfei/p/18397073