文章目录
1.MYSQL
A.mysql安装
下载解压版mysql-5.7
-
- 配置环境变量
MYSQL_HOME = D:\Program Files\mysql-5.7.38-winx64
PATH += %MYSQL_HOME%\bin
- 2.编写配置文件my.ini,放到根目录
[mysql]
default-character-set=utf8
[mysqld]
skip-grant-tables # 跳过权限表认证,用于解决登录sql的报错:ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: NO)
port=3306
character-set-server=utf8
default-storage-engine=INNODB
sql-mode="STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION"
- 3.初始化数据库
以管理员方式执行,效果为在mysql根目录生成data文件夹
mysqld --initialize-insecure
注册mysql为系统服务
mysqld -install
#注册服务
mysqld -remove
#删除服务
- 4.启动mysql服务
net start mysql #启动服务
net stop mysql # 停止服务
设置密码
mysqladmin -u root password 1234`
登录
mysql -u root -p # 默认密码为空
mysql -u 用户名 -p 密码 -h 主机 -P 端口
或services.msc
# 通过windows的services图形界面启动
修改密码
mysqld --skip-grant-tables --skip-grant-tables 的意思是跳过权限表认证。
mysqld -u root -p root # 修改密码
- 连接他人mysql的方法
B.sql通用语法
1.sql不区分大小写
2.sql的注释:
单行注释:-- 注释内容
或 # 注释内容
多行注释:/* 注释内容 */
-
常用数据类型
-
sql的分类
-
SQL功能:
数据查询select;
数据定义create,drop,alter;
数据操纵insert,update,delete;
数据控制grant,revoke。
C.DDL数据定义语言
a.操作数据库
-
1.查询数据库
show databases;
-
2.创建数据库
create database 数据库名;
-
3.删除数据库
drop database数据库名;
-
4.使用数据库
use 数据库名;
-
5.查看当前使用的数据库
select Database();
b.操作表
- 1.创建表
create table 表名(
字段名1 数据类型1,
字段名2 数据类型2 -- 最后一行无逗号
);
- 2.查询所有表
show tables;
- 3.查询表结构
desc 表名;
- 4.删除表
drop table 表名;
- 5.修改表名
alter table 旧表名 rename to 新表名;
+6. 修改表名alter table 旧表名 rename to 新表名;
-
7.修改列的数据类型
alter table 表名 modify 列名 新数据类型;
-
8.修改列名和数据类型
alter table 表名 change 列名 新列名 新数据类型;
-
9.删除列
alter table 表名 drop 列名;
D.DML数据操作语言
a.添加数据
INSERT INTO student VALUES(2,'李四','2001-1-1',90);
b.修改数据
UPDATE student
SET
score=60,birthday='2001-12-12'
WHERE
studentname='李四;
//没有where全部修改
C.删除数据
DELETE FROM student WHERE studentname='李四';
//不添加where条件删除全部数据
E.DQL数据查询语言
a.基础查询
b.条件查询
SELECT id,studentname
FROM student
WHERE id=1;
\
c.排序查询
按成绩升序
SELECT * FROM student ORDER BY score ASC;
d.聚合函数和分组查询
- 聚合函数
SELECT COUNT(id) FROM student;
- 分组查询
查询每个部门的部门编号和每个部门的工资和:
SELECT deptno, SUM(sal)
FROM emp
GROUP BY deptno;
e.分页查询
SELECT * FROM student LIMIT 0 , 2 ;//查询前两条数据
SELECT * FROM student LIMIT 2 , 4 ;//查询第3和第4条数据
f.模糊查询
ELECT 字段 FROM 表 WHERE 某字段 Like 条件
其中关于条件,SQL 提供了两种匹配模式:
- % :表示任意 0 个或多个字符。可匹配任意类型和长度的字符,有些情况下若是中文,请使用两个百分号(%%)表示。
- _: 表示任意单个字符。匹配单个任意字符,它常用来限制表达式的字 符长度语句。
举例说明
查询姓名由 5 个字母构成的学生记录
SELECT * FROM stu
WHERE sname LIKE '_ _ _ _ _';
查询姓名由 5 个字母构成,并且第 5 个字母为“i”的学生记录
SELECT * FROM stu
WHERE sname LIKE '_ _ _ _i';
查询姓名以“z”开头的学生记录
SELECT * FROM stu
WHERE sname LIKE 'z%';
其中“%”匹配 0~n 个任何字母。
查询姓名中第 2 个字母为“i”的学生记录
SELECT * FROM stu
WHERE sname LIKE '_i%';
\查询姓名中包含“a”字母的学生记录
SELECT * FROM stu WHERE sname LIKE '%a%';
F.约束
- 外键
G.多表查询
- 内连接
select staff.name,deptname
from staff,deptno
where
staff.name=deptno.name;
- 左外连接
select staff.name,deptname
from staff
left join deptno onstaff.name=deptno.name;
- 右外连接
select deptname,deptno.name
from staff
right join deptno ondeptno.name=staff.name;
H.子查询
查询工资高于scott的人
SELECT *
FROM emp
WHERE sal>(SELECT sal FROM emp WHERE ename='SCOTT')
查询CLERK和SALESMAN工作的人
SELECT *
FROM emp
WHERE ename in(SELECT ename FROM emp WHERE job ='CLERK' or job = 'SALESMAN' );
查询MANAGER工作工资大于2000的人
SELECT *
FROM (SELECT * FROM emp WHERE sal>2000)as 工资大于2000表
WHERE job = 'MANAGER' ;
I.事务
BEGIN;//开启事务
...
COMMIT//提交事务
ROLLBACK;//回滚事务
查询是否会自动提交事务
SELECT @@autocommit;//1为自动,0为手动
set @@autocommit = 0;//设置为手动
2.JDBC
A.数据库连接
- 1.DriverManager
- 2.connection
- 3.Statement
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class Main {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
//1.注册驱动
Class.forName("com.mysql.cj.jdbc.Driver");
//2.连接
String url = "jdbc:mysql://127.0.0.1/db1";
String username = "root";
String password = "1234";
Connection c1 = DriverManager.getConnection(url,username,password);
//3.定义要执行的sql语句
String sql = "UPDATE stu SET age = 35 WHERE sid = \"S_1001\"";
//4.获取执行对象 Statement
Statement s1 = c1.createStatement();
//5.执行sql语句
int i = s1.executeUpdate(sql);//返回执行的语句数量
System.out.println(i);//1
//6.释放资源
c1.close();
s1.close();
}
}
B.事务
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class Main {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
//注册驱动
Class.forName("com.mysql.cj.jdbc.Driver");
//连接
String url = "jdbc:mysql://127.0.0.1/db1";
String username = "root";
String password = "1234";
Connection c1 = DriverManager.getConnection(url,username,password);
//定义要执行的sql语句
String sql1 = "UPDATE stu SET age = 44 WHERE sid = \"S_1001\"";
String sql2 = "UPDATE stu SET age = 41 WHERE sid = \"S_1002\"";
//获取执行对象 Statement
Statement s1 = c1.createStatement();
//执行sql语句
try {
//1.开启事务
c1.setAutoCommit(false);
int i1 = s1.executeUpdate(sql1);
int i2 = s1.executeUpdate(sql2);
int n = 3/0;
//2.提交事务
c1.commit();
System.out.println("提交成功");
} catch (Exception e) {
//3.回滚事务
c1.rollback();
System.out.println("提交失败");
}
//6.释放资源
c1.close();
s1.close();
}
}
C.ResultSet
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
//1.注册驱动
Class.forName("com.mysql.cj.jdbc.Driver");
//2.连接
String url = "jdbc:mysql://127.0.0.1/db1";
String username = "root";
String password = "1234";
Connection c1 = DriverManager.getConnection(url, username, password);
//3.定义要执行的sql语句
String sql = "SELECT * FROM stu";
//4.获取执行对象Statement
Statement stat = c1.createStatement();
//5.执行sql
ResultSet re = stat.executeQuery(sql);
int i=1;
//创建ArrayList集合
List<Account> student = new ArrayList<>();
while (re.next()){
Account account = new Account();
String id = re.getString(1);//第一列id
String name = re.getString(2);//第二列name
int age = re.getInt(3);//第三列age
String sex = re.getString(4);//第四列sex
System.out.println("第"+i+++"条数据:"+id+","+name+","+age+","+sex);
System.out.println("=============");
//赋值并添加到集合内
account.setId(id);
account.setName(name);
account.setAge(age);
account.setSex(sex);
student.add(account);
}
System.out.println("=====Student表=====\n"+student);
//释放资源
c1.close();
stat.close();
re.close();
}
}
D.REparedStatement
a.sql注入演示
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
//注册驱动
Class.forName("com.mysql.cj.jdbc.Driver");
//连接
String url = "jdbc:mysql://127.0.0.1/db1";
String username = "root";
String password = "1234";
Connection c1 = DriverManager.getConnection(url, username, password);
//1.随意输入不存在的用户账号,和特殊语句密码
String name = "23423423";
String pwd = "'or'1'='1";
//2.定义sql语句
//问题在拼字符串:name和pwd会先false后1=1为true,整个结果为true
String sql = "select * from user where username = '"+name+"' and password ='"+pwd+"'";//用单引号加上双引号
//3.创建执行对象Statement
Statement stat = c1.createStatement();
//4.执行sql语句
ResultSet re = stat.executeQuery(sql);
//判断结果集ResultSet内是否有内容
if (re.next()){
System.out.println("登录成功");
}else {
System.out.println("登录失败");
}
//释放资源
c1.close();
stat.close();
re.close();
}
}
b.解决注入
package JDBC1;
import java.sql.*;
public class Main {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
//注册驱动
Class.forName("com.mysql.cj.jdbc.Driver");
//连接
String url = "jdbc:mysql://127.0.0.1/db1";
String username = "root";
String password = "1234";
Connection c1 = DriverManager.getConnection(url, username, password);
//1.随意输入不存在的用户账号,和特殊语句密码
String name = "23423423";
String pwd = "'or'1'='1";
//2.定义sql语句,使用?当占位符
String sql = "select * from user where username = ? and password = ? ";
//创建执行对象prepareStatement
PreparedStatement pst = c1.prepareStatement(sql);
pst.setString(1,name);//sql语句的第一个?号,设置为name
pst.setString(2,pwd);//sql语句的第二个?号,设置为pwd
ResultSet re = pst.executeQuery();
//判断结果集ResultSet内是否有内容
if (re.next()){
System.out.println("登录成功");
}else {
System.out.println("登录失败");
}
//释放资源
c1.close();
pst.close();
re.close();
}
}
- 预编译功能的开启
E.数据库连接池
import com.alibaba.druid.pool.DruidDataSourceFactory;
import javax.sql.DataSource;
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Properties;
public class test {
public static void main(String[] args) throws Exception {
//1.加载配置文件
Properties p1 = new Properties();
p1.load(new FileInputStream("src/druid.properties"));
//2.获取连接对象
DataSource ds = DruidDataSourceFactory.createDataSource(p1);
//3.获取数据库连接
Connection cc = ds.getConnection();
//创建prepareStatement与sql语句的执行
String sql = "select * from stu";
PreparedStatement s = cc.prepareStatement(sql);
ResultSet re= s.executeQuery();
while(re.next()){
String id = re.getString(1);//第一列id
String name = re.getString(2);//第二列name
int age = re.getInt(3);//第三列age
String sex = re.getString(4);//第四列sex
System.out.println(id+","+name+","+age+","+sex);
System.out.println("=============");
}
//释放资源
cc.close();
s.close();
re.close();
}
}
//定义配置文件druid.properties
driverClassName = com.mysql.cj.jdbc.Driver
url=jdbc:mysql://127.0.0.1/db1?useSSL=false&userServerPrepStmts=true
username = "root"
password = "1234"
# 初始化连接数量
initialSize = 5
# 最大连接数
maxActive = 10
# 最大等待时间
maxWait = 3000
3.Maven
A. Maven安装与配置
- 1.安装网站
https://maven.apache.org/download.cgi - 2.配置
修改本地仓库存放目录
配置阿里云私人仓库
<mirror>
<id>aliyunmaven</id>
<mirrorOf>*</mirrorOf>
<name>阿里云公共仓库</name>
<url>https://maven.aliyun.com/repository/public</url>
</mirror>
B. Maven的基本使用
C.IDEA配置maven
D.maven坐标和创建,导入
-
maven坐标
-
创建项目
-
导入maven工程
-
实用的maven插件
E.依赖导入和依赖范围
- 导入依赖
- 依赖范围
4.MyBatis
-
mybatis官网
https://mybatis.org/mybatis-3/zh/getting-started.html -
添加MyBatis坐标
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>x.x.x</version>
</dependency>
A.基础使用
- 1.配置文件
配置核心文件mybatis-config.xml文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql:///db1?useSSL=false"/>
<property name="username" value="root"/>
<property name="password" value="1234"/>
</dataSource>
</environment>
</environments>
<mappers>
<!--加载sql映射文件-->
<mapper resource="userMapper.xml"/>
</mappers>
</configuration>
配置sql映射文件 userMapper.xml文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--
namespace -命名空间
id -唯一标识
resultType - 包装类型
-->
<mapper namespace="test">
<select id="selectAll" resultType="com.test.pojo.user">
select * from user
</select>
</mapper>
- 2.定义pojo类
//User类
public class User {
private int id;
private String username;
private String password;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "user{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
'}'+"\n";
}
}
- 3.加载核心与执行执行函数
// main
package com.test;
import com.test.pojo.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
public class main {
public static void main(String[] args) throws IOException {
//1.加载配置文件(可从官网复制)
String resource = "mybatis-config.xml";//加载配置文件路径
InputStream inputStream = Resources.getResourceAsStream(resource);//加载文件返回一个字节输入流
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);//将流传入,创建一个数据库连接池
//2.获取SqlSession对象,用来 执行sql语句
SqlSession sqlSession = sqlSessionFactory.openSession();
//3.执行sql语句
//传入名称空间和唯一标识
List<User> users = sqlSession.selectList("test.selectAll");
System.out.println(users);
//释放资源
sqlSession.close();
}
}
B.Mapper代理
依旧存在硬编码且查标识不方便
- 解决
-
配置文件
-
main
package com.test;
import com.test.mapper.userMapper;
import com.test.pojo.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
public class main {
public static void main(String[] args) throws IOException {
//1.加载配置文件(可从官网复制)
String resource = "mybatis-config.xml";//加载配置文件路径
InputStream inputStream = Resources.getResourceAsStream(resource);//加载文件返回一个字节输入流
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);//将流传入,创建一个数据库连接池
//2.获取SqlSession对象,用来 执行sql语句ff
SqlSession sqlSession = sqlSessionFactory.openSession();
/* //执行sql语句
//传入名称空间和唯一标识
List<User> users = sqlSession.selectList("test.selectAll");
System.out.println(users);*/
//3执行mapper代理sql语句
userMapper m = sqlSession.getMapper(userMapper.class);
List<User> users = m.selectAll();
System.out.println(users);
//释放资源
sqlSession.close();
}
}
//sql映射文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--
namespace -命名空间
id -唯一标识
resultType - 包装类型
-->
<mapper namespace="com.test.mapper.userMapper">
<select id="selectAll" resultType="com.test.pojo.User">
select * from user
</select>
</mapper>
// 配置核心文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql:///db1?useSSL=false"/>
<property name="username" value="root"/>
<property name="password" value="1234"/>
</dataSource>
</environment>
</environments>
<mappers>
<!--加载sql映射文件-->
<mapper resource="com/test/mapper/userMapper.xml"/>
</mappers>
</configuration>
// 定义接口
package com.test.mapper;
import com.test.pojo.User;
import java.util.List;
public interface userMapper {
List<User> selectAll();
}
//定义user类
package com.test.pojo;
public class User {
private int id;
private String username;
private String password;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "user{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
'}'+"\n";
}
}
C.XML核心配置文件
https://mybatis.org/mybatis-3/zh/configuration.html
类型别名
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!-- environments配置数据库环境,可以配置多个环境<environment,通过default切换不同的environment-->
<environments default="development">
<environment id="development">
<!-- 事务管理方式-->
<transactionManager type="JDBC"/>
<!-- 数据库连接池信息-->
<dataSource type="POOLED">
<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql:///db1?useSSL=false"/>
<property name="username" value="root"/>
<property name="password" value="1234"/>
</dataSource>
</environment>
</environments>
<mappers>
<!--加载sql映射文件-->
<mapper resource="com/test/mapper/userMapper.xml"/>
</mappers>
</configuration>
D.配置文件完成增删改查
- 基础配置文件
//mybatis-config.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!-- environments配置数据库环境,可以配置多个环境<environment,通过default切换不同的environment-->
<environments default="development">
<environment id="development">
<!-- 事务管理方式-->
<transactionManager type="JDBC"/>
<!-- 数据库连接池信息-->
<dataSource type="POOLED">
<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql:///db1?useSSL=false"/>
<property name="username" value="root"/>
<property name="password" value="1234"/>
</dataSource>
</environment>
</environments>
<mappers>
<!--加载sql映射文件-->
<mapper resource="com/test/mapper/userMapper.xml"/>
</mappers>
</configuration>
//userMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--
namespace -命名空间
id -唯一标识
resultType - 包装类型
-->
<mapper namespace="com.test.mapper.userMapper">
<select id="selectAll" resultType="com.test.pojo.User">
select * from user
</select>
</mapper>
//user类
package com.test.pojo;
public class User {
private int id;
private String userName;
private String passWord;
private String userNumber;
public String getUserNumber() {
return userNumber;
}
public void setUserNumber(String userNumber) {
this.userNumber = userNumber;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassWord() {
return passWord;
}
public void setPassWord(String passWord) {
this.passWord = passWord;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", userName='" + userName + '\'' +
", passWord='" + passWord + '\'' +
", userNumber='" + userNumber + '\'' +
'}'+ "\n";
}
}
//
a.查询所以数据
package com.test;
import com.test.mapper.userMapper;
import com.test.pojo.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
public class main {
public static void main(String[] args) throws IOException {
//1.加载配置文件(可从官网复制)
String resource = "mybatis-config.xml";//加载配置文件路径
InputStream inputStream = Resources.getResourceAsStream(resource);//加载文件返回一个字节输入流
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);//将流传入,创建一个数据库连接池
//2.获取SqlSession对象,用来 执行sql语句ff
SqlSession sqlSession = sqlSessionFactory.openSession();
//3.获取Mapper接口
userMapper m = sqlSession.getMapper(userMapper.class);
// 4.执行sql
List<User> users = m.selectAll();
System.out.println(users);
//释放资源
sqlSession.close();
}
}
//userMapper接口
package com.test.mapper;
import com.test.pojo.User;
import java.util.List;
public interface userMapper {
List<User> selectAll();
}
b.resultMap别名映射
当类变量与数据库属性名称不同时无法自动完成封装
- 1.标签完成映射,主键用id,非主键用result
- 2.将属性
resultType="com.test.pojo.User"
改为resultMap="userResult"
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--
namespace -命名空间
id -唯一标识
resultType - 包装类型
-->
<mapper namespace="com.test.mapper.userMapper">
<!-- 1.resultMap完成映射,主键用id,非主键用result-->
<resultMap id="userResult" type="com.test.pojo.User">
<result column="user_number" property="userNumber"/>
</resultMap>
<!-- 2.将resultType="com.test.pojo.User"改为resultMap="userResult"-->
<select id="selectAll" resultMap="userResult">
select * from user
</select>
</mapper>
c.查询指定参数的数据
通过参数占位符查询指定参数的数据
- 1.#{}
会替换成?,防止sql注入问题- 2.${}
直接使用字符串拼接,存在问题(一般不使用)
表名或者列名不固定时可使用
使用参数占位符接收参数
传递参数
d.多条件查询
-------->散装参数
-------->实体类封装参数
-------->map集合
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.test.mapper.userMapper">
<resultMap id="userResult" type="com.test.pojo.User">
<result column="user_number" property="userNumber"/>
</resultMap>
//1.通过条件查询指定数据
<select id="selectAppoint" resultMap="userResult">
select * from user
where username like #{userName} and user_number like #{userNumber}
</select>
</mapper>
- 1.散装参数
//userMapper接口
使用@Param(“”)注解
注解名与需xml内的参数名称相同
package com.test.mapper;
import com.test.pojo.User;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface userMapper {
//1.@Param
List<User> selectAppoint(@Param("userName")String userName, @Param("userNumber")String userNumber);
}
//userMapper.xml
- 2.实体类封装参数
//main
package com.test;
import com.test.mapper.userMapper;
import com.test.pojo.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
public class main {
public static void main(String[] args) throws IOException {
//1.接收参数,并封装成对象
String userName ="张";
String userNumber ="2001";
userName = "%" + userName +"%";
userNumber = "%" + userNumber +"%";
//注:sql占位符参数名要与user对象内的属性名相同
User u1 = new User();
u1.setUserName(userName);
u1.setUserNumber(userNumber);
//加载配置文件(可从官网复制)
String resource = "mybatis-config.xml";//加载配置文件路径
InputStream inputStream = Resources.getResourceAsStream(resource);//加载文件返回一个字节输入流
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);//将流传入,创建一个数据库连接池
SqlSession sqlSession = sqlSessionFactory.openSession();//获取SqlSession对象,用来 执行sql语句ff
userMapper m = sqlSession.getMapper(userMapper.class);//获取Mapper接口
//2.执行sql语句
List<User> users = m.selectAppoint(u1);
System.out.println(users);//输出结果
//[User{id=1, userName='张三', passWord='123', userNumber='20010101'}
//, User{id=2, userName='刘张四', passWord='123', userNumber='20010201'}
//, User{id=3, userName='张五', passWord='123', userNumber='20010301'}]
sqlSession.close();//释放资源
}
}
//userMpeer接口
package com.test.mapper;
import com.test.pojo.User;
import java.util.List;
public interface userMapper {
// List<User> selectAppoint(@Param("userName")String userName, @Param("userNumber")String userNumber);
List<User> selectAppoint(User u);
}
- 3.Map集合
//main
package com.test;
import com.test.mapper.userMapper;
import com.test.pojo.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class main {
public static void main(String[] args) throws IOException {
//1.接收参数,并封装成Map对象
String userName ="张";
String userNumber ="2001";
userName = "%" + userName +"%";
userNumber = "%" + userNumber +"%";
//注:第一个参数需要与userMapper.xml语句中的占位符参数名
Map m1 = new HashMap();
m1.put("userName",userName);
m1.put("userNumber",userNumber);
//加载配置文件(可从官网复制)
String resource = "mybatis-config.xml";//加载配置文件路径
InputStream inputStream = Resources.getResourceAsStream(resource);//加载文件返回一个字节输入流
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);//将流传入,创建一个数据库连接池
SqlSession sqlSession = sqlSessionFactory.openSession();//获取SqlSession对象,用来 执行sql语句ff
userMapper m = sqlSession.getMapper(userMapper.class);//获取Mapper接口
//2.执行sql语句
List<User> users = m.selectAppoint(m1);
System.out.println(users);//输出结果
//[User{id=1, userName='张三', passWord='123', userNumber='20010101'}
//, User{id=2, userName='刘张四', passWord='123', userNumber='20010201'}
//, User{id=3, userName='张五', passWord='123', userNumber='20010301'}]
sqlSession.close();//释放资源
}
}
//userMapper接口
package com.test.mapper;
import com.test.pojo.User;
import java.util.List;
import java.util.Map;
public interface userMapper {
List<User> selectAll();
User selectIdUser(int i);
// List<User> selectAppoint(@Param("userName")String userName, @Param("userNumber")String userNumber);
//List<User> selectAppoint(User u);
List<User> selectAppoint(Map m);
}
E.动态sql
官网动态sql网址
https://mybatis.org/mybatis-3/zh/dynamic-sql.html
动态sql标签:
a.多条件动态查询(if,where标签)
可选择任意数量的条件
- if
username like #{userName} and user_number like #={userNumber}
<select id="selectAppoint" resultMap="userResult">
select * from user
where 1 = 1 //用一个恒等式,在后面语句都加上and
//或使用<where>标签代替where 1=1
<if test="userName != NULL and userName !='' ">
and username like #{userName}
</if>
<if test="userNumber != Null and userNumber != '' ">
and user_number like #{userNumber}
</if>
</select>
- where
<select id="selectAppoint" resultMap="userResult">
select * from user
<where> //代替where和恒等式
<if test="userName != NULL and userName !='' ">
and username like #{userName}
</if>
<if test="userNumber != Null and userNumber != '' ">
and user_number like #{userNumber}
</if>
</where>
</select>
b.单条件动态查询choose(when,otherwise)
从多个条件中选择一个查询
choose相当于switch
when相当于case
otherwise相当于default
//main
package com.test;
import com.test.mapper.userMapper;
import com.test.pojo.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class main {
public static void main(String[] args) throws IOException {
//1.接收参数,并封装成对象
String userName ="张";
String userNumber ="2001";
userName = "%" + userName +"%";
userNumber = "%" + userNumber +"%";
User u1 = new User();
u1.setUserName(userName);
// u1.setUserNumber(userNumber);
//加载配置文件(可从官网复制)
String resource = "mybatis-config.xml";//加载配置文件路径
InputStream inputStream = Resources.getResourceAsStream(resource);//加载文件返回一个字节输入流
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);//将流传入,创建一个数据库连接池
SqlSession sqlSession = sqlSessionFactory.openSession();//获取SqlSession对象,用来 执行sql语句ff
userMapper m = sqlSession.getMapper(userMapper.class);//获取Mapper接口
//2.执行sql语句
List<User> users = m.selectChoose(u1);
System.out.println(users);//输出结果
sqlSession.close();//释放资源
}
}
//userMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.test.mapper.userMapper">
<!-- 1.resultMap完成映射,主键用id,非主键用result-->
<resultMap id="userResult" type="com.test.pojo.User">
<result column="user_number" property="userNumber"/>
</resultMap>
//1.choose
<select id="selectChoose" resultMap="userResult">
select * from user
where
<choose>
<when test="userName != null and userName !='' ">
username like #{userName}
</when>
<when test="userNumber != null and userNumber != '' ">
user_number like #{userNumber}
</when>]
<otherwise> //可防止不选择时报错,或使用<where>标签
1 = 1
</otherwise>
</choose>
</select>
//2.choose使用where标签
<!-- <select id="selectChoose" resultMap="userResult">
select * from user
<where>
<choose>
<when test="userName != null and userName !='' ">
username like #{userName}
</when>
<when test="userNumber != null and userNumber != '' ">
user_number like #{userNumber}
</when>
</choose>
</where>
</select>-->
</mapper>
c.添加
//userMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--
namespace -命名空间
id -唯一标识
resultType - 包装类型
-->
<mapper namespace="com.test.mapper.userMapper">
<!-- 1.resultMap完成映射,主键用id,非主键用result-->
<resultMap id="userResult" type="com.test.pojo.User">
<result column="user_number" property="userNumber"/>
</resultMap>
<!-- 2.将resultType="com.test.pojo.User"改为resultMap="userResult"-->
<select id="selectAll" resultMap="userResult">
select * from user
</select>
1.添加sql语句,并返回数据的主键
<insert id="add" useGeneratedKeys="true" keyProperty="id">
insert into user(username,password,user_number)
values (#{userName},#{passWord},#{userNumber});
</insert>
</mapper>
//main
package com.test;
import com.test.mapper.userMapper;
import com.test.pojo.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class main {
public static void main(String[] args) throws IOException {
//1.接收参数,并封装成对象
String userName ="李三";
String passWord = "123";
String userNumber ="20010101";
User u1 = new User();
u1.setUserName(userName);
u1.setPassWord(passWord);
u1.setUserNumber(userNumber);
//加载配置文件(可从官网复制)
String resource = "mybatis-config.xml";//加载配置文件路径
InputStream inputStream = Resources.getResourceAsStream(resource);//加载文件返回一个字节输入流
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);//将流传入,创建一个数据库连接池
SqlSession sqlSession = sqlSessionFactory.openSession();//获取SqlSession对象,用来 执行sql语句ff
userMapper m = sqlSession.getMapper(userMapper.class);//获取Mapper接口
//2.执行sql语句
m.add(u1);
//提交事务
sqlSession.commit();
sqlSession.close();//释放资源
}
}
d.修改及“set”标签的使用
//usermapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--
namespace -命名空间
id -唯一标识
resultType - 包装类型
-->
<mapper namespace="com.test.mapper.userMapper">
<!-- 1.resultMap完成映射,主键用id,非主键用result-->
<resultMap id="userResult" type="com.test.pojo.User">
<result column="user_number" property="userNumber"/>
</resultMap>
//1.定义sql修改语句
<update id="update">
update user
<set>
<if test="userName != null and userName !=''">username = #{userName},</if>
<if test="passWord != null and passWord != ''">passWord = #{passWord},</if>
<if test="userNumber != null and userNumber != ''">user_number = #{userNumber}</if>
</set> //防止逗号出现的报错
where id = #{id}
</update>
</mapper>
//main
package com.test;
import com.test.mapper.userMapper;
import com.test.pojo.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class main {
public static void main(String[] args) throws IOException {
//1.接收参数,并封装成对象
Integer id = 9;
String userName ="李456";
String passWord = "123";
String userNumber ="20060101";
User u1 = new User();
u1.setId(id);
u1.setUserName(userName);
u1.setPassWord(passWord);
u1.setUserNumber(userNumber);
//加载配置文件(可从官网复制)
String resource = "mybatis-config.xml";//加载配置文件路径
InputStream inputStream = Resources.getResourceAsStream(resource);//加载文件返回一个字节输入流
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);//将流传入,创建一个数据库连接池
SqlSession sqlSession = sqlSessionFactory.openSession();//获取SqlSession对象,用来 执行sql语句ff
userMapper m = sqlSession.getMapper(userMapper.class);//获取Mapper接口
//2.执行sql语句
int i = m.update(u1);
System.out.println(i);
//提交事务
sqlSession.commit();
sqlSession.close();//释放资源
}
}
e.删除
删除单个
//userMapper.xml
<delete id="delete">
delete from user where id = #{id}
</delete>
//userMapper接口
int delete(int i);
//main
package com.test;
import com.test.mapper.userMapper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.IOException;
import java.io.InputStream;
public class main {
public static void main(String[] args) throws IOException {
//加载配置文件(可从官网复制)
String resource = "mybatis-config.xml";//加载配置文件路径
InputStream inputStream = Resources.getResourceAsStream(resource);//加载文件返回一个字节输入流
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);//将流传入,创建一个数据库连接池
SqlSession sqlSession = sqlSessionFactory.openSession();//获取SqlSession对象,用来 执行sql语句ff
userMapper m = sqlSession.getMapper(userMapper.class);//获取Mapper接口
//2.执行sql语句
int i = m.delete(11);//返回影响行数的数量
System.out.println(i);
//提交事务
sqlSession.commit();
sqlSession.close();//释放资源
}
}
批量删除以及 “foreach”标签的使用
mybatis将数组封装成一个map集合:
1. map集合默认: array = 数组
2. 如果不想使用默认名称array(<foreach collection ="array"
>),使用@param注解默认key的名称
//userMapper接口
int deletes(@Param("ids") int[] ids);
//userMapper.xml
```SQL
<delete id="deletes">
delete from user where id in(
<foreach collection="ids" item="id" separator=",">
#{id}
</foreach>
)
</delete>
//main
package com.test;
import com.test.mapper.userMapper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.IOException;
import java.io.InputStream;
public class main {
public static void main(String[] args) throws IOException {
int[] is={8,9,11};
//加载配置文件(可从官网复制)
String resource = "mybatis-config.xml";//加载配置文件路径
InputStream inputStream = Resources.getResourceAsStream(resource);//加载文件返回一个字节输入流
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);//将流传入,创建一个数据库连接池
SqlSession sqlSession = sqlSessionFactory.openSession();//获取SqlSession对象,用来 执行sql语句ff
userMapper m = sqlSession.getMapper(userMapper.class);//获取Mapper接口
//2.执行sql语句
int i = m.deletes(is);
System.out.println(i);
//提交事务
sqlSession.commit();
sqlSession.close();//释放资源
}
}
F.参数传递
G.注解完成增删改查
- 注解与ResultMap
5.HTML
6.CSS
7.Javascript
JavaWeb技术核心
8.HTTP
A.http请求数据的格式
B.http响应数据格式
9.web服务器-Tomcat
A.配置
B.项目的部署
C.Maven web项目
-
项目结构
-
创建
-
- 1.使用骨架
- 1.使用骨架
-
- 2.不使用骨架
-
<packaging>war</packaging>
D.IDEA使用Tomcat
-
手动添加
-
插件
<build>
<plugins>
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.2</version>
<configuration>
<port>80</port>
<path>/</path>
</configuration>
</plugin>
</plugins>
</build>
E.servlet
a.基础使用
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
b.生命周期
package com.test.servlet;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebServlet;
import java.io.IOException;
@WebServlet(urlPatterns = "/demo1",loadOnStartup = 1)
public class ser implements Servlet {
//1.默认servlet被第一次访问的时候调用,只会调用一次
//使用loadOnStartup = 1可以改为服务器启动时调用
@Override
public void init(ServletConfig servletConfig) throws ServletException {
System.out.println("init.....");
}
//
@Override
public ServletConfig getServletConfig() {
return null;
}
//2.每一次访问servlet都会被调用,会调用多次
@Override
public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
System.out.println("service.....");
}
@Override
public String getServletInfo() {
return null;
}
//3.内存释放或者servlet关闭时调用,只会调用一次
@Override
public void destroy() {
}
}
c.五个方法介绍
d.servlet体系
package com.test.servlet;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/demo2")
public class httpser extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("get...");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("post...");
}
}
e.urlPattern配置
- 当一个路径同时满足精确匹配和目录匹配,优先精确匹配
(1).请求Reques
a.request体系结构
b.request获取请求数据
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
@WebServlet("/demo2")
public class httpser extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("get...");
//1.获取请求行
//getMethod()
String method = req.getMethod();
System.out.println("method:"+method);//method:GET
//getRequestURI()
String requestURI = req.getRequestURI();
System.out.println("uri"+requestURI);//uri/demo2
//2.获取请求头
String host = req.getHeader("Host");//主机名
String agent = req.getHeader("user-agent");//浏览器版本
System.out.println("Host:"+ host+" agent:"+agent);
//Host:localhost agent:Mozilla/5.0 (Windows NT 10.0; Win64; x64)............
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("post...");
//3.获取请求体
BufferedReader reader = req.getReader();
String s = reader.readLine();
System.out.println(s); //username=user1&password=123456
}
}
/a.html提交表单
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<span>请登录</span>
<form action="/demo2" method="post">
<input type="text" name="username">
<input type="password" name="password">
<input type="submit">
</form>
</body>
</html>
c通用方式获取请求参数
- 解决Get与post的不同
post与get的的方式不同使用不方便,使用Map集合获取:
package com.test.servlet;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.Map;
@WebServlet("/demo2")
public class httpser extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//1.用Map集合获取参数getParameterMap()
Map<String, String[]> map1 = req.getParameterMap();
//遍历Map数组
for (String key : map1.keySet()) { //iter关键字快速添加
System.out.println(key+":");
String[] values = map1.get(key);
for (String value : values) {
System.out.print(value+" ");
}
System.out.println();
}
System.out.println("===数组获取===");
//2.用数组获取值
String[] hobbies = req.getParameterValues("hobby");
for (String hobby : hobbies) {
System.out.println("hobby:"+hobby);
}
System.out.println("===单个获取===");
//3.单个获取
String username = req.getParameter("username");
System.out.println(username);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doGet(req, resp);//复用
}
}
//a.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<span>请登录</span>
<form action="/demo2" method="get">
<input type="text" name="username">
<input type="password" name="password"><br>
<input type="checkbox" name="hobby" value="swim">游泳
<input type="checkbox" name="hobby" value="run">跑步<br>
<input type="submit">
</form>
</body>
</html>
d.中文乱码的解决
post使用的是GetReader()
get使用的是getQuerString
-
1.post方式解决
req.setCharacterEncoding("UTF-8");
-
2.get方式解决
@WebServlet("/demo2")
public class httpser extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String username = req.getParameter("username");
System.out.println("解码前:"+username);//解码前:ä½ å¥½ 乱码
byte[] bytes = username.getBytes("ISO-8859-1");//编码
String s = new String(bytes, "UTf-8");//解码
String s = new String(bytes, StandardCharsets.UTF_8);//解码
System.out.println("解码后:"+s);//解码后:你好
//为避免写错可使用StandardCharsets对象
//byte[] bytes = username.getBytes(StandardCharsets.ISO_8859_1);//编码
// String s = new String(bytes, StandardCharsets.UTF_8);//解码
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doGet(req, resp);
}
}
e.请求转发
//demo3
@WebServlet( "/demo3")
public class Servlet1 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("demo3....");
//setAttribute()设置数据
request.setAttribute("password","123456");
//1.访问demo3时将数据转发到dem4
request.getRequestDispatcher("/demo4").forward(request,response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request,response);
}
}
//demo4
@WebServlet( "/demo4")
public class Servlet2 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("demo4...");
//getAttribute()获取数据
Object password = request.getAttribute("password");
System.out.println(password);//123456
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request,response);
}
}
(2)响应Response
a.设置响应功能&重定向
- 重定向
//R1
@WebServlet("/R1")
public class Response extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("r1..........");
/*1.设置响应状态码,302为转发
response.setStatus(302);
2.设置响应头Location()转发地址
response.setHeader("Location","R2");
*/
//可简化为:
response.sendRedirect("R2");
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request,response);
}
}
//R2
@WebServlet("/R2")
public class Response2 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("成功转发到r2.....");
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request,response);
}
}
访问R1后重定向到R2
- 重定向和转发的区别
路径问题
b.响应字符数据
@WebServlet("/R3")
public class Response3 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1.为避免中文乱码
// response.setHeader("content-type","text/html");//设置解析html语句
response.setContentType("text/html;charset=utf-8");//解析html语句以及编码
//2.获取字符输出流
PrintWriter w = response.getWriter();
w.write("你好");
w.write("<h1>你好,张三</h1>");
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request,response);
}
}
c.响应字节数据
@WebServlet("/R3")
public class Response3 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1.读取文件
FileInputStream f1 = new FileInputStream("src/main/java/img1.png");
//2.response的直接输出流
ServletOutputStream os = response.getOutputStream();
//3. IOUtils工具类完成copy
IOUtils.copy(f1,os);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request,response);
}
}
F.用户注册案例(结合mybits)
//Login主程序
package com.login.web;
import com.login.mapper.UserMapper;
import com.login.pojo.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.jdbc.Null;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//从html获取数据
String userName = request.getParameter("username");
String passWord = request.getParameter("password");
//封装实体类
User user = new User();
user.setUserName(userName);
user.setPassWord(passWord);
String resource = "mybatis-config.xml";//加载配置文件路径
InputStream inputStream = Resources.getResourceAsStream(resource);//加载文件返回一个字节输入流
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);//将流传入,创建一个数据库连接池
SqlSession sqlSession = sqlSessionFactory.openSession();//获取SqlSession对象,用来 执行sql语句ff
UserMapper mapper = sqlSession.getMapper(UserMapper.class);//获取Mapper接口
//执行查询sql
User select = mapper.Select(userName);
//设置编码,防止中文报错
response.setContentType("text/html;charset=utf-8");
//response输出流
PrintWriter writer = response.getWriter();
//判断用户是否存在
if (select == null){
//2.执行注册,添加sql
mapper.add(user);
sqlSession.commit();
writer.write("您好"+userName+",恭喜注册成功");
sqlSession.close();
}else
{
writer.write("用户"+userName+"已存在");
sqlSession.close();
}
sqlSession.close();
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request,response);
}
}
//usermapper接口
package com.login.mapper;
import com.login.pojo.User;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
public interface UserMapper {
@Select("select * from users where username = #{username}")
User Select(String username);
@Insert("insert into users values(null,#{username},#{password})")
void add(User user);
}
//mybatis-config.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!-- environments配置数据库环境,可以配置多个环境<environment,通过default切换不同的environment-->
<environments default="development">
<environment id="development">
<!-- 事务管理方式-->
<transactionManager type="JDBC"/>
<!-- 数据库连接池信息-->
<dataSource type="POOLED">
<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql:///db1?useSSL=false&useServerPrepStmts=true"/>
<property name="username" value="root"/>
<property name="password" value="1234"/>
</dataSource>
</environment>
</environments>
<mappers>
<!--加载sql映射文件-->
<mapper resource="com/login/mapper/UserMapper.xml"/>
</mappers>
</configuration>
//userMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--
namespace -命名空间
id -唯一标识
resultType - 包装类型
-->
<mapper namespace="com.login.mapper.UserMapper">
</mapper>
//user实体类
package com.login.pojo;
public class User {
private int id;
private String userName;
private String passWord;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassWord() {
return passWord;
}
public void setPassWord(String passWord) {
this.passWord = passWord;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", userName='" + userName + '\'' +
", passWord='" + passWord + '\'' +
'}'+"\n";
}
}
//pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<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>
<groupId>org.example</groupId>
<artifactId>login</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<properties>
<maven.compiler.source>19</maven.compiler.source>
<maven.compiler.target>19</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.5</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.30</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.2</version>
<configuration>
<port>80</port>
<path>/</path>
</configuration>
</plugin>
</plugins>
</build>
</project>
G.SqlSessionFactory工具类优化
创建一个工具类,使用时调用
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.IOException;
import java.io.InputStream;
public class SqlSessionFactoryUtil {
private static SqlSessionFactory sqlSessionFactory;
static{
try {
String resource = "mybatis-config.xml";//加载配置文件路径
InputStream inputStream = Resources.getResourceAsStream(resource);//加载文件返回一个字节输入流
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);//将流传入,创建一个数据库连接池
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static SqlSessionFactory getSqlSessionFactory(){return sqlSessionFactory;}
}
10.JSP
A.JSP的脚本
B.Servlet+jsp- - - EL表达式
servlet提供数据
//userAll.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1>以下为全部账号</h1>
${users}
</body>
</html>
//UserMapper接口
public interface UserMapper {
@Select("select * from users")
List<User> SelectAll();
}
//selectALLServlet主程序
package com.login.web;
import com.login.mapper.UserMapper;
import com.login.pojo.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
@WebServlet("/All")
public class selectALLServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1.获取数据库数据
//加载配置文件,(可从官网查询)
String resource = "mybatis-config.xml";//加载配置文件路径
InputStream inputStream = Resources.getResourceAsStream(resource);//加载文件返回一个字节输入流
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);//将流传入,创建一个数据库连接池
SqlSession sqlSession = sqlSessionFactory.openSession();//获取SqlSession对象,用来 执行sql语句ff
UserMapper mapper = sqlSession.getMapper(UserMapper.class);//获取mapper接口
//执行sql,获取数据
List<User> users = mapper.SelectAll();
//2.请求转发数据
//将数据存储到request域中
request.setAttribute("users",users);
//转发数据到jsp文件(jsp文件通过EL表达式获取数据)
request.getRequestDispatcher("/userAll.jsp").forward(request,response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request,response);
}
}
如果el表达式失效可添加以下头:
<%@page isELIgnored=“false” %>
C.Servlet+jsp- - - JSTL标签
a.导入坐标
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.1.2</version>
</dependency>
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
b.if&foreach的使用
//jstl.jsp
<%--
Created by IntelliJ IDEA.
User: hfq20
Date: 2023/3/12
Time: 21:19
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>账号管理</title>
</head>
<body>
<table border="1">
<thead>
<tr><td>序号</td><td>账号</td><td>密码</td><td>权限</td></tr>
</thead>
<tbody>
//1.foreach
<c:forEach items="${users}" var="user">
<tr >
<td>${user.id}</td>
<td>${user.userName}</td>
<td>${user.passWord}</td>
<td>
//2.if标签
<c:if test="${user.id == 1}">
管理员
</c:if>
<c:if test="${user.id !=1}">
普通用户
</c:if>
</td>
</tr>
</c:forEach>
</tbody>
</table>
</body>
</html>
//servlet
package com.login.web;
import com.login.mapper.UserMapper;
import com.login.pojo.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
@WebServlet("/All")
public class selectALLServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1.获取数据库数据
//加载配置文件,(可从官网查询)
String resource = "mybatis-config.xml";//加载配置文件路径
InputStream inputStream = Resources.getResourceAsStream(resource);//加载文件返回一个字节输入流
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);//将流传入,创建一个数据库连接池
SqlSession sqlSession = sqlSessionFactory.openSession();//获取SqlSession对象,用来 执行sql语句ff
UserMapper mapper = sqlSession.getMapper(UserMapper.class);//获取mapper接口
//执行sql,获取数据
List<User> users = mapper.SelectAll();
//2.请求转发数据
//将数据存储到request域中
request.setAttribute("users",users);
request.getRequestDispatcher("/jstl.jsp").forward(request,response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request,response);
}
}
D.MVC模式和三层架构
//uti/SqlSessionFactoryUtil
package com.login.util;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.IOException;
import java.io.InputStream;
public class SqlSessionFactoryUtil {
private static SqlSessionFactory sqlSessionFactory;
static{
try {
String resource = "mybatis-config.xml";//加载配置文件路径
InputStream inputStream = Resources.getResourceAsStream(resource);//加载文件返回一个字节输入流
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);//将流传入,创建一个数据库连接池
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static SqlSessionFactory getSqlSessionFactory(){return sqlSessionFactory;}
}
//service/UserService
package com.login.service;
import com.login.mapper.UserMapper;
import com.login.pojo.User;
import com.login.util.SqlSessionFactoryUtil;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import java.util.List;
public class UserService {
// //加载配置文件
SqlSessionFactory sqlSessionFactory = SqlSessionFactoryUtil.getSqlSessionFactory();
/*查询所以数据*/
public List<User> selectAll(){
//1.获取数据库数据
SqlSession sqlSession = sqlSessionFactory.openSession();//获取SqlSession对象,用来 执行sql语句
UserMapper mapper = sqlSession.getMapper(UserMapper.class);//获取mapper接口
//执行sql,获取数据
List<User> users = mapper.SelectAll();
sqlSession.close();
return users;
}
11.会话
(1).Cookie
a.Cookie的使用
b.Cookie的原理和使用细节
//发送数据
@WebServlet("/test")
public class test extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//解决中文编码问题
String hello ="你好";
hello = URLEncoder.encode(hello,"UTF-8");
//1.创建cookie
Cookie cookie = new Cookie("sayHello", hello);
//2.设置时间
cookie.setMaxAge(60*60*5);
//3.发送cookie
response.addCookie(cookie);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request,response);
}
}
//接收数据
@WebServlet("/test2")
public class test2 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Cookie[] cookies = request.getCookies();
for (Cookie cookie : cookies) {
String name = cookie.getName();
if ("sayHello".equals(name)){
String value = cookie.getValue();
//解决中文编码问题
value = URLDecoder.decode(value,"UTF-8");
System.out.println(value);
}
}
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request,response);
}
}
(2).Session
a.Session使用
a.Session的原理和使用细节
@WebServlet( "/test")
public class test extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//创建对象
HttpSession session = request.getSession();
//设置属性
session.setAttribute("username","小明");
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request,response);
}
}
@WebServlet("/test1")
public class test1 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//创建对象
HttpSession session = request.getSession();
//获取属性
Object username = session.getAttribute("username");
System.out.println(username);//小明
//销毁
ession.invalidate();//再次访问结果为null
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
}
A.Cookie与Session的区别
B.记住用户案例
//a.jsp
<%--
Created by IntelliJ IDEA.
User: hfq20
Date: 2023/3/16
Time: 9:27
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<span>请登录</span>
<form action="/login" method="post">
<div id="errorMSg" style="color: brown">${errorMsg}</div>
//1.${cookie.键值.value}
账号:<input type="text" name="username" value="${cookie.username.value}"><br>
密码:<input type="password" name="password" value="${cookie.password.value}"><br>
记住我<input type="checkbox" name="remember" value="1"><br>
<input type="submit" value="登录">
</form>
</body>
</html>
//loginSerlvet
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
private UserService userService = new UserService();
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String username = request.getParameter("username");
String password = request.getParameter("password");
String remember = request.getParameter("remember");
User login = userService.login(username, password);
if (login != null){
if ("1".equals(remember)){
//1.新建cookie
Cookie cUserName = new Cookie("username",username);
Cookie cPassWord = new Cookie("password",password);
//设置时间
cUserName.setMaxAge(60*60*10);//10小时
cPassWord.setMaxAge(60*60*10);//10小时
//2.发送cookie
response.addCookie(cUserName);
response.addCookie(cPassWord);
}
response.sendRedirect("All");
}else {
request.setAttribute("errorMsg","用户名或密码错误");
request.getRequestDispatcher("/a.jsp").forward(request,response);
}
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request,response);
}
}
//pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<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>
<groupId>org.example</groupId>
<artifactId>login</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<properties>
<maven.compiler.source>19</maven.compiler.source>
<maven.compiler.target>19</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.5</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.30</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.2</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.1.2</version>
</dependency>
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.2</version>
<configuration>
<port>80</port>
<path>/</path>
</configuration>
</plugin>
</plugins>
</build>
</project>
12.Filter
A.基本使用
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;
@WebFilter("/*")
public class filterDemo implements Filter {
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
//1.放行前,(对request数据进行处理)
System.out.println("1 filter...");
//2.放行
filterChain.doFilter(servletRequest,servletResponse);// 页面执行System.out.println("2 filter...");
//3.放行后执行,(对response数据进行处理)
System.out.println("3 filter...");
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void destroy() {
}
}
B.拦截路径的配置
C.登录验证案例
//LoginFilter
@WebFilter("/*")
public class LoginFilter implements Filter {
public void init(FilterConfig config) throws ServletException {
}
public void destroy() {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
String[] urls = {"a.jsp","add.jsp","a.html","add.html"};
HttpServletRequest req = (HttpServletRequest) request;//用子类才能获取req.getSession()
//1.获取当前页面的URl
String uri = req.getRequestURI().toString();
System.out.println(uri);
//2.如果是指定的页面直接放行
for (String u : urls) {
if (uri.contains(u)){
chain.doFilter(request,response);
return;
}
}
HttpSession session = req.getSession();//如果已登录那么设置一个Session,key为“user1”
Object user = session.getAttribute("user1");
//3.如果不是指定的页面,并且未登录,那么跳转到login页面
if (user != null){
chain.doFilter(request, response);
}else {
request.setAttribute("denglu","请登录");
request.getRequestDispatcher("a.jsp").forward(request,response);
}
}
}
12.Listener
13.AJAX
A.基础使用
//html(从官网复制)
<body>
<script>
// 1.创建核心对象
var xhttp;
if (window.XMLHttpRequest) {
xhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
// 2.发送请求,可携带数据
xhttp.open("GET", "http://localhost/ajax");
xhttp.send();
//3.获取响应
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
alert(this.responseText);
}
};
</script>
</body>
</htm
//ajaxServlet
@WebServlet("/ajax")
public class AJAXServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.getWriter().write("AJAX");
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request,response);
}
}
B.案例–使用AJAX验证用户是否存在
//ajaxServlet
@WebServlet("/ajax")
public class AJAXServlet extends HttpServlet {
private UserService userService = new UserService();
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1.获取请求
String username = request.getParameter("username");
//2.使用Service查询用户名是否存在
User select = userService.select(username);
boolean flag ;
if (select != null){
flag = true;
response.getWriter().write("" +flag);
}else {
flag = false;
response.getWriter().write(""+flag);
}
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request,response);
}
}
//html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<span>注册:</span><br>
<form action="/ajax" method="post">
账号:<input id="name" type="text" name="username">
<span id="user_error" style="display: none;color:red">用户已存在</span><br>
密码:<input type="password" name="password"><br>
<input type="submit" value="提交">
</form>
<script>
//1.绑定点击事件
document.getElementById("name").onblur=function (){
//2.发送ajax
let username = this.value;
// 1.1创建核心对象
var xhttp;
if (window.XMLHttpRequest) {
xhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
// 1.2.发送请求 ,username属性
xhttp.open("GET", "http://localhost/ajax?username="+username);
xhttp.send();
//1.3.获取响应
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
if(this.responseText == "true"){
document.getElementById("user_error").style.display="";
}else{
document.getElementById("user_error").style.display="none";
}
}
};
}
</script>
</body>
</html>
C.框架Axios
https://www.axios-http.cn/docs/intro
a.使用
//aious.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<span>axios注册:</span><br>
<form action="/ajax" method="post">
账号:<input id="name" type="text" name="username">
<span id="user_error" style="display: none;color:red">用户已存在</span><br>
密码:<input type="password" name="password"><br>
<input type="submit" value="提交">
</form>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script>
//失去焦点,判断用户是否存在
document.getElementById("name").onblur=function () {
let username = this.value;
axios({//请求
method: 'get',
url: "http://localhost/ajax?username="+username
})
.then(function (response) {//响应
//判断用户是否存在
alert(response.data)
if(response.data == true){
document.getElementById("user_error").style.display="";
}else{
document.getElementById("user_error").style.display="none";
}
});
}
</script>
</body>
</html>
//servlet
@WebServlet("/ajax")
public class AJAXServlet extends HttpServlet {
private UserService userService = new UserService();
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1.获取请求
String username = request.getParameter("username");
//2.使用Service查询用户名是否存在
User select = userService.select(username);
boolean flag ;
if (select != null){
flag = true;
response.getWriter().write("" +flag);
}else {
flag = false;
response.getWriter().write(""+flag);
}
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request,response);
}
}
b.API
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<span>axios注册:</span><br>
<form action="/ajax" method="post">
账号:<input id="name" type="text" name="username">
<span id="user_error" style="display: none;color:red">用户已存在</span><br>
密码:<input type="password" name="password"><br>
<input type="submit" value="提交">
</form>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script>
document.getElementById("name").onblur=function () {
let username = this.value;
//起别名
axios.get("http://localhost/ajax?username="+username)
.then(function (response){
if(response.data == true){
document.getElementById("user_error").style.display="";
}else{
document.getElementById("user_error").style.display="none";
}
})}
</script>
</body>
</html>
14.JSON
A.基础使用
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<script>
var json = {
"name" : "zs",
"age": 13,
"addr":["北京","上海"]
}
alert(json.age)
alert(json.addr)
</script>
</body>
</html>
B.json数据和java对象的转换
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.62</version>
</dependency>
public class json {
public static void main(String[] args) {
User user = new User();
user.setId(10);
user.setUserName("user10");
user.setPassWord("123");
//1.java转json,toJSONString
String s = JSON.toJSONString(user);
System.out.println("java-->json:"+s);//java-->json:{"id":10,"passWord":"123","userName":"user10"}
//2.json转java,parseObject
User user1 = JSON.parseObject(s, User.class);
System.out.println("json-->java:"+user1);//json-->java:User{id=10, userName='user10', passWord='123'}
}
}
C.案例–Axios和JSon查询所以数据
//html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
全部账号如下:
<input type="button" value="新增" id="add">
<table border="1" id="table">
<thead>
<tr><td>序号</td><td>账号</td><td>密码</td><td>权限</td><td>操作</td></tr>
</thead>
<tbody>
</tbody>
</table>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script>
window.onload = function (){
axios({ //请求
method: 'get',
url: 'http://localhost/JsonAll',
})
.then(function (response) { //响应
let users = response.data; //获得响应数据
let dataTable =' <thead>\n' +
' <tr><td>序号</td><td>账号</td><td>密码</td><td>权限</td><td>操作</td></tr>\n' +
' </thead>';
//遍历json数据
for (let i = 0; i < users.length; i++) {
let user = users[i];
dataTable += "\n"+"<tr><td>"+(i+1)+"</td>" +
"<td>"+user.userName+"</td>" +
"<td>"+user.passWord+"</td>" +
"<td>权限</td><td>操作</td></tr>";
}
document.getElementById("table").innerHTML = dataTable;
});
}
</script>
</body>
</html>
//servelt
@WebServlet("/JsonAll")
public class JsonServlet extends HttpServlet {
UserService userService = new UserService();
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1.调用UserSer获取数据库数据
List<User> users = userService.selectAll();
//2.JSON序列化,将对象转换未json数据
String s = JSON.toJSONString(users);
//3.响应数据,防止中文乱码
response.setContentType("text/json;charset=utf-8");
response.getWriter().write(s);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
}
D.案例–Axios和JSon添加数据
//html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<span>json方式注册:</span><br>
<form action="#">
账号:<input type="text" name="username" id="username"><br>
密码:<input type="password" name="password" id="password"><br>
<input type="submit" value="提交" id="btn">
</form>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script>
document.getElementById("btn").onclick = function (){
//1.json数据
var formData = {
"userName":"",
"passWord":""
}
let username = document.getElementById("username").value;
formData.userName = username
let password = document.getElementById("password").value;
formData.passWord = password;
axios({ //发送请求
method: 'post',
url: 'http://localhost/JAdd',
data: formData
}).then(function (response) { //响应
alert("success")
if (response.data == "success"){
location.href="http://localhost/json.html"
}
}).catch(function (){
alert("error")
})
}
</script>
</body>
</html>
//servlet
@WebServlet("/JAdd")
public class JAddServlet extends HttpServlet {
UserService userService = new UserService();
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1.post请求,数据在请求体内
BufferedReader reader = request.getReader();
String s = reader.readLine();
//2.json数据转换成User对象
User user = JSON.parseObject(s, User.class);
//3.执行数据库添加
userService.Add(user);
response.getWriter().write("success");
System.out.println("success");
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response); }
}
15.VUE
A.基础使用
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div id="app">
<input v-model = "username">
{{username}}
</div>
<script src="js/vue.js"></script>
<script>
new Vue({
el:"#app",
data(){
return{
username:""
}
}
});
</script>
</body>
</html>
B.常用指令
a.v-bind绑定标签属性值
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div id="app">
<!-- 1.v-bind 改变属性-->
<a v-bind:href="url" >vue</a>
<!-- 2.输入框改变url值-->
<input v-model = "url">
</div>
<script src="js/vue.js"></script>
<script>
new Vue({
el:"#app",
data(){
return{
url:"https://cn.vuejs.org/"
}
}
});
</script>
</body>
</html>
b.v-on绑定事件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div id="app">
<button v-on:click="show()">点击说hi</button>
</div>
<script src="js/vue.js"></script>
<script>
new Vue({
el:"#app",
data(){
return{
url:"https://cn.vuejs.org/"
}
},
methods:{
show(){
alert("hi")
}
}
});
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div id="app">
打分:<input v-model="score">
<!-- 1.v-if-->
<div v-if="score>=60">及格</div>
<div v-else>不及格</div>
<!-- 2. v-show-->
<div v-show="score>=60">通过</div>
<div v-show="score<60">未通过</div>
</div>
<script src="js/vue.js"></script>
<script>
new Vue({
el:"#app",
data(){
return{
score:100
}
}
});
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div id="app">
<div v-for="addr in addrs">{{addr}}</div>
<div v-for="(i,addr) in addrs">{{i+1}}---{{addr}}</div>
</div>
<script src="js/vue.js"></script>
<script>
new Vue({
el:"#app",
data(){
return{
addrs:["北京","上海","深圳"]
}
}
});
</script>
</body>
</html>
C.生命周期
D.案例—vue查询所以
//html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div id="app">
<input type="button" value="新增" id="add">
<table border="1" id="table">
<thead>
<tr><td>序号</td><td>账号</td><td>密码</td><td>权限</td><td>操作</td></tr>
</thead>
<tbody>
<!-- v-for遍历json数据-->
<tr v-for="user in users">
<td >{{user.id}}</td>
<td >{{user.userName}}</td>
<td >{{user.passWord}}</td>
<td>权限</td><td>操作</td>
</tr>
</tbody>
</table>
</div>
<script src="js/vue.js"></script>
<script src="js/axios.js"></script>
<script>
new Vue({
el:"#app",
data(){
return{
users:[]
}
},
mounted(){
var _this = this;
axios({ //请求
method: 'get',
url: 'http://localhost/JsonAll',
})
.then(function (response) { //响应
_this.users = response.data;
});
}
});
</script>
</body>
</html>
//servlet
@WebServlet("/JsonAll")
public class JsonServlet extends HttpServlet {
UserService userService = new UserService();
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1.调用UserSer获取数据库数据
List<User> users = userService.selectAll();
//2.JSON序列化
String s = JSON.toJSONString(users);
//3.响应数据,防止中文乱码
response.setContentType("text/json;charset=utf-8");
response.getWriter().write(s);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
}
E.案例—vue添加数据
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div id="app">
<span>Vue方式注册:</span><br>
<form action="#" >
账号:<input type="text" name="username" v-model="users.userName"><br>
密码:<input type="password" name="password" v-model="users.passWord"><br>
<input type="submit" value="提交" v-on:click="add()">
</form>
</div>
<script src="js/vue.js"></script>
<script src="js/axios.js"></script>
<script>
new Vue({
el: "#app",
data() {
return {
users: {}
}
},
methods: {
add() {
var _this = this;
axios({
method: 'post',
url: 'http://localhost/JAdd',
data: _this.users
}).then(function (response) {
alert("success")
if (response.data == "success") {
location.href = "http://localhost/vueAll.html"
}
}).catch(function () {
alert("error")
})
}
}
});
</script>
</body>
</html>
@WebServlet("/JAdd")
public class JAddServlet extends HttpServlet {
UserService userService = new UserService();
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1.post请求,数据在请求体内
BufferedReader reader = request.getReader();
String s = reader.readLine();
//2.json数据转换成User对象
User user = JSON.parseObject(s, User.class);
//3.执行数据库添加
userService.Add(user);
response.getWriter().write("success");
System.out.println("success");
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response); }
}