web开发:
web应用程序:可以提供浏览器访问的程序;
web应用程序编写完成后,若想提供给外界访问:需要一个服务器来统一管理;
页面会动态展示:"web的页面效果因人而异"
ASP
微软:国内最早流行的就是ASP;
在HTML中嵌入了VB的脚本,ASP + COM;
在ASP开发中,基本上一个页面都有几千行的业务代码,页面极其紊乱
C#
IIS
<h1>
<h1><h1>
<h1><h1>
<h1>
<%
sout("hello")
%>
<h1>
<h1><h1>
<h1><h1>
<h1>
PHP
JSP/Sevlet
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最新版本为10.0.0-M4。
下载tomcat:
1、安装or解压
2、了解配置文件及目录结构
3、这个东西的作用
http(超文本传输协议)是一个简单的请求-响应协议,它通常运行在TCP之上。
https:安全的
Request URL: https://www.baidu.com/ 请求地址
Request Method: GET get方法/post方法
Status Code: 200 OK 状态码
Remote Address: 36.152.44.96:443
Referrer Policy: unsafe-url
Accept: text/html
Accept-Encoding: gzip, deflate, br
Accept-Language: zh-CN,zh;q=0.9 语言
Connection: keep-alive
1、请求行
2、消息头
Accept:告诉浏览器,它所支持的数据类型
Accept-Encoding:支持哪种编码格式,GBK UTF-8, GB2312 ISO8859-1
Accept-Language:告诉浏览器,它的语言环境
Cache-Control:缓存控制
Connection:告诉浏览器,请求完成是断开还是保持连接
Host:主机
服务器--响应(Response) -- 客户端
百度:
Cache-Control: private 缓存控制
Connection: keep-alive 连接:
Content-Encoding: gzip 编码
Content-Type: text/html;charset=utf-8 类型
1.响应体
Accept:告诉浏览器,它所支持的数据类型
Accept-Encoding:支持哪种编码格式,GBK UTF-8, GB2312 ISO8859-1
Accept-Language:告诉浏览器,它的语言环境
Cache-Control:缓存控制
Connection:告诉浏览器,请求完成是断开还是保持连接
Host:主机
Reflush:告诉客户端多久刷新一次
Location:让网页重新定位;
2.响应状态码
200:请求响应成功
3xx:请求重定向
404:找不到资源
500:服务器代码错误
502:网关错误
常见面试题:
当你的浏览器中地址栏输入地址并回车的一瞬间到网页能够展示回来,经历了什么?
以下查询后得到一个经典的文章--->点我查看:)
DNS查找过程为:
浏览器缓存->系统缓存->路由器缓存->ISP DNS缓存->递归搜索
递归搜索过程为:从根域名服务器到顶级域名服务器到你查询的域名服务器。
我为什么要学习这个技术?
1.在javaweb开发中,需要使用大量的jar包,我们手动去导入;
2.如何能够让一个东西自动帮我导入和配置这个jar包.
? 由此,Maven诞生了。
我们目前用来就是方便导入jar包的!
Maven的核心思想:约定大于配置
Maven会规定好你该如何去编写我们的java代码,必须要按照这个规范来!
下载完成后解压即可;
在我们的系统环境变量中
配置 如下配置:
测试Maven是否安装成功,保证必须配置完成!
<mirror>
<id>nexus-aliyun</id>
<mirrorOf>*,!jeecg,!jeecg-snapshots</mirrorOf>
<name>Nexus aliyun</name>
<url>http://maven.aliyun.com/nexus/content/groups/public</url>
</mirror>
在本地的仓库,远程仓库;
建立一个本地仓库:localRepository
<localRepository>
D:\javafile\javaconfig\apache-maven-3.6.1\maven-repo
</localRepository> //要根据电脑的路径自己设置!
1.启动IDEA
2.创建一个Mavenweb项目
4.观察maven仓库中多了什么东西?
5.IDEA中的MAVEN设置
注意:IDEA项目创建成功后,看一眼Maven的配置
这个只有在web应用下才有!
解决警告问题
必须要的配置:为什么会有这个问题:我们访问一个网站,需要指定一个文件夹名字;
<?xml version="1.0" encoding="UTF-8"?>
<!--Maven的版本和头文件-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<!--这里就是我们刚才配置的GAV-->
<groupId>com.zgrj</groupId>
<artifactId>javaweb-01-maven01</artifactId>
<version>1.0-SNAPSHOT</version>
<!--Package:项目的打包方式
jar:Java应用
war:JavaWeb应用
-->
<packaging>war</packaging>
<!--配置-->
<properties>
<!--项目的默认构建编码-->
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<!--编码版本-->
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
</properties>
<!--项目依赖-->
<dependencies>
<!--具体依赖的jar包配置文件-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
</dependencies>
<!--项目构建用的东西-->
<build>
<finalName>javaweb-01-maven01</finalName>
<pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
<plugins>
<plugin>
<artifactId>maven-clean-plugin</artifactId>
<version>3.1.0</version>
</plugin>
<!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>3.0.2</version>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.1</version>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.2</version>
</plugin>
<plugin>
<artifactId>maven-install-plugin</artifactId>
<version>2.5.2</version>
</plugin>
<plugin>
<artifactId>maven-deploy-plugin</artifactId>
<version>2.8.2</version>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>
maven由于他的约定大于配置,我们之后可能遇到我们写的配置文件,无法被导出或者生效的问题,解决方案:
<!--在bulid中配置resources,来防止我们资源导出失败的问题-->
<build>
.......
<resources>
<resource>
<directory>src/main/resources</directory>
<excludes>
<exclude>**/*.properties</exclude>
<exclude>**/*.xml</exclude>
</excludes>
<filtering>false</filtering>
</resource>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
......
</build>
把实现了Servlet接口的java程序叫做:Servlet
Servlet接口Sun公司有两个默认的实现类:HttpServlet,GenericServlet
1.构建一个普通的Maven项目,删掉里面的src目录,以后我们的学习就在这个项目里面建立Moudle;这个空的工程就是Maven的主工程;
2.关于Maven父子工程的理解;
父项目中会有
<modules>
<module>servlet-01</module>
</modules>
子项目中会有
<parent>
<artifactId>javaweb-02-servlet</artifactId>
<groupId>com.zgrj</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
父项目中的jar包子项目可以直接使用
son extends father
? 1.修改web.xml为最新的
? 2.将maven的结构搭建完整
? 1.编写一个普通类
? 2.实现Servlet接口,这里我们直接继承HttpServlet
public class HelloServlet extends HttpServlet {
//由于get或者post只是请求实现的不同的方式,可以相互调用,业务逻辑都一样;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// ServletOutputStream out= resp.getOutputStream();
resp.setContentType("text/html;charset=utf-8");
PrintWriter out = resp.getWriter(); //响应流
out.print("你好,张三!");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doPost(req, resp);
doGet(req,resp);
}
}
图解:
5.编写Servlet的映射
为什么需要映射:我们写的是java程序,但是要通过浏览器访问,而浏览器需要连接web服务器;
所以我们需要在web服务中注册我们写的Servlet,还需要给它一个浏览器能够访问的路径;
<!--注册Servlet-->
<servlet>
<servlet-name>hello</servlet-name>
<servlet-class>com.zgrj.servlet.HelloServlet</servlet-class>
</servlet>
<!--Servlet的请求路径-->
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
注意:配置项目发布的路径就可以了
Servlet是由web服务器调用,web服务器在收到浏览器请求之后,会:
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/hello1</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>/hello/*</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
<!--可以自定义后缀实现请求
注意点,*前面不能加项目映射的路径
hello/asdasds.qinjiang-->
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
<!--自定义error :404页面-->
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>error</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
web容器在启动的时候,它会为每个web程序都创建一个对应的ServletContext对象,它代表了当前的web应用;
我在这个Servlet中保存的数据,可以在另外一个servlet中拿到;
public class HelloServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//this.getInitParameter(); //初始化参数
// this.getServletConfig(); //Servlet的配置
ServletContext context = this.getServletContext();//Servlet上下文
String name = "张三"; //数据
context.setAttribute("name",name); //将一个数据保存在ServletContext中,名字为:name,值:name
System.out.println("你长得真好看!");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req,resp);
}
}
public class GetServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext context = this.getServletContext();
String name = (String) context.getAttribute("name");
resp.setContentType("text/html;charset=utf-8");
PrintWriter writer = resp.getWriter();
writer.print("<h1>"+ name + "</h1>");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req,resp);
}
}
<servlet>
<servlet-name>hello</servlet-name>
<servlet-class>com.zgrj.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.zgrj.servlet.GetServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>getC</servlet-name>
<url-pattern>/getC</url-pattern>
</servlet-mapping>
<!--配置一些web应用初始化参数-->
<context-param>
<param-name>url</param-name>
<param-value>jdbc:mysql://localhost:3306/mybatis</param-value>
</context-param>
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext context = this.getServletContext();
String url = context.getInitParameter("url");
resp.getWriter().print(url);
}
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext context = this.getServletContext();
context.getRequestDispatcher("/gp").forward(req,resp); //调用forward实现请求转发
// context.getRequestDispatcher() //转发的请求路径
System.out.println("进入了Demo04");
}
图解:
web服务器接收到客户端的http请求,针对这个请求,分别创建一个代表请求的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_CONTINUE = 100;
int SC_SWITCHING_PROTOCOLS = 101;
int SC_OK = 200; //常见
int SC_CREATED = 201;
int SC_ACCEPTED = 202;
int SC_NON_AUTHORITATIVE_INFORMATION = 203;
int SC_NO_CONTENT = 204;
int SC_RESET_CONTENT = 205;
int SC_PARTIAL_CONTENT = 206;
int SC_MULTIPLE_CHOICES = 300;
int SC_MOVED_PERMANENTLY = 301;
int SC_MOVED_TEMPORARILY = 302;
int SC_FOUND = 302;
int SC_SEE_OTHER = 303; //常见
int SC_NOT_MODIFIED = 304; //常见
int SC_USE_PROXY = 305;
int SC_TEMPORARY_REDIRECT = 307;
int SC_BAD_REQUEST = 400;
int SC_UNAUTHORIZED = 401;
int SC_PAYMENT_REQUIRED = 402;
int SC_FORBIDDEN = 403;
int SC_NOT_FOUND = 404; //常见
int SC_METHOD_NOT_ALLOWED = 405;
int SC_NOT_ACCEPTABLE = 406;
int SC_PROXY_AUTHENTICATION_REQUIRED = 407;
int SC_REQUEST_TIMEOUT = 408;
int SC_CONFLICT = 409;
int SC_GONE = 410;
int SC_LENGTH_REQUIRED = 411;
int SC_PRECONDITION_FAILED = 412;
int SC_REQUEST_ENTITY_TOO_LARGE = 413;
int SC_REQUEST_URI_TOO_LONG = 414;
int SC_UNSUPPORTED_MEDIA_TYPE = 415;
int SC_REQUESTED_RANGE_NOT_SATISFIABLE = 416;
int SC_EXPECTATION_FAILED = 417;
int SC_INTERNAL_SERVER_ERROR = 500; //常见
int SC_NOT_IMPLEMENTED = 501;
int SC_BAD_GATEWAY = 502;
int SC_SERVICE_UNAVAILABLE = 503;
int SC_GATEWAY_TIMEOUT = 504;
int SC_HTTP_VERSION_NOT_SUPPORTED = 505;
1.向浏览器输出消息
2.下载文件
1.要获取下载文件的路径
2.下载的文件名是什么?
3.设置想办法让浏览器能够支持下载我们的需要的东西
4.获取下载文件的输入流
5.创建缓冲区
6.获得OutputStream对象
7.将FileOutputStream流写入到buffer缓冲区
8.使用OutputStream将缓冲区中的数据输出到客户端!
例:
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 1.要获取下载文件的路径
//D:\MyNewWorld\New_Java\JavaWeb\javaweb-02-servlet\response\src\main\resources\cfy.jpg
String realPath = "D:\\MyNewWorld\\New_Java\\JavaWeb\\javaweb-02-servlet\\response\\src\\main\\resources\\cfy.jpg";
System.out.println("要下载的文件路径:" + realPath);
// 2.下载的文件名是什么?
String fileName = realPath.substring(realPath.lastIndexOf("\\") + 1);
// 3.设置想办法让浏览器能够支持下载我们的需要的东西
resp.setHeader("Content-Disposition","attachment;filename=" + fileName);
// 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))!= -1){
out.write(buffer,0,len);
}
in.close();
out.close();
}
验证怎么来的?
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.pink);
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("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;
}
B一个web资源收到客户端A请求后,B它会通知客户端A去访问另外一个web资源C,这个过程叫做重定向
常见场景:
void sendRedirect(String var1) throws IOException;
测试:
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
/*
resp.setHeader("Location","/r/img");
resp.setStatus(302);
*/
resp.sendRedirect("/r/img");
}
面试题:请你聊聊重定向和转发的区别?
相同点
不同点:
测试:
<html>
<body>
<h2>Hello World!</h2>
<%--这里提交的路径,需要寻找到项目的类路径--%>
<%--${pageContext.request.contextPath}代表当前的项目--%>
<form action="${pageContext.request.contextPath}/login" method="get">
用户名:<input type="text" name="username"><br>
密码:<input type="password" name="password"><br>
<input type="submit" value="点击提交">
</form>
</body>
</html>
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("/r/success.jsp");
}
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1>Success</h1>
</body>
</html>
HttpServletRequest代表客户端的请求,用户通过http协议访问服务器,Http请求中的所有信息会被封装到HttpServletRequest;
通过这个HttpServletRequest的方法,获得客户端的所有信息;
获取前端传递的参数,并请求转发
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[] hobbys = req.getParameterValues("hobbys");
System.out.println("-------------------------->");
//后台接收中文乱码问题
System.out.println(username + ":" + password );
System.out.println("爱好:" + Arrays.toString(hobbys));
System.out.println("-------------------------->");
//这里的 /代表当前的web应用
req.getRequestDispatcher("/success.jsp").forward(req,resp);
}
会话:用户打开了浏览器,点击了很多超链接,访问了多个web资源,关闭浏览器,这个过程可以称之为会话
cookie就是饼干!很好理解的,就是你第一次访问我我会拦住你,然后我分给你一块饼干,当你有了
这个饼干就相当于有了一个令牌,以后访问不会拦截你
有状态会话:某个人来过这个房间,下次再来,我们就会知道这个人曾经来过,称之为有状态的会话;
你怎么证明你是某某学校的学生?
你 某某学校
1.发票 学校给你发票
2.学校登记 学校标记你来过了
那么一个网站,怎么证明你来过?
客户端 服务端
1.服务端给客户端一个信件,客户端下次访问服务端带上信件就可以了;cookie
2.服务器登记你来过了,下次你来的时候我来匹配你;session
cookie
客户端技术(响应,请求)
seesion
服务器技术,利用这个技术,可以保存用户的会话信息;我们可以把信息或数据放在session中;
常见场景:网站登录之后,你下次不用再登录,第二次访问直接就上去了;
Cookie[] cookies = req.getCookies(); //获得Cookie
cookie.getName(); //获得cookie中的key
cookie.getValue(); //获得cookie中的value
new Cookie("lastLoginTime", System.currentTimeMillis() + ""); //新建一个cookie
cookie1.setMaxAge(24*60*60); //设置cookie的有效期
resp.addCookie(cookie1); //响应给客户端一个cookie
一个小栗子:
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//设置编码字符集
req.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=utf-8");
PrintWriter out = resp.getWriter();
//Cookie,服务器端从客户端获取
Cookie[] cookies = req.getCookies(); //这里返回cookie数组,说明Cookie可能存在多个
Cookie cookie = null;
//判断Cookie是否存在
if(cookies != null){
//如果存在怎么办
out.write("您上次的访问时间是:");
for (int i = 0; i <cookies.length ; i++) {
cookie = cookies[i];
//获取cookie的名字
if(cookie.getName().equals("lastLoginTime")){
//获取cookie中的值
long lastLoginTime = Long.parseLong(cookie.getValue());
Date date = new Date(lastLoginTime);
out.write(String.valueOf(date));
}
}
}else{
out.write("您这是第一次访问!");
}
//服务端给客户端响应一个cookie;
Cookie cookie1 = new Cookie("lastLoginTime", System.currentTimeMillis() + "");
//cookie有效期为1天
cookie1.setMaxAge(24*60*60);
resp.addCookie(cookie1);
一个网站cookie是否存在上限!
删除Cookie
编码解码:
URLEncoder.encode("张三","utf-8");
URLDecoder.decode(cookie.getvalue(),"utf-8");
什么session:
Session和Cookie的区别:
使用场景:
使用Session
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//解决乱码问题
resp.setContentType("text/html;charset=utf-8");
//得到session
HttpSession session = req.getSession();
//给session中存东西
session.setAttribute("name","张三");
//获取Session的ID
String id = session.getId();
//判断Session是不是新创建的
if(session.isNew()){
resp.getWriter().write("Session创建成功,ID为:" + id);
}else{
resp.getWriter().write("Session在服务器中已经存在了,ID为:" + id);
}
}
拿到Session
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//解决乱码问题
resp.setContentType("text/html;charset=utf-8");
//得到session
HttpSession session = req.getSession();
User user = (User)session.getAttribute("name");
System.out.println(user.toString());
}
手动注销Session
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
HttpSession session = req.getSession();
session.removeAttribute("name");
//手动注销Session
session.invalidate();
}
会话自动过期:web.xml配置
<!--设置Session默认的失效时间-->
<session-config>
<!--设置15分钟后Session自动失效,以分钟为单位-->
<session-timeout>15</session-timeout>
</session-config>
Java Server Pages:Java服务器端页面,也和Servlet一样,用于动态web技术?
最大的特点:
JSP是怎么执行的呢?
代码层面没有任何问题
服务器内部工作
Tomcat中有一个work目录;
IDEA中使用Tomcat的会在IDEA的Tomcat中产生一个work目录
我电脑的地址:
C:\Users\99561.IntelliJIdea2018.3\system\tomcat\Unnamed_javaweb-session-cookie\work\Catalina\localhost\s\org\apache\jspf
发现页面转变成了Java程序
浏览器向服务器发送请求,不管访问什么资源,其实都是在访问Servlet!
JSP最终也会被转换为一个Java类!
JSP本质上就是一个Servlet
//初始化
public void _jspInit() {
}
//销毁
public void _jspDestroy() {
}
//JSPService
public void _jspService(HttpServletRequest request,HttpServletResponse response)
1.判断请求
2.内置了一些对象
final javax.servlet.jsp.PageContext pageContext; //页面上下文
javax.servlet.http.HttpSession session = null; //session
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:当前页
HttpServletRequest request //请求
HttpServletResponse response //响应
response.setContentType("text/html"); //设置响应的页面类型
pageContext = _jspxFactory.getPageContext(this, request, response,
null, true, 8192, true);
_jspx_page_context = pageContext;
application = pageContext.getServletContext();
config = pageContext.getServletConfig();
session = pageContext.getSession();
out = pageContext.getOut();
_jspx_out = out;
在JSP页面中;
只要是Java代码就会原封不动的输出;
如果是HTML代码,就会被转换为:
out.write("\r\n");
这样的格式,输出到前端;
任何语言都有自己的语法,Java中有,JSP作为Java技术的一种应用,它拥有一些自己扩充的语法(了解即可)
Java所有 语法都支持!
<%--JSP表达式
作用:用来将程序的输出,输出到客户端
<%= 变量或者表达式%>
--%>
<%= new java.util.Date()%>
jsp脚本片段
<%--jsp脚本片段--%>
<%
int sum = 0 ;
for (int i = 0; i <= 100 ; i++) {
sum+=i;
}
out.println("<h1>Sum=" + sum + "</h1>");
%>
脚本片段的在实现
<%
int x = 10;
out.println(x);
%>
<p>这是一个jsp文档</p>
<%
int y = 20;
out.print(y);
%>
<hr>
<%--在代码中嵌入HTML元素--%>
<%
for (int i = 0; i < 5 ; i++) {
%>
<h3 style="color: orange">hello,world<%=i%></h3>
<%
}
%>
JSP声明
<%!
static {
System.out.println("Loading Servlet!");
}
private int globalVar = 0;
public void go(){
System.out.println("进入了方法go!");
}
%>
jsp声明:会被编译到JSP生成的Java的类中!其他的就会被生成到_jspService方法中!
在JSP,嵌入Java代码即可
<%%>
<%=%>
<%!%>
<%--注释--%>
jsp的注释,不会在客户端显示,HTML就会!
例:自定义500/404跳转页面
<%@page arg... %>
主页面:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<%
int i = 1/0; //这里肯定报错
%>
</body>
</html>
500:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>我的500页面</title>
</head>
<body>
<img src="${pageContext.request.contextPath}/img/500.jpg" alt="500错误页面"> //我只是简单的给了一张500的错误页面的图片
</body>
</html>
404:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>404</title>
</head>
<body>
<img src="${pageContext.request.contextPath}/img/404.jpg" alt="404资源找不到页面"> //插入了一张图片用来显示404错误
</body>
</html>
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">
<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>
</web-app>
例:
<%@ 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/footdr.jsp"%>
<hr>
<%--JSP标签
jsp:include:拼接页面,本质还是三个 //推荐
--%>
<jsp:include page="common/header.jsp"/>
<h1>网页主体</h1>
<jsp:include page="common/footdr.jsp"/>
</body>
</html>
@include file底层:
jsp:include page底层:
pageContext.setAttribute("name1","张三"); //保存的数据只在一个页面中有效
request.setAttribute("name2","李四"); //保存的数据只在一次请求中有效,请求转发会携带这个数据
session.setAttribute("name3","王五"); //保存的数据只在一次会话中有效,从打开浏览器到关闭浏览器
application.setAttribute("name4","赵六"); //保存的数据只在服务器中有效,从打开服务器到关闭服务器
request:客户端向服务器发送请求,产生的数据,用户看完就没用了,例:新闻,用户看完就看完了
session:客户端向服务器发送请求,产生的数据,用户用完一会可能还有用,比如:购物车
application:客户端向服务器发送请求,产生的数据,某个用户用完了,其他的用户可能还会使用,例:聊天数据
maven依赖:
<!--JSTL表达式的依赖-->
<!-- https://mvnrepository.com/artifact/javax.servlet.jsp.jstl/jstl-api -->
<dependency>
<groupId>javax.servlet.jsp.jstl</groupId>
<artifactId>jstl-api</artifactId>
<version>1.2</version>
</dependency>
<!--standard标签库-->
<!-- https://mvnrepository.com/artifact/taglibs/standard -->
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
EL表达式:${ }
JSP标签
<%--<jsp:include page="/..."></jsp:include>--%>
<h2>页面一</h2>
<jsp:forward page="/jsptag2.jsp">
<jsp:param name="name" value="Lucy"></jsp:param>
<jsp:param name="age" value="21"></jsp:param>
</jsp:forward>
JSTL表达式
JSTL标签库的使用就是为了弥补HTML标签的不足;它自定义许多标签,可以供我们使用,标签的功能和java代码一样;
格式化标签
SQL标签
XML标签
核心标签(掌握部分)
JSTL标签库使用步骤
<%--引入JSTL核心标签库,我们才能使用JSTL标签 core:核心--%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
使用其中的方法
可能会出现的问题:在Tomcat也需要引入JSTL的jar包,不然可能会报错:JSTL解析错误
c: if例:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%--引入JSTL核心标签库,我们才能使用JSTL标签 core:核心--%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h4>if测试</h4>
<hr>
<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="欢迎管理员${param.username}"/>
</c:if> <br>
<%--自闭合标签--%>
<c:out value="${isAdmin}"/>
</body>
</html>
测试页面:
c:choose例:
<%--定义一个变量score,值为85--%>
<c:set var="score" value="77"/>
<c:choose>
<c:when test="${score>=90}">
成绩优秀
</c:when>
<c:when test="${score>=80}">
成绩良好
</c:when>
<c:when test="${score>=70}">
成绩一般
</c:when>
<c:when test="${score>=60}">
成绩还行
</c:when>
</c:choose>
测试结果:
foreach例:
<html>
<head>
<title>Title</title>
</head>
<body>
<%
ArrayList<String> student = new ArrayList<>();
student.add(0,"张三");
student.add(1,"李四");
student.add(2,"王五");
student.add(3,"赵六");
student.add(4,"郑七");
request.setAttribute("list",student);
%>
<%--
var :每次要遍历出来的变量
items:要遍历的对象
begin: 从哪里开始
end: 到哪里结束
step: 步长
--%>
<c:forEach var="stu" items="${list}">
<c:out value="${stu}"/> <br>
</c:forEach>
<hr>
<c:forEach var="stu" items="${list}" begin="1" end="3" step="2">
<c:out value="${stu}"/> <br>
</c:forEach>
</body>
</html>
测试结果:
实体类
JavaBean有特定的写法:
一般用来与数据库的字段做映射 ORM;
ORM:对象关系映射
people表
id | name | age | address |
---|---|---|---|
1 | 张三 | 15 | 新乡 |
2 | 李四 | 16 | 洛阳 |
3 | 王五 | 17 | 孟津 |
class people{
private int id;
private String name;
private int age;
private String address;
}
class A{
new people(1,"张三",15,"新乡");
}
原文:https://www.cnblogs.com/CHENFANgY/p/12915157.html