JavaWeb
静态web资源(如html 页面):指web页面中供人们浏览的数据始终是不变。
动态web资源:指web页面中供人们浏览的数据是由程序产生的,不同时间点访问web页面看到的内容各不相同。
静态web资源开发技术:HTML、CSS、JavaScript。
动态web资源开发技术:JSP/Servlet、ASP、PHP等。在Java中,动态web资源开发技术统称为Java Web。
Web服务器
技术讲解
ASP:微软,国内最早流行的是ASP,在HTML中嵌入了VB的脚本,ASP+COM,维护成本高。
PHP:开发速度很快,功能很强大,跨平台,代码简单,但是无法承载大访问量的情况(局限性)。
JSP/Servlet:sun公司主推的B/S架构,基于java语言,可以承载三高问题(高并发,高可用,高性能)。
Web服务器
IIS:微软的,主要用于ASP,Windows中自带的服务器。
**Tomcat:**Tomcat是Apache 软件基金会(Apache Software Foundation)的Jakarta 项目中的一个核心项目,最新的Servlet 和JSP 规范总是能在Tomcat 中得到体现,Tomcat 5支持最新的Servlet 2.4 和JSP 2.0 规范。因为Tomcat 技术先进、性能稳定,而且免费,因而深受Java 爱好者的喜爱并得到了部分软件开发商的认可,成为目前比较流行的Web 应用服务器。
Tomcat 服务器是一个免费的开放源代码的Web 应用服务器,属于轻量级应用服务器,在中小型系统和并发访问用户不是很多的场合下被普遍使用,是开发和调试JSP 程序的首选。对于一个JavWeb初学者来说,是最好的选择。
Tomcat
安装Tomcat:官网下载(tomcat.apache.org/)压缩包,解压至指定目…
在bin目录下点击startup.bat启动,在浏览器网址栏输入localhost:8080测试。
Http
Http(超文本传输协议):http是一个简单的请求–响应协议,它通常运行在TCP之上。(默认端口:80)
Https:443
Http请求
Http响应
请求方式:
get:请求能够携带的参数比较少,大小有限制,会在浏览器地址栏显示参数的内容,不安全,但是高效。
post:请求能够携带的参数没有限制,大小没有限制,不会再浏览器地址栏显示参数的内容,安全,但不高效。
200:请求响应成功
3**:请求重定向
404:找不到资源
Maven
Maven:项目架构管理工具,自动导入jar包(约定大于配置)。
下载Maven后解压,配置环境变量,将bin目录的路径配置到path中,在cmd中输入mvn-version,查看是否配置成功
D:Environmentsapache–maven-3.6.3maven–repo
pom.xml
由于maven的约定大于配置,我们之后写的配置文件可能无法导出或者无法生效,就需要在maven配置下面配置resouce。
Servlet
servlet就是sun公司开发动态web的一门技术,sun公司在API中提供了一个接口叫Servlet,如果需要开发一个Servlet程序,需要编写一个类去实现Servlet接口,再把开发好的java类部署到web服务器中。
HelloServlet
sun公司有两个Servlet接口的默认实现类:HttpServlet和GenericServlet
父项目中会有
<modules>
<module>servlet-01</module>
</modules>
子项目中有
<parent>
<artifactId>javaweb-02-servlet</artifactId>
<groupId>com.zr</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
3.Maven环境优化:修改web.xml为最新的,将Maven的结构搭建完整。
4.编写一个普通类,实现Servlet接口,继承HttpServlet。
public class HelloServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//ServletOutputStream outputStream = resp.getOutputStream();
PrintWriter writer = resp.getWriter(); //响应流
writer.println("Hello Servlet");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doPost(req, resp);
}
}
5.编写Servlet的映射:我们写的是java程序,但是要通过浏览器访问,而浏览器要连接web服务器,所以我们要在web服务器注册我们写的Servlet,还需要给它一个浏览器能够访问的路径。
<!--注册Servlet-->
<servlet>
<servlet-name>hello</servlet-name>
<servlet-class>com.zr.servlet.HelloServlet</servlet-class>
</servlet>
<!--Servlet请求路径-->
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
6.配置Tomcat
Servlet原理
Servlet是由Web服务器调用,web服务器收到请求后,会进行以下操作:
Mapping
-
<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>/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>/hello/*</url-pattern>
</servlet-mapping>
4.默认请求
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
<!--*前面不能加任何映射的路径-->
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>*.zzr</url-pattern>
</servlet-mapping>
指定了固有的映射路径,优先级最高,找不到就会走默认的处理请求。
处理404页面
<!--404-->
<servlet>
<servlet-name>error</servlet-name>
<servlet-class>com.zr.servlet.ErrorServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>error</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
ServletContext
web容器在启动的时候,它会为每一个web程序都创建一个ServletContext对象,它代表了当前的 web应用。
public class HelloServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("hello");
//this.getInitParameter(); 初始化参数
//this.getServletConfig(); Servlet的配置
//this.getServletContext(); Servlet上下文
ServletContext context = this.getServletContext();
String username = "周周";
context.setAttribute("username",username);//将一个数据保存在ServletContext中
}
}
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.setCharacterEncoding("utf-8");
resp.setContentType("text/html");
resp.getWriter().println("名字:"+username);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
}
}
<servlet>
<servlet-name>hello</servlet-name>
<servlet-class>com.zr.servlet.HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>get</servlet-name>
<servlet-class>com.zr.servlet.GetServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>get</servlet-name>
<url-pattern>/get</url-pattern>
</servlet-mapping>
<!--配置一个web应用的初始化参数-->
<context-param>
<param-name>url</param-name>
<param-value>jdbc:mysql://localhost:3306/mybaits</param-value>
</context-param>
<servlet>
<servlet-name>gp</servlet-name>
<servlet-class>com.zr.servlet.ServletDemo03</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>gp</servlet-name>
<url-pattern>/gp</url-pattern>
</servlet-mapping>
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().println(url);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doPost(req, resp);
}
}
2.请求转发
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);//转发
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doPost(req, resp);
}
}
<servlet>
<servlet-name>sd4</servlet-name>
<servlet-class>com.zr.servlet.ServletDemo04</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>sd4</servlet-name>
<url-pattern>/sd4</url-pattern>
</servlet-mapping>
读取资源文件
properties
发现都被打包到了target下的class目录下,我们称这个路径为类路径classpath。
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 properties = new Properties();
properties.load(is);
String username = properties.getProperty("username");
String password = properties.getProperty("password");
resp.getWriter().println("username:"+username);
resp.getWriter().println("password:"+password);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
<servlet>
<servlet-name>sd5</servlet-name>
<servlet-class>com.zr.servlet.ServletDemo05</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>sd5</servlet-name>
<url-pattern>/sd5</url-pattern>
</servlet-mapping>
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<excludes>
<exclude>**/*.properties</exclude>
<exclude>**/*.xml</exclude>
</excludes>
<filtering>true</filtering>
</resource>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
</build>
//文件 db.properties
username=root
password=123456
HttpServletResponse
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_OK = 200;
...
int SC_MULTIPLE_CHOICES = 300;
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_INTERNAL_SERVER_ERROR = 500;
int SC_BAD_GATEWAY = 502;
下载文件
public class FileServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//1. 获取下载文件的路径
String realPath = "D:\IDEACode\javaweb-02-servlet\response\src\main\resources\1.PNG";
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))>0){
out.write(buffer,0,len);
}
in.close();
out.close();
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
验证码功能
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(300,60,BufferedImage.TYPE_INT_RGB);
//得到图片
Graphics g = image.getGraphics(); //笔
//设置图片的背景颜色
g.setColor(Color.green);
g.fillRect(0,0,300,60);
//给图片写数据
g.setColor(Color.magenta);
g.setFont(new Font(null,Font.BOLD,70));
g.drawString(makeNum(),0,60);
//浏览器以图片的形式打开
resp.setContentType("image/png");
//网站存在缓存。不让浏览器缓存
resp.setDateHeader("expires",-1);
resp.setHeader("Cache-Control","no-cache");
resp.setHeader("Pragma","no-cache");
//把图片显示出来
boolean write = 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>
<servlet-name>image</servlet-name>
<servlet-class>com.zr.servlet.ImageServlet</servlet-class>
</servlet>
<!--Servlet请求路径-->
<servlet-mapping>
<servlet-name>image</servlet-name>
<url-pattern>/image</url-pattern>
</servlet-mapping>
实现重定向
void sendRedirect(String var1) throws IOException;//重定向
public class RedirectServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
/*
resp.setHeader("Location","/r/image");
resp.setStatus(302);
*/
resp.sendRedirect("/r/image");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
配置web.xml测试
重定向和转发的区别:
相同点:页面都会发生跳转
不同点:
- 请求转发的时候,url不会改变 307
- 重定向的时候,url地址栏会发生变化 302
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<body>
<h2>Hello World!</h2>
<%--提交的路径需要寻找到当前项目的路径--%>
<form action="${pageContext.request.contextPath}/login" method="post">
用户名:<input type="text" name="username"><br>
密码 :<input type="password" name="password"><br>
<input type="submit">
</form>
</body>
</html>
success.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1>success</h1>
</body>
</html>
public class RequestTest extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("进入这个请求了");
String username = req.getParameter("username");
String password = req.getParameter("password");
System.out.println("username:"+username);
System.out.println("password:"+password);
resp.sendRedirect("/r/success.jsp");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
<!--注册Servlet-->
<servlet>
<servlet-name>test</servlet-name>
<servlet-class>com.zr.servlet.RequestTest</servlet-class>
</servlet>
<!--Servlet请求路径-->
<servlet-mapping>
<servlet-name>test</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
HttpServletRequest
HttpServletRequest代表客户端的请求,用户通过http协议访问服务器,http请求中的所有的信息会被封装到HttpServletRequest,通过这个HttpServletRequest的方法,获得客户端的所有信息。
public class LoginServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
@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[] hobbys = req.getParameterValues("hobbys");
System.out.println("==================================");
System.out.println(username);
System.out.println(password);
System.out.println(Arrays.toString(hobbys));
//请求转发
//这里的/代表当前的web应用
req.getRequestDispatcher("/success.jsp").forward(req,resp);
}
}
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>登录</title>
</head>
<body>
<h1>登录</h1>
<div style="text-align: center">
<form action="${pageContext.request.contextPath}/login" method="post">
用户名:<input type="text" name="username"><br>
密码:<input type="password" name="password"><br>
爱好:
<input type="checkbox" name="hobbys" value="唱歌">唱歌
<input type="checkbox" name="hobbys" value="女孩">女孩
<input type="checkbox" name="hobbys" value="写字">写字
<input type="checkbox" name="hobbys" value="代码">代码
<br>
<input type="submit">
</form>
</div>
</body>
</html>
success.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1>登录成功</h1>
</body>
</html>
web.xml
<servlet>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>com.zr.servlet.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
Cookie, Session
- 客户端技术(响应,请求)
Cookie
从请求中拿到cookie信息
//保存用户上一次访问的时间
public class CookieDemo01 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");
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()+"");
//有效期为1天
cookie.setMaxAge(24*60*60);
resp.addCookie(cookie);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
web.xml
<servlet>
<servlet-name>CookieDemo01</servlet-name>
<servlet-class>com.zr.servlet.CookieDemo01</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>CookieDemo01</servlet-name>
<url-pattern>/c1</url-pattern>
</servlet-mapping>
删除cookie
Session
session和cookie的区别:
- cookie是把用户的数据写给用户的浏览器,浏览器保存(可以保存多个)
- session是把数据写到用户独占的session中,服务器保存(保存重要的信息,减少资源的浪费)
- session对象由服务器创建
session保存数据
package com.zr.pojo;
public class Person {
private String name;
private int age;
public Person() {
}
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + ''' +
", age=" + age +
'}';
}
}
public class SessionDemo01 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存东西
session.setAttribute("name",new Person("周周",1));
//获得session的id
String id = session.getId();
//判断session是不是新创建的
if(session.isNew()){
resp.getWriter().write("session创建成功,ID:"+ id);
}else {
resp.getWriter().write("session已经存在,ID:"+ id);
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
public class SessionDemo02 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();
Person person = (Person) session.getAttribute("name");
System.out.println(person);
}
@Overridejava
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
<servlet>
<servlet-name>SessionDemo01</servlet-name>
<servlet-class>com.zr.servlet.SessionDemo01</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>SessionDemo01</servlet-name>
<url-pattern>/s1</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>SessionDemo02</servlet-name>
<servlet-class>com.zr.servlet.SessionDemo02</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>SessionDemo02</servlet-name>
<url-pattern>/s2</url-pattern>
</servlet-mapping>
session手动注销
public class SessionDemo03 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
HttpSession session = req.getSession();
session.removeAttribute("name");
//手动注销session
session.invalidate();
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
JSP
什么是JSP
jsp:java server pages,Java服务器端界面,和servlet一样,用于开发动态web技术。
特点
JavaBean
实体类
JavaBean有特定的写法:
ORM对象关系映射
package com.zr.pojo;
//实体类 一般是和数据库中的表结构一一对应的
public class People {
private int id;
private String name;
private int age;
private String address;
public People() {
}
public People(int id, String name, int age, String address) {
this.id = id;
this.name = name;
this.age = age;
this.address = address;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return "People{" +
"id=" + id +
", name='" + name + ''' +
", age=" + age +
", address='" + address + ''' +
'}';
}
}
<%@ page import="com.zr.pojo.People" %><%--
Created by IntelliJ IDEA.
User: zr
Date: 2020/10/11
Time: 22:08
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<%
// People people = new People();
// people.setAddress();
// people.setId();
// people.setAge();
// people.setName();
//和下面的等价
%>
<jsp:useBean id="people" class="com.zr.pojo.People" scope="page"/>
<jsp:setProperty name="people" property="address" value="武汉"/>
<jsp:setProperty name="people" property="id" value="1"/>
<jsp:setProperty name="people" property="age" value="18"/>
<jsp:setProperty name="people" property="name" value="小周"/>
姓名:<jsp:getProperty name="people" property="name"/>
id:<jsp:getProperty name="people" property="id"/>
年龄:<jsp:getProperty name="people" property="age"/>
地址:<jsp:getProperty name="people" property="address"/>
</body>
</html>
MVC三层架构
MVC:model,view,controller 模型视图控制器
Model
View
- 展示数据
- 提供操作发起Servlet请求(a,form,img ….)
Controller(Servlet)
工作流程:
1.浏览器通过视图向控制器发出请求;
2.控制器接收到请求后对数据进行封装,选择模型进行业务逻辑处理;
过滤器
- 处理中文乱码
- 登录验证…
Filter
功能:
1、⽤来拦截传⼊的请求和传出的响应。
2、修改或以某种⽅式处理正在客户端和服务端之间交换的数据流。
如何使⽤?
与使⽤ Servlet 类似,Filter 是 Java WEB 提供的⼀个接⼝,开发者只需要⾃定义⼀个类并且实现该接⼝
即可。
Filter 的⽣命周期
当 Tomcat 启动时,通过反射机制调⽤ Filter 的⽆参构造函数创建实例化对象,同时调⽤ init ⽅法实现
初始化,doFilter ⽅法调⽤多次,当 Tomcat 服务关闭的时候,调⽤ destory 来销毁 Filter 对象。
⽆参构造函数:只调⽤⼀次,当 Tomcat 启动时调⽤(Filter ⼀定要进⾏配置)
init ⽅法:只调⽤⼀次,当 Filter 的实例化对象创建完成之后调⽤
doFilter:调⽤多次,访问 Filter 的业务逻辑都写在 Filter 中
destory:只调⽤⼀次,Tomcat 关闭时调⽤。
同时配置多个 Filter,Filter 的调⽤顺序是由 web.xml 中的配置顺序来决定的,写在上⾯的配置先调
⽤,因为 web.xml 是从上到下顺序读取的。
实际开发中 Filter 的使⽤场景:
1、统⼀处理中⽂乱码。
2、屏蔽敏感词。
监听器
JDBC
Java连接数据库,导入JDBC依赖mysql–connector-java,IDEA中连接数据库
public class TestJdbc {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
//配置信息
String url = "jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=utf8";
String username = "root";
String password = "123456";
//加载驱动
Class.forName("com.mysql.jdbc.Driver");
//连接数据库
Connection connection = DriverManager.getConnection(url, username, password);
//向数据库发送sql的对象
Statement statement = connection.createStatement();
//编写sql
String sql = "select * from users";
//执行查询sql,返回一个结果集
ResultSet rs = statement.executeQuery(sql);
while (rs.next()){
System.out.println("id="+rs.getObject("id"));
System.out.println("name="+rs.getObject("name"));
System.out.println("password="+rs.getObject("password"));
System.out.println("email="+rs.getObject("email"));
System.out.println("birthday="+rs.getObject("birthday"));
}
//关闭连接
rs.close();
statement.close();
connection.commit();
}
}
预编译sql
<!--单元测试-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
简单使用
@Test注解只在方法上有效,只要加了这个注解的方法,就可以直接运行.
public class TestJdbc3 {
@Test
public void test(){
System.out.println("Hello");
}
}
转账事务(创建account表,字段id,name,money),使用单元测试
public class TestJdbc3 {
@Test
public void test() {
//配置信息
String url = "jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=utf8";
String username = "root";
String password = "123456";
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='A'";
connection.prepareStatement(sql1).executeUpdate();
//制造错误
int i=1/0;
String sql2 = "update account set money=money+100 where name='B'";
connection.prepareStatement(sql2).executeUpdate();
connection.commit();//以上sql都执行成功才提交
System.out.println("提交成功!");
} catch (Exception e) {
try {
//如果出现异常,就回滚事务
connection.rollback();
System.out.println("转账失败!");
} catch (SQLException throwables) {
throwables.printStackTrace();
}
e.printStackTrace();
}finally {
try {
connection.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
}
原文地址:https://blog.csdn.net/qq_57747969/article/details/132667626
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如若转载,请注明出处:http://www.7code.cn/show_2721.html
如若内容造成侵权/违法违规/事实不符,请联系代码007邮箱:suwngjj01@126.com进行投诉反馈,一经查实,立即删除!