web开发:
在Java中,动态web资源开发的技术称为javaweb
可以提供浏览器访问的程序
web程序编写后:向提供外界访问:需要一个服务器管理
*.html, *.htm这些都是网页的后缀,如果一直存在,我们就可以直接读取 。
页面会动态展示:“页面随着时间和不同人发生变化”
缺点:加入服务器web资源出现错误,需要编写后台程序,重新发布。
优点:可以动态更新,可以与数据库交互(数据持久化)
ASP
PHP:开发速度快,跨平台,代码简单,无法承载大的访问量的情况下(局限性)
JSP/Servlet:
服务器是一种被动操作,用来处理用的一些请求和给户用一下响应信息。
开启,关闭tomcat
可以与配置启动的端口号:
Tomcat:8080
http:80
mysql:3306
https:443
可以配置主机的名称:
<Host name="localhost" appBase="webapps"
unpackWARs="true" autoDeploy="true">
面试题:谈一谈网站是如何访问?
配置环境变量
发布一个简单的web网站:
将自己的html放在Tomcat中可以访问
--webapps : Tomcaat服务器的web目录
-ROOT
-自己的网站:
-WEB-INF
-classes:java程序
-lib:web应用的jar包
-web.xml :网站的配置文件
-index.html默认的首页
-static
-css
-style.css
-js
-img
-........
http(超文本传输协议)
HTTPS:安全
443
http1.0
http2.0
HTTP请求:
客服端---->发请求—>服务器
Request URL: https://www.baidu.com/请求地址
Request Method: GET方法/Host
Status Code: 200 OK 状态码:200
Remote(远程) Address: [2408:80f0:410c:1c:0:ff:b00e:347f]:443
Referrer Policy: no-referrer-when-downgrade
Accept: text/htmlapplication/signed-exchange;v=b3
Accept-Encoding: gzip, deflate, br
Accept-Language: zh-CN,zh;q=0.9 //语言
Connection: keep-alive
Cookie: PSTM=1507441409; BIDUPSID=46EC5BF0344AA3B8C6C5BB0B647015CE; BAIDUID=B87B4FDA728C929353D6AC747E4197FC:FG=1; BD_UPN=12314353; BDORZ=FFFB88E999055A3F8A630C64834BD6D0; ispeed_lsm=0; __guid=136081015.4001874688588183600.1592444487195.8638; BDRCVFR[psZeE7xbzjm]=mk3SLVN4HKm; BD_HOME=1; H_PS_PSSID=; monitor_count=4; BDSVRTM=16
Host: www.baidu.com
Sec-Fetch-Mode: navigate
Sec-Fetch-Site: none
Sec-Fetch-User: ?1
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36
1.请求行:
方式:GET、host。head,put
2.消息头:
Accept:支持的数据类型
Accept-Encoding:支持哪种编码格式 GBK,utf-8,GB2312,iso
Accept-Language: //语言环境cache-control :缓存控制
Connection: 请求完成后是断开回还是保持连接
HOST:主机
HTTP响应
服务器—>响应---->客户端
响应体:
Accept:支持的数据类型
Accept-Encoding:支持哪种编码格式 GBK,utf-8,GB2312,iso
Accept-Language: //语言环境
cache-control :缓存控制
Connection: 请求完成后是断开回还是保持连接
HOST:主机
refrush:告诉客户端刷新
location:让网页重新定位
响应状态码:
-5xx:服务器代码错误
面试题:当浏览器地址栏输入地址并回车的一瞬间到页面展示回来,经历了什么?
在javaweb开发中,需要大量的jar中,需要手动导入
maven:诞生
方便导入jar包
核心思想:约定大于配置
maven:规定何如编写我们的java代码
安装配置maven和tomcat包
会出现的问题:
为什么会警告?
访问一个网站必须有一个需要指定的文件夹的名字:
webapp- maven-war:虚拟路径映射
pom.xml是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.0modelVersion>
<groupId>com-zhanggroupId>
<artifactId>javaweb-01-mavenartifactId>
<version>1.0-SNAPSHOTversion>
<packaging>warpackaging>
<name>javaweb-01-maven Maven Webappname>
<url>http://www.example.comurl>
<properties>
<project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
<maven.compiler.source>1.7maven.compiler.source>
<maven.compiler.target>1.7maven.compiler.target>
properties>
<dependencies>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>4.11version>
<scope>testscope>
dependency>
dependencies>
<build>
<finalName>javaweb-01-mavenfinalName>
<pluginManagement>
<plugins>
<plugin>
<artifactId>maven-clean-pluginartifactId>
<version>3.1.0version>
plugin>
<plugin>
<artifactId>maven-resources-pluginartifactId>
<version>3.0.2version>
plugin>
<plugin>
<artifactId>maven-compiler-pluginartifactId>
<version>3.8.0version>
plugin>
<plugin>
<artifactId>maven-surefire-pluginartifactId>
<version>2.22.1version>
plugin>
<plugin>
<artifactId>maven-war-pluginartifactId>
<version>3.2.2version>
plugin>
<plugin>
<artifactId>maven-install-pluginartifactId>
<version>2.5.2version>
plugin>
<plugin>
<artifactId>maven-deploy-pluginartifactId>
<version>2.8.2version>
plugin>
plugins>
pluginManagement>
build>
project>
maven高级指出是可以导入jar依赖的其他jar包:
由于maven约定大于配置,之后可能自己的配置文件用不了,可以在build中解决
maven仓库的使用
servlet是 sun公司开发动态web的一门技术
sun提供了接口:servlet
servlet接口有两个默认的实现:HttpServlet,genericServlet
1.构建maven项目,删掉里面的src目录,在这个项目建立module:空工程是maven的主工程
关于maven父子的:
在父项目中可以有很多子项目:
父项目中的jar包,子项目可以直接使用
son extends father
maven 项目优化:
编写一个servlet程序
编写一个普通类
package com.zhang.servlet;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletOutputStream;
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 helloservlet extends HttpServlet {
//get,host只是实现请求的方式不同,所以可以相互调用,业务逻辑一样
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// ServletInputStream is = req.getInputStream();
PrintWriter out = resp.getWriter();//响应流
ServletOutputStream os = resp.getOutputStream();
out.print("helloyyyy");
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
}
实现servlet接口,或者直接继承HttpServlet类
servlet ------》genericServlet—》HttpServlet—》自己的代码
编写servlet的映射
我们写的是java程序,但是要通过浏览器访问,而浏览器需要连接web服务器,所以我们需要在web服务器中注册我们写的servlet。还要一个浏览器能够访问的路径。
<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>hiservlet-name>
<servlet-class>com.zhang.servlet.helloservletservlet-class>
servlet>
<servlet-mapping>
<servlet-name>hiservlet-name>
<url-pattern>/jjurl-pattern>
servlet-mapping>
web-app>
6.开启tomcat
7 测试
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Ttrj8TRx-1592883308714)(C:\Users\Administrator\Documents\Tencent Files\924608198\FileRecv\MobileFile\1592549382317.jpg)]
6.4mapping:
一个servlet可以指定一个映射路径
<servlet-mapping>
<servlet-name>hiservlet-name>
<url-pattern>/hiiurl-pattern>
servlet-mapping>
web-app>
一个servlet可以指定一个映射路径
<servlet-mapping>
<servlet-name>hiservlet-name>
<url-pattern>/hii1url-pattern>
servlet-mapping><servlet-mapping>
<servlet-name>hiservlet-name>
<url-pattern>/hii2url-pattern>
servlet-mapping><servlet-mapping>
<servlet-name>hiservlet-name>
<url-pattern>/hii3url-pattern>
servlet-mapping>
3.一个servlet可以指定一个通用映射路径(*)
<servlet-mapping>
<servlet-name>hiservlet-name>
<url-pattern>/hi/*url-pattern>
servlet-mapping><servlet-mapping>
//特例“
4.优先级映射:
制定了固有的路径优先级最高,找不到找到默认的处理请求。
web 容器在启动的时候,会为每个web程序都创建一个servletContext对象,
共享数据
在这个servlet中保存的数据,在另外一个servlet中拿到,get和set方法
public class helloservlet extends HttpServlet {
//get,host只是实现请求的方式不同,所以可以相互调用,业务逻辑一样
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// ServletInputStream is = req.getInputStream();
System.out.println("hhh");
PrintWriter out = resp.getWriter();//响应流
// ServletOutputStream os = resp.getOutputStream();
out.print("helloyyyy");
ServletContext context = this.getServletContext();
String str = "halo";
context.setAttribute("str",str);
}
public class get extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext context = this.getServletContext();
String str = (String)context.getAttribute("str");
resp.setContentType("text/html");
resp.setCharacterEncoding("utf-8");
}
}
<servlet>
<servlet-name>hiservlet-name>
<servlet-class>com.zhang.servlet.helloservletservlet-class>
servlet>
<servlet-mapping>
<servlet-name>hiservlet-name>
<url-pattern>/hiurl-pattern>
servlet-mapping>
<servlet>
<servlet-name>hiiservlet-name>
<servlet-class>com.zhang.servlet.getservlet-class>
servlet>
<servlet-mapping>
<servlet-name>hiiservlet-name>
<url-pattern>/hiiiiurl-pattern>
servlet-mapping>
ServletContext context = this.getServletContext();
String url = context.getInitParameter("url");
resp.getWriter().println(url);
<context-param>
<param-name>urlparam-name>
<param-value>jdbc:mysql://localhost::33006/mybatisparam-value>
context-param>
<servlet>
<servlet-name>oooservlet-name>
<servlet-class>com.zhang.servlet.demoservlet-class>
servlet>
<servlet-mapping>
<servlet-name>oooservlet-name>
<url-pattern>ooourl-pattern>
servlet-mapping>
<servlet>
<servlet-name>hiservlet-name>
<servlet-class>com.zhang.servlet.helloservletservlet-class>
servlet>
public class demo1 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext context = this.getServletContext();
// RequestDispatcher requestDispatcher = context.getRequestDispatcher(s);
//转发其他的servlet,但自己的servlet路径不变
context.getRequestDispatcher("/ooo").forward(req,resp);
}
}
Properties
在web中,新建的配置文件Properties和写的java文件都打包到ClassPAth路径
用servletcontext,读取配置文件
:需要一个文件流
public class readProperties extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
InputStream is = this.getServletContext().getResourceAsStream("/WEB-INF/classes/db.properties");
Properties properties = new Properties();
properties.load(is);
String s = properties.getProperty("username");
resp.getWriter().print("s");
}
}
代表客户端的请求:用户通过HTTP协议访问服务器,请求中的全部信息汇封装到HttpServletRequest,通过HttpServletRequest方法,获得客户端的信息。
1、获取前端的传递参数请求转发
public class request 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("hobby");
System.out.println("=========================");
System.out.println(password);
System.out.println(username);
System.out.println(Arrays.toString(hobbies));
//通过请求转发
req.getRequestDispatcher("/succe.jsp").forward(req,resp);
//resp.sendRedirect();
}
}
重定向和转发的区别:
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-QvkXGtaf-1592883308724)(C:\Users\Administrator\AppData\Roaming\Typora\typora-user-images\image-20200622091649050.png)]
web 服务器接收到客户端的http的请求,针对这个请求,分别创建一个代表请求的HttpServletRequest和代表响应的 8HttpServletResponse:
简单分类:
负责向浏览器发送数据的方法
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.下载文件
public class response extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 获取下载文件的路径
String realPath = this.getServletContext().getRealPath("真实路径");
// 下载的文件名是啥?
String s = realPath.substring(realPath.lastIndexOf("\\") + 1);
// 设置浏览器消息头允许下载Content-disposition,文件名中有中文,转化编码
resp.setHeader("Content-disposition","attachment;filename="+URLEncoder.encode(s,"utf-8") );
// - 获取下载文件的输出流
FileInputStream in = new FileInputStream(realPath);
// - 创建缓冲流
int len = 0;
byte[] buffer = new byte[1024];
// - 获取OutputStream对象
ServletOutputStream os = resp.getOutputStream();
// - 将FileOutputStream流写入到buffer缓冲区
while((len = in.read(buffer))>0)){
// - 输出缓冲区数据到客户端
os.write(buffer,0,len);
}
in.close();
os.close();
//关闭流
}
}
验证码功能:
前端:js
后端:需要java图片类,生产一个图片
一个web资源收到客户端请求,他会通知客户端去访问另外一个web资源,这个过程叫重定向。:
void sendRedirect(String var1) throws IOException;
实现
resp.sendRedirect("/s1/ooo");跳转到名字为ooo的servlet中,:状态码为302
//
重定向和转发的区别:
会话:用户打开一个浏览接,点击很多超链接,访问多个web资源,关闭浏览器,为会话
cookie :客户端技术(响应,请求)
session:服务器技术,
常见:网站初次访问之后,下次不用登陆
1.从请求中拿到cookie信息
2.服务器响应给客户端cookie
//保存用户上一次保存的时间
public class cookie 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();
//f服务器从客户端获取
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("lastTime")){
//获取cookie中的值,转化为long的时间戳,
long l = Long.parseLong(cookie.getValue());
//把时间戳转化成date对象
Date date = new Date(l);
//date对象转化成String
out.write(date.toLocaleString());
}
}
}else{
out.write("这是您第一次来");
}
//服务器给客户端发cookie
Cookie lastTime = new Cookie("lastTime", System.currentTimeMillis() + "");
//设置有效期
lastTime.setMaxAge(25*69);
resp.addCookie(lastTime);
}
}
cookie:一般会保存在本地的用户目录下appdata
一个网站cookie是否存在上限:
一个cookie只能保存一个信息
一个web查念可以给浏览器多个cookie:浏览器上限300,每个web站点最多存放20个
删除:- 、
session:
服务器会给每一个户用(浏览器)创建一个session对象。
<session-config>
<session-timeout>1session-timeout>
session-config>
public class session extends HttpServlet {
@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存东西,可以跨servlet!!!!!!!!!!!!!!!!!!!!!
session.setAttribute("name","张启鹏");
//得到这个东西
String name = (String) session.getAttribute("name");
//获得session id
String id = session.getId();
//判断session是不是新的
if(session.isNew()){
resp.getWriter().write("session创建成功"+id);
}else{
resp.getWriter().write("session已经存在" +
"");
}
//手动注销sessiion,注销之后会产生一个对象,下面的name代表一个对象
session.removeAttribute("name");
session.invalidate();
//session每次创建
// Cookie cookie = new Cookie("JSESSIONID",id);
// resp.addCookie(cookie);
}
}
Session和cookie区别:
使用场景:-
java serve Page (java服务器页面,用于动态开发)
写jsp和HTML类似:
浏览器访问发送请求,其实都在访问 servlet,转化为一个Java类,jsp本质上就是一个servlet
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-iNdECx0N-1592883308820)(C:\Users\Administrator\Documents\Tencent Files\924608198\FileRecv\MobileFile\1592806605830.jpg)]
在jsp中,只要是java原封不动的输出;
如果是HTML代码,就会转化成:
out.write("<html>\r\n")
这样的格式输出
jsp在java中的语法都支持
jsp表达式:
<%--jsp 表达式,,变量或者表达式
将程序的输出到客户端--
: <%= %>
%>
<%= new java.util.Date() %>
jsp脚本片段
<%
int sum=0;
for(int i = 0; i < 10; i++) {
i++;
out.print(""+i+"
" );
}
%>
JSP声明
<%!
static{
System.out.print("fhshfhs");
}
private int globle =0;
public viod zhang(){
System.out.print("fhshfhs");
}
会被编译到jsp 生成的Java类的类中,其他的jsp脚本片段,jsp表达式,就会生成到_jspService方法中。
会被编译到jsp 生成的Java类的类中,其他的jsp脚本片段,jsp表达式,就会生成到_jspService方法中。
jsp注释不会再客户端识别
404
换error界面
<%@ page arges...%>
<%@ include file = %>
本质是include后面的页面或者语句合二为一
本质是include后面的页面或者语局拼接在一起
存东西
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
Title
<%--四大存数据对象--%>
<%
//作用域越来越久
pageContext.setAttribute("name1","zhang");//指在一个数据中有效
request.setAttribute("name2","zhang2");//保存的数据在一次请求中有效,转发会携带这个请求
session.setAttribute("name3","zhang3");//在一次会话中有效(浏览器)
application.setAttribute("name4","zhang4");//在服务器有效
%>
<%--用get取值--%>
<%
String name1 = (String)pageContext.getAttribute("name1");
String name2 = (String)request.getAttribute("name2");
String name3 = (String)session.getAttribute("name3");
String name4 = (String)application.getAttribute("name4");
%>
<%--使用EL方式输出${} 和 <%=%> --%>
${name1}
${name2}
${name3}
${name4}
<dependency>
<groupId>taglibsgroupId>
<artifactId>standardartifactId>
<version>1.1.2version>
dependency>
<dependency>
<groupId>javax.servletgroupId>
<artifactId>jstlartifactId>
<version>1.2version>
dependency>
EL表达式:${}
jsp标签中的 forword方法
<%--取出参数--%>
名字:<%= request.getParameter("name") %>
jstl标签库的使用就是为了弥补html的不足,自定义很多标签,标签的功能和java功能相同。
核心标签(掌握部分)
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
Title
<%--定义一个变量score,值为5--%>
<%-- EL表达式获取表单中的数据
${param.参数名}
--%>
<%--Var(isAdmin) 是一个boolean值--%>
基础迭代标签,接受多种集合类型:
本身只当做和的父标签
的子标签,用来判断条件是否成立
实体类
有特定的写法:
一般用爱和数据库的字段做映射
ORM:对象关系映射
数据库–java
表—类
字段—属性
行记录—对象
MVC:model view controller(模型视图控制器)
用户直接访问控制层,控制层直接操作数据库
Servlet ---crud(增加(Create)、读取(Retrieve)、更新(Update)和删除(Delete))----数据库代码
弊端:程序拥堵,不利用维护
servlet:处理请求,响应,试图跳转,处理jdbc ,处理业务和逻辑代码
架构:没有是加一层解决不了的
jdbc ---各种数据库
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-RC5CTqcI-1592883308828)(C:\Users\Administrator\Documents\Tencent Files\924608198\FileRecv\MobileFile\1592873977993.jpg)]
model
view:
Controller(servlet)
接受胡勇的请求:(req:请求参数,Session信息)
交给业务层队里对应的代码
控制视图的跳转
登录–接受用户的请求—处理用户的请求(获取用户登陆的参数)–交给业务层处理登录业务(判断用户名密码是否正确:事务)—Dao层查询用户名密码是否正确------查询数据库
用来过滤网站的数据:
使用过程
package com.zhang.filter;
import javax.servlet.*;
;import java.io.IOException;
public class CharcterEncodingFilter implements Filter {
///初始化,web服务器启动则开启
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
//filterChain:
/*
1.过滤器中所有代码,在过滤器特定请求时候被执行
必须让过滤中继续通行。filterChain.doFilter
*/
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
servletRequest.setCharacterEncoding("utf-8");
servletResponse.setCharacterEncoding("utf-8");
servletResponse.setContentType("text/html;charse=tUTF-8");//让我们的请求继续往前走,如不写,则程序被拦截
filterChain.doFilter(servletRequest,servletResponse);
}
//销毁,web服务器关闭则关闭
@Override
public void destroy() {
}
}
package com.zhang.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 ShowServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// resp.setCharacterEncoding("utf-8");
resp.getWriter().write("你好");
}
}
ShowServlet
com.zhang.servlet.ShowServlet
ShowServlet
/show
ShowServlet
/sh/show
fil
com.zhang.filter.CharcterEncodingFilter
fil
/sh/*
实现一个监听器的接口
Hello World!
当前有 <%=this.getServletConfig().getServletContext().getAttribute("OnlineCount")
%>
com.zhang.listen.listen
package com.zhang.listen;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
//统计网站在线人数:统计session
public class listen implements HttpSessionListener {
//创建session监听,一旦创建Session,就会触发一次监听
@Override
public void sessionCreated(HttpSessionEvent se) {
ServletContext context = se.getSession().getServletContext();
Integer onlineCount = (Integer) context.getAttribute("OnlineCount");
if(onlineCount==null){
onlineCount = new Integer(1);
}else
{
int count = onlineCount.intValue();
onlineCount = new Integer(count++);
}
context.setAttribute("OnlineCount",onlineCount);
}
//销毁session,一旦销毁Session,就会触发一次监听
@Override
public void sessionDestroyed(HttpSessionEvent se) {
ServletContext context = se.getSession().getServletContext();
Integer onlineCount = (Integer) context.getAttribute("OnlineCount");
if(onlineCount==null){
onlineCount = new Integer(1);
}else
{
int count = onlineCount.intValue();
onlineCount = new Integer(count--);
}
context.setAttribute("OnlineCount",onlineCount);
}
}
常见应用:
登录: -
用户登路之后,向session中放入用户数据
进入主页之后要判断用户是否已经登录:在过滤中实现
HttpServlet req = (HttpServlet)servletRequest;
HttpServlet resp = (HttpServlet)servletResponse;
if(req.getSession().getAttribute(constant.参数 ==null)){
resp.sendRedirect("/error.jsp");
}
filterChain.doFilter(servletRequest,servletResponse);