javaweb狂神学习篇
javaweb
1、基本概念
1.1、前言
web开发:
- web,网页的意思,www.baidu.com
- 静态web
- html,css
- 提供给所有人看的数据始终不会发生变化
- 动态web
- 淘宝,几乎所有网站
- 提供给所有人看的数据始终会发生变化,每个人在不同时间,不同地点看到的信息不同
- 技术线:servlet/jsp,ASP,PHP
在java中 ,动态web资源开发的技术同城为javaweb;
1.2、web应用程序
web应用程序:可以提供浏览器访问的程序;
- a.html、b.html…多个web资源,这些web资源可以被外界访问,对外界提供服务;
- 访问到的任何页面后者资源,存在于某一个角落
- URL
- 这个同意的web资源会被放在同一个文件夹下,web应用程序–>tomcat:服务器
- 一个web应用由多部份组成(静态web、动态web)
- html、css、js
- jsp、servlet
- Java
- jar
- 配置文件
web应用程序编写完后,若想提供给外界访问:需要一个服务器来统一管理;
1.3、静态web
-
*.htm
和*.html
,这些都是网页的后缀,如果服务器上一直存在这些东西,我们就可以直接进行
-
静态web存在的缺点
- web页面无法动态更新
- 轮播图,点击特效:伪动态
- javascript【实际开发最多】
- VBScript
- 无法和数据库交互(数据持久化,用户无法交互)
- web页面无法动态更新
1.4、动态web
页面动态展示:“web的页面展示的效果因人而异”
缺点
- 加入服务器的动态web资源出现错误,需要重新编写我们的后台程序,重新发布;
- 停机维护
优点:
- 停机维护
- web页面可以动态更新
- 可以和数据库交互
2、web服务器
2.1、技术讲解
ASP
- 微软:国内最早流行的就是ASP;
- 在html中嵌入了VB的脚本,ASP+COM;
- 在ASP开发中,基本一个页面由几千行代码,页面极其混乱
- 维护成本高!
- c#
- IIS
php - php开发速度快,功能很强大,跨平台,代码简单
- 无法承载大访问量的情况下(局限性)
jsp/servlet:
B/S:浏览和服务器
C/S:客户端和服务器端
- sun公司主推B/S架构
- 基于java语言
- 可以承载三高问题的影响
- 语法像ASP,ASP–>JSP,加强市场强度;
2.2、web服务器
服务器是一种被动的操作,用来处理用户的一些亲求和给用户一些响应消息;
IIS
微软的;ASP…Windows
Tomcat
面向百度(搜索)
3、Tomcat
启动、关闭:
可能遇到的问题:
1、Java环境没有配置
2、闪退问题:需要配置兼容性
3、乱码问题:配置文件中设置
3.3、配置
server.xml
可以配置端口号
- tomcat默认:8080
- mysql:3306
- http:80
- https:443
可以配置主机名称
- 默认主机名:localhost–>127.0.0.1
- 默认网站应用存放位置为:webapps
高难度面试题:
请谈谈网站是如何进行访问的!
1.输入一个域名;回车
2.检查本机hots文件是否有
- 有,直接返回对应的ip地址,这个地址有我们需要访问的web程序,可以直接访问
- 没有,去DNS服务器找
3.4、发布一个网站
将自己写的网站,放到服务器指定的webapps下面
--webapps:tomcat服务器的web目录
-root
-myweb:网站目录
- WEB-INF
- classes:Java程序
- lib:web应用所依赖的jar包
- web.xml:网站配置文件
-index.html 默认首页
-static
-css
-styl.css
-js
-img
....
4、http
4.1、http定义
HTTP(超文本传输协议)是一个简单的请求-响应协议,通常运行在TCP之上
- 文本:html、字符串
- 超文本:图片、音乐…
- 80
Https:安全的
- 443
4.2、两个时代
- http1.0
- HTTP/1.0:客户端可以与web服务器连接,只能获得一个web资源 ,断开连接。
- http2.0
- HTTP/1.1:客户端可以与web服务器连接后, 可以获得多个web资源。
4.3、http请求
- 客户端----发请求-----服务器
1、请求行
- 请求行中的请求方式:GET
- 请求方式:Get,Post
- get:请求能够携带的参数较少,大小有限制,会在浏览器的URL地址栏显示数据内容,不安全,但高效
- post:请求能够携带的参数没有限制,大小没有限制,不会在浏览器的URL地址栏显示数据内容,安全,但不高效
2、消息头
Accept:告诉浏览器,他所支持的数据类型
Accept-Encoding:支持那种编码格式 GBK UTF-8 GB2312 ISO8859-1
Accept-Language:告诉浏览器,他的语言环境
Cache-Control:缓存控制
Connection:告诉浏览器,请求完成是断开还是保持连续
HOST:主机…/
4.4、http响应
- 服务器----响应-------客户端
1.响应体
Accept:告诉浏览器,他所支持的数据类型
Accept-Encoding:支持那种编码格式 GBK UTF-8 GB2312 ISO8859-1
Accept-Language:告诉浏览器,他的语言环境
Cache-Control:缓存控制
Connection:告诉浏览器,请求完成是断开还是保持连续
HOST:主机…/
Refresh:告诉客户端,多久刷新一次
Location:让网页重新定位
2、响应状态码(重点)
200:请求响应成功
3xx:请求重定向
- 重定向:你重新到给你的位置
404:找不到资源
5xx:服务器代码错误500 502:网关错误
常见面试题:
当你的浏览器中地址栏输入地址并回车一瞬间能够展示回来,经历了什么?
5、Maven
为什么学maven?
1.再javaweb中需要使用大量的jar包,手动导入
2.如何让一个东西自动导入和配置jar包
由此,Maven诞生!
5.1 Maven项目架构管理工具
方便导入jar包
Maven的核心思想:约定大于配置
- 有约束,不违反
Maven会规定号你该如何去编写java代码,必须按照这个规范来;
5.2 idea创建web须知及常见问题配置
资源导出的时候注意:
<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>
关于tomcat实验环境去原tomcat的web资源下寻找web.xml进行复制
6、Servlet
6.1、servlet简介
- Servlet就是sun公司开发动态web的一门技术
- Sun在这些API中提供一个接口叫做:Servlet,如果你想开发一个Servlet程序,只需完成两个步骤:
- 编写一个类,实现Servlet接口
- 把开发好的Java类部署到Web服务器中
把实现了Servlet接口的Java程序叫做,Servlet
6.2、HelloServlet
1、构建一个普通的Maven项目,删掉里面的src目录,以后我们的学习就在这个项目里面建moudel,这就是maven主工程。
2、关于Maven父子工程的理解:
父项目中会有:
<modules>
<module>servlt-01</module>
</modules>
子项目会有:
<parent>
<artifactId>javaweb-02-servlet</artifactId>
<groupId>com.xv</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
父项目中的java子项目可以直接用父项目的
son extends father
3、Maven环境优化
- 修改web.xml
- 将maven的结构搭建完善
4、编写一个servlet程序
- 编写一个普通类
- 实现servlet接口,继承HttpServlet
5、编写servlet映射
为什么需要映射:我们写的是Java程序,但是要通过浏览器访问,浏览器需要连接web服务器,所以我们需要在web服务中注册我们写的servlet,给它一个浏览器访问的路径。
<!--注册Servlet-->
<servlet>
<servlet-name>hello</servlet-name>
<servlet-class>com.xv.servlet.HelloServlet</servlet-class>
</servlet>
<!--Servlet映射-->
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
6、配置Tomcat
注意:配置项目发布的路径就可以了
7、启动测试
6.3、Servlet原理
Servlet是由web服务器调用,web服务器在收到浏览器请求之后,会:
6.4、mapping问题
1、一个Servlet可以指定一个mapping映射路径
2、一个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>/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>
3、一个Servlet可以指定通用的mapping映射路径
<!--Servlet-->
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/hello/*</url-pattern>
</servlet-mapping>
注意:如果是直接/*会不走index页面建议不要这样写
4、指定后缀和前缀
<!--可以自己自定义后缀实现请求映射
注意点:*前面不能加项目映射的路径例如:
hello/skdhfla.xcg是错的-->
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>*.xcg</url-pattern>
</servlet-mapping>
5、优先级问题
指定了固有映射路径优先级最高,找不到就会走默认请求
6.5、ServletContext
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配置
// this.getServletContext() Servlet上下文
ServletContext context = this.getServletContext();
String username = "徐朝刚";
context.setAttribute("username",username);
System.out.println("hello");
}
}
public class GetServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext servletContext = this.getServletContext();
String username = (String) servletContext.getAttribute("username");
resp.setContentType("text/html");
resp.setCharacterEncoding("utf-8");
PrintWriter writer = resp.getWriter();
writer.print(username);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doPost(req, resp);
}
}
- 获取初始化参数
<!--配置web应用初始化参数-->
<context-param>
<param-name>url</param-name>
<param-value>jdbc:mysql://localhost:3306/mybatis</param-value>
</context-param>
public class ServletDemo03 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext servletContext = this.getServletContext();
String url = servletContext.getInitParameter("url");
PrintWriter writer = resp.getWriter();
writer.print(url);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doPost(req, resp);
}
}
- 请求转发
public class ServletDemo04 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext context = this.getServletContext();
RequestDispatcher requestDispatcher = context.getRequestDispatcher("/gp");//转发的请求路径
requestDispatcher.forward(req,resp);//调用forward实现请求转发
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doPost(req, resp);
}
}
- 读取资源文件
Properties
- 在java目录下新建properties
- 在resources目录下新建properties
注意:依据上文资源导出,配置maven。
发现:都打包到了同一个路径下:classes,我们俗称这个路径为classpath;
思路:需要一个文件流;
public class ServletDemo05 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
InputStream resourceAsStream = this.getServletContext().getResourceAsStream("/WEB-INF/classes/db.properties");
Properties properties = new Properties();
properties.load(resourceAsStream);
String username = properties.getProperty("username");
String password = properties.getProperty("password");
resp.getWriter().print(username+":"+password);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doPost(req, resp);
}
}
- HttpServletResponse
web服务器节后到客户端的http请求,针对这个请求,分别创建一个代表请求的HttpServletRequest对象,代表响应的一个HttpServletResponse;
- 如果要获取客户端请求过来的餐宿:找HttpServletRequest
- 如果要给客户端响应一些信息:找HttpServletResponse
1、简单分类
负责向浏览器发送数据
ServletOutputStream getOutputStream() throws IOException;
PrintWriter getWriter() throws IOException;
负责向浏览器发送响应头
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;
2、常见应用
-
向浏览器输出消息
-
下载文件
1. 要获取下载文件的路径 2. 下载的文件名是什么? 3. 设置想办法让浏览器能够支持下载需要的东西 4. 获取下载文件的输入流 5. 创建缓冲区 6. 获取OutputStream对象 7. 将FileOutputStream流写入到buffer缓冲区 8. 使用OutputStream将缓冲区中的数据输出到客户端
-
验证码功能
验证怎么实现
- 前端实现
- 后端实现,需要用到Java的图片类,生产一个图片
- 实现重定向
一个web资源收到客户端请求后,通知客户端去访问另外一个web资源,这个过程叫重定向
常见场景:
- 用户登录
void sendRedirect(String var1) throws IOException;
测试:
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// resp.setHeader("Location","/check");
// resp.setStatus(302);
resp.sendRedirect("/check");//重定向
}
面试题:请你聊聊重定向和转发的区别?
相同点
- 页面都会实现跳转
不同点 - 请求转发的时候,url不会发生变化
- 重定向,url会变化
public class RequestTest 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);
resp.sendRedirect("success.html");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doPost(req, resp);
}
}
<html>
<body>
<h2>Hello World!</h2>
<%--这里提交的路径需要寻找到项目路径--%>
<%--${pageContext.request.contextPath()}代表当前的项目--%>
<form action="${pageContext.request.contextPath}/login" method="get">
username: <input type="text" name="username"> <br>
password: <input type="password" name="password"> <br>
<input type="submit">
</form>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>success</h1>
</body>
</html>
- HttpServletRequest
HttpServletRequest代表客户端的请求,用户通过Http协议访问服务器,Http请求中的所有信息被封装到HttpServletRequest,通过这个HttpServletRequest的方法可以获得所有信息。
1、获取前端参数,并且请求转发
@Override
protected void doPost(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(username);
System.out.println(password);
System.out.println(Arrays.toString(hobbies));
//通过请求转发
//这里的“/”代表当前的web应用
req.getRequestDispatcher("/success.jsp").forward(req,resp);
}
注意:此处的请求转发中"/"代表的就是web线面的路径。
7.Cookie、Session
7.1、会话
**会话:**用户打开一个浏览器,点击了很多超链接,访问多个web资源,关闭浏览器,这个过程可以称hi为会话。
7.2、保存会话的两种技术
cookie
- 客户端技术(响应,请求)
session - 服务器技术,利用这个技术可以保存用户的会话信息,我们可以把信息或者数据放在Session中!
常见场景:网站登录后不需要再次重新登录。
7.3、Cookie
- 从请求中拿到cookie信息
- 从服务器响应给客户端cookie
cookie:一般会存在本地的用户目录下
乱码解决参见:
网络编程的转码。
URLEncoder.encod("","");
URLDecoder.decode(cookie.getValue(),"UTF-8");
7.4、Session
什么是Session:
- 服务器会给每一个用户(浏览器)创建一个Session;
- 一个session独占一个浏览器,只要浏览器没有关闭,这个session就存在
- 用户登录之后,整个网站都可以访问!—》保存用户信息
8、JSP
8.1、什么是JSP
Java Server Page:Java服务器端页面,ueheServlet一样,用于动态Web技术。
最大特点:
- 写jsp就像在写HTML
- 区别:
- HTML只给用户提供静态的数据
- jsp页面中可以嵌入Java代码,为用户提供动态数据。
8.2、JSP原理
思路:JSP到底怎么执行的!
- 代码层面没有问题
- 服务器内部工作
我的电脑地址:
C:\Users\11218\.IntelliJIdea2018.2\system\tomcat\Unnamed_javaweb-session-cookie\work\Catalina\localhost\ROOT\org\apache\jsp
发现页面变成了java程序!
浏览器像服务器发送请求,不管访问什么都会转成servlet!
//初始化
public void _jspInit() {
}
//销毁
public void _jspDestroy() {
}
//JSPService
public void _jspService(final javax.servlet.http.HttpServletRequest request, final javax.servlet.http.HttpServletResponse response)throws java.io.IOException, javax.servlet.ServletException {
}
- 判断请求
- 内置一些对象
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,当前页
3.输出页面前增加的代码
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页面中直接使用!
在jsp页面中:
只要是Java代码就会原封不动的输出
如果时HTML代码,就会被转换为:
out.wirte("<html>\r\n")
这样的形式,输出到前端。
8.3、JSP基础语法
任何语言都有自己的语法,Java中有。jsp作为Java技术的一种应用,它拥有一些自己扩充的语法(了解知道),Java中所有语法都支持!
jsp表达式:
<%-- jsp表达式
作用:用来将程序的输出,输出到客户端
<%= 变量或者表达式 %>
--%>
<%= new java.util.Date() %>
jsp脚本片段
<%-- jsp脚本片段 --%>
<%
int sum = 0;
for(int i = 1;i <= 100; i++){
sum+=i;
}
out.println("<h1>Sum="+sum+"</h1>");
%>
** 脚本片段的再实现 **
<%
int x = 10;
out.println(x);
%>
<p>这是一个jsp文档</p>
<hr>
<%-- 在代码嵌入HTML元素 --%>
<%
for (int i = 0; i < 5; i++){
%>
<h1>hello word</h1>
<%
}
%>
jsp声明
<%!
static {
System.out.println("Loading Sevlet");
}
private int globalVar = 0;
public void xv(){
System.out.println("进入了方法xv!");
}
%>
jsp声明:会被编译到jsp生成Java的类中!其他的,就会被生成到_jspService方法中。
在jsp嵌入Java代码即可!
<%%>
<%=%>
<%!%>
<%--注释--%>
jsp的注释不会被源代码查看到。
8.4、jsp指令
<%--@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"/>
8.5、九大内置对象
- PageContext
- Request 存东西
- Response
- Session 存东西
- Application(ServletContext)存东西
- config(ServletConfig)
- out
- page
- exception
pageContext.setAttribute("name1","xcg1");//保存的数据只在一个页面中有效
request.setAttribute("name2","xcg2");//保存的数据只在一次请求中有效,请求转发会携带数据
session.setAttribute("name3","xcg3");//保存的数据只会在一次会话中有效(打开关闭浏览器)
application.setAttribute("name4","xcg4");//保存的数据只在服务器中有效,从打开服务器到关闭服务器
request:客户端向服务器发送请求,产生的数据,用户看完就没用了,比如新闻,用户看完没用的!
session:客户端向服务器发送请求,产生的数据,用户看完一会还有用,比如:购物车;
application:客户端向服务器发送请求,产生的数据,一个用户用完了,其他用户还可能使用,比如:聊天
8.6、JSP标签、JSTL标签、EL表达式
<!-- jsp表达式的依赖 -->
<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>
EL表达式:
- 获取数据
- 执行运算
- 获取web开发的常用对象
JSP标签
<%--<jsp:include page=""></jsp:include>--%>
<jsp:forward page="jsptagTest.jsp">
<jsp:param name="name" value="xcg"></jsp:param>
<jsp:param name="age" value="20"></jsp:param>
</jsp:forward>
JSTL
标签库的使用就是为了弥补HTM标签的不足;它自定义许多标签,可以供我们使用,标签的功能和java代码
格式化标签
SQL标签
XML 标签
核心标签(掌握)
JSTL标签库使用步骤
- 引入对应的taglib
- 使用方法
- 在tomcat也需要引入jstl的包和standard的包,否则会报错:jstl报错解析
<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="管理员欢迎你!"/>
</c:if>
<c:out value="${isAdmin}"></c:out>
</body>
<body>
<%
ArrayList<String> people = new ArrayList<>();
people.add(0,"张三");
people.add(1,"李四");
people.add(2,"王五");
people.add(3,"赵六");
people.add(4,"田七");
request.setAttribute("list",people);
%>
<%--
var,每一次遍历的变量
items,要遍历的对象
begin,
end,
step
--%>
<c:forEach var="people" items="${list}">
<c:out value="${people}"/> <br>
</c:forEach>
<hr>
<c:forEach var="people" items="${list}" begin="1" end="4" step="2">
<c:out value="${people}"></c:out>
</c:forEach>
</body>
9、JavaBean
实体类
JavaBean有特定的写法
- 必须要有一个无参构造
- 属性必须私有化
- 必须尤对应的get/set方法
一般用来和数据库的字段做映射 ORM;
ORM对象关系映射 - 表–>类
- 字段–>属性
- 行记录–>对象
10、MVC三层架构
什么是MVC:Model view Controller 模型、视图、控制器
10.1、老版的架构
用户直接访问控制层,控制层就可以直接操作数据。
servlet-->CRUD-->数据库
弊端:程序十分臃肿,不利于维护
servlet的代码中:处理请求、响应、试图跳转、处理jdbc、处理业务代码、处理逻辑代码
架构:没有什么事加一层解决不了的!
程序员调用
JDBC
Mysql Oracle SQL Server.....
10.2、三层架构
Model
- 业务处理:业务逻辑(Service)
- 数据持久层:CRUD(Dao)
View - 展示数据
- 提供链接发起Servlet请求(a,form,img…)
Controller - 接收用户的请求:(req:请求参数、Session信息…)
- 交给用户层处理对应的代码
- 控制视图的跳转
11、Filter(重点)
shiro
Filter:过滤器,用来过滤网站数据;
- 处理中文乱码
- 登录验证
Fileter开发步骤:
- 导包
- 编写过滤器,重写对应方法即可
public class CharacterEncodingFilter implements Filter {
//初始化:web服务器启动就初始化,随时等待过滤器对象启动
public void init(FilterConfig filterConfig) throws ServletException {
System.out.println("初始化");
}
//chain:链
/*
1.过滤中的所有代码,再过滤特定请求的时候都会执行
2.必须要让过滤器继续同行
chain.doFilter(request,response);
*/
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("执行前");
chain.doFilter(request,response);//让请求继续走,如果不写,程序到这里就会被拦截停止!
System.out.println("执行后");
}
//销毁:web服务器关闭会销毁
public void destroy() {
System.out.println("销毁!");
}
}
- 在web.xml配置Filter过滤器
<filter>
<filter-name>CharacterEncodingFilter</filter-name>
<filter-class>com.xv.filter.CharacterEncodingFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<!-- 只要/servlet的任何请求,会经过这个过滤器 -->
<url-pattern>/servlet/*</url-pattern>
</filter-mapping>
12、监听器
实现一个监听器的接口(有N种)
- 编写一个监听器
实现监听器的接口
//在线人数监听:统计session
public class OnlineCountListener implements HttpSessionListener {
//创建session监听:看你的一举一动
//一旦创建一个session就会触发一次这个事件
public void sessionCreated(HttpSessionEvent se) {
ServletContext servletContext = se.getSession().getServletContext();
System.out.println(se.getSession().getId());
Integer onlineCount = (Integer) servletContext.getAttribute("OnlineCount");
if (onlineCount == null){
onlineCount = new Integer(1);
}else {
int count = onlineCount.intValue();
onlineCount = new Integer(count+1);
}
servletContext.setAttribute("OnlineCount",onlineCount);
}
//销毁session监听
//一旦销毁一个session就会触发一次这个事件
public void sessionDestroyed(HttpSessionEvent se) {
ServletContext servletContext = se.getSession().getServletContext();
Integer onlineCount = (Integer) servletContext.getAttribute("OnlineCount");
if (onlineCount == null){
onlineCount = new Integer(1);
}else {
int count = onlineCount.intValue();
onlineCount = new Integer(count+1);
}
servletContext.setAttribute("OnlineCount",onlineCount);
}
/*
Session销毁
1.手动销毁se.getSession().invalidate();
2.自动销毁
*/
}
- web.xml种注册监听器
<!-- 注册监听器 -->
<listener>
<listener-class>com.xv.listener.OnlineCountListener</listener-class>
</listener>
- 看情况是否使用
13、过滤器监听器的常见应用
监听器: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,100,100);
panel.setBackground(new Color(0,255,0));
frame.add(panel);
frame.setVisible(true);
frame.addWindowListener(new WindowListener() {
public void windowOpened(WindowEvent e) {
System.out.println("窗口打开了欢迎你!");
}
public void windowClosing(WindowEvent e) {
System.out.println("窗口关闭中!");
System.exit(0);
}
public void windowClosed(WindowEvent e) {
System.out.println("窗口已近关了");
}
public void windowIconified(WindowEvent e) {
}
public void windowDeiconified(WindowEvent e) {
}
public void windowActivated(WindowEvent e) {
System.out.println("激活");
}
public void windowDeactivated(WindowEvent e) {
System.out.println("未激活");
}
});
}
}
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,100,100);
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);
System.exit(0);
}
});
}
}
用户登录候后才能进入主页!用户注销后就不能进入主页了!
- 用户登录之后,像session中放入用户的数据
- 进入主页的时候要判断用户已经登录;要求:在过滤器中实现
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpServletRequest = (HttpServletRequest) request;
HttpServletResponse httpServletResponse = (HttpServletResponse) response;
Object session_username = httpServletRequest.getSession().getAttribute(Constant.SESSION_USERNAME);
if (session_username == null){
httpServletResponse.sendRedirect("/error.jsp");
}
chain.doFilter(request,response);
}
14、JDBC
什么事JDBC?连接数据库。
JDBC固定步骤:
- 加载驱动
- 连接数据库,代表数据库
- 向数据库发送SQL的对象Statement:CRUD
- 编写SQL(根据业务,不同的SQL)
- 执行SQL
- 关闭连接
public class TestJDBC {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
//配置信息
//解决中文乱码
String url ="jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=utf-8";
String username = "root";
String password = "root";
//加载驱动
Class.forName("com.mysql.jdbc.Driver");
//连接数据库
Connection connection = DriverManager.getConnection(url, username, password);
//向数据库发送sql的对象Statement PreparedStatement:CRUD
Statement statement = connection.createStatement();
//编写sql
String sql = "delete id=3 from people";
//i表示受影响的行数,增删改都用executeUpdate即可
// int i = statement.executeUpdate(sql);
//查询sql,返回一个ResultSet
ResultSet resultSet = statement.executeQuery(sql);
while(resultSet.next()){
System.out.println("id="+resultSet.getObject("id"));
System.out.println("name="+resultSet.getObject("name"));
System.out.println("password="+resultSet.getObject("password"));
System.out.println("email="+resultSet.getObject("email"));
System.out.println("birthday="+resultSet.getObject("birthday"));
}
//6.关闭连接释放资源(一定要做) 先开的后关
resultSet.close();
statement.close();
connection.close();
}
}
public class TestJDBC2 {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
String url ="jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=utf-8";
String username = "root";
String password = "root";
Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection(url, username, password);
String sql = "insert into people(id, name, password, email, birthday) values (?,?,?,?,?)";
PreparedStatement preparedStatement = connection.prepareStatement(sql);
java.util.Date date = new java.util.Date();
preparedStatement.setInt(1,4);//给第一个占位符“?”赋值1
preparedStatement.setString(2,"xcgxcg");//给第一个占位符“?”赋值1
preparedStatement.setString(3,"123456");//给第一个占位符“?”赋值1
preparedStatement.setString(4,"xcgxcg@qq.com");//给第一个占位符“?”赋值1
preparedStatement.setDate(5,new Date(date.getTime()));//给第一个占位符“?”赋值1
//执行sql
int i = preparedStatement.executeUpdate();
//关闭连接
preparedStatement.close();
connection.close();
}
}
事务
要么都成功,要么都失败!
ACID原则:保证数据安全。
开启事务
事务提交 commit
事务回滚 rollback
关闭事务
public class TestJDBC3 {
@Test
public void test() {
String url = "jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=utf-8";
String username = "root";
String password = "root";
Connection connection = null;
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection(url, username, password);
//开启事务
connection.setAutoCommit(false);
String sql1 = "update account set money = money-100 where name='xcg'";
connection.prepareStatement(sql1).executeUpdate();
//制造错误
int i = 1/0;
String sql2 = "update account set money = money+100 where name='xh'";
connection.prepareStatement(sql2).executeUpdate();
connection.commit();
System.out.println("success");
} catch (Exception e) {
try {
connection.rollback();
} catch (SQLException e1) {
e1.printStackTrace();
}
e.printStackTrace();
}finally {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}