java后端第二阶段:JavaWeb

一、Mysql


        定义:关系型数据库,存储在硬盘数据安全。

1.SQL通用语法

注释:

        单行注释 -- 注释内容 或  #注释内容(MySQL特有)

        多行注释 /* 注释 */       

DDL:操作数据库,表等

DML:对表中的数据进行增删改

DQL:对表中的数据进行查询

DCL:对数据库进行权限控制 

2.DDL-操作数据库

查询:SHOW DATABASES;

创建:

        (1)创建数据库:CREATE DATABASE 数据库名称;

        (2)创建数据库(判断,如果不存在则创建):CREATE DATABASE IF NOT EXISTS 数据库名称;

删除:

        (1)删除数据库:DROP DATABASE 数据库名称;

        (2)删除数据库(判断,如果存在则删除):DROP DATABASE IF EXISTS 数据库名称;

查看当前使用的数据库:SELECT DATABASE();

使用数据库:USE 数据库名称

3.DDL-操作表

查询当前数据库下的表:SHOW TABLES;

查询表结构:DESC 表名称;

创建表:

        CREATE TABLE 表名(

                字段1 数据类型1,

                字段2 数据类型2);

数据类型:int、float、double、date、datetime、varchar、text等;double使用存储100.02这样的数double(总长度,小数保留的位数) double(5,2)

删除表:

        删除表:DROP TABLE 表名

        删除表时判断表是否存在:DROP TABLE IF EXISTS 表名;

修改表:

        修改表名:ALTER TABLE 表名 RENAME TO 新的表名;

        添加一列:ALTER TABLE 表名 ADD 列名 数据类型;

        修改数据类型:ALTER TABLE 表名 MODIFY 列名 新数据类型;

修改列名和数据类型:ALTER TABLE 表名 CHANGE 列名 新列名 新数据类型;

删除列:ALTER TABLE 表名 DROP 列名;

4.DML-操作数据

添加数据:

        1.给指定列添加数据:INSERT INTO 表名(列名1,列名2...)VALUES(值1,值2....);

        2.给全部列添加数据:INSERT INTO 表名VALUES(值1,值2....);

        3.批量添加数据:

                INSERT INTO 表名 (列名1,列名2...) VALUES(值1,值2....),(值1,值2....);

                INSERT INTO 表名 VALUES(值1,值2....),(值1,值2....);

修改数据:UPDATE 表名 SET 列名1=值1,列名2=值2,...[WHERE 条件]

删除数据:DELETE FROM 表名 [WHERE 条件];

5.DQL-数据查询

基础查询:SELECT [DISTINCT] 列名 AS 别名 FROM 表名                #DISTINCT:去除重复数据            #AS:起别名

条件查询:SELECT 列名 FROM 表名 WHERE 条件列表;

排序查询:SELECT 列名 FROM 表名 ORDER BY 排序字段1 [排序方式1],排序字段1 [排序方式2]...;         ASC:升序(默认)         DESC:降序排序

聚合函数:COUNT(列名):个数 MAX最大值 MIN最小值 AVG平均值 SUM求和        SELECT 聚合函数(列名) FROM 表;

分组查询:SELECT 字段列表 FROM 表名 [WHERE 分组前条件] GROUP BY 分组字段名 [HAVING 分组后条件过滤]

分页查询:SELECT 字段列表 FROM 表名 LIMIT 起始索引 , 查询条目数;        计算公式:起始索引=(当前页码-1)* 每页显示的条数

6.约束

约束分类:NOT NULL:非空约束 UNIQUE:唯一约束 PRIMARY KEY:主键约束 CHECK:检查约束(不常用)

外键约束:

        CREATE TABLE 表名([CONSTRAINT] 外键名称 FOREIGN KEY (外键字段名称) REFERENCES 主表名称(主表列名称));

        ALTER TABLE 表名 ADD CONSTRAINT 外键名称 FOREIGN KEY (外键字段名称) REFERENCES 主表名称(主表列名称);

7.多表查询

内连接:查询交集

        隐式内连接:SELECT 字段列表 FROM 表1,表2... WHERE 条件;

        显示内连接:SLELECT 字段列表 FROM 表1 [INNER] JOIN 表2 ON 条件;

外连接:左外连接:查询A表所有数据和交集部分数据;右外连接:查询B表所有数据和交集部分数据

        左外连接:SELECT 字段列表 FROM 表1 LEFT [OUTER] JOIN 表2 ON 条件

        右外连接:SELECT 字段列表 FROM 表1 RIGHT [OUTER] JOIN 表2 ON 条件

子查询:查询中嵌套查询

        单行单列:SELECT 字段列表 FROM 表 WHERE 字段名 = (子查询)

        多行单列:SELECT 字段列表 FROM 表 WHERE 字段名 in (子查询)

        多行多列:SELECT 字段列表 FROM(子查询)WHERE 条件

8.事务

        原子性----一致性---隔离性---持久性

        START TRANSACTION 或者 BEGIN   #开启事务

        COMMIT;        #提交事务

        ROLLBACK         #回滚事务

二、JDBC


1.入门案例

#1.导入jar包 mysql-contror-java-8.0.23.jar
#2.注册驱动 Class.forName("com.mysql.jdbc.Driver); #8.0使用com.mysql.cj.jdbc.Driver
#8.0使用jdbc:mysql://localhost:3306/jdbc?useSSL=false&serverTimezone=UTC
#3.获取链接 Connection conn = DriverManager.getConnerction(url,username,password) 
#4.定义sql语句 String sql = "update.."
#5.获取执行SQL对象Statement stmt = createStatement();
#6.执行SQL stmt.exeuteUpdate(sql)
#7.处理返回结果
#8.释放资源
conn.close()   stmt.close()

2.JDBC的API详解

DriverManager:连接驱动管理

Connection:连接,获取执行的sql对象;

        开启事务:setAutoCommit(boolean autoCommit);true为自动提交事务;false为手动提交事务,即为开启事务

        提交事务:commit()        回滚事务:rollback()

Statement:执行sql语句

        int executeUpdate(sql):执行DML、DDL语句        返回影响行数

        ResultSet executeQuery(sql):执行DQL语句        返回ResultSet结果集

ResultSet:结果集返回查询结果    ResultSet.next()判断是否有下一列   ResultSet.getInt(1)获取这列的第一个值。索引从1开始 ResultSet.getInt("id")

PreparedStatement:防止sql注入

        (1)获取prepareStattement预编译对象

String sql = "select * from account where id = ?";
PreparedStatement pstmt = connection.prepareStatement(sql);

        (2)设置参数值:pstmt.setString(1,id)

String id = "1";
pstmt.setString(1,id);

        (3)执行sql

ResultSet resultSet = pstmt.executeQuery();

3.Druid使用

使用步骤:1.导入jar包druid    2.定义配置文件    3.加载配置文件   4.获取数据连接池对象    5.获取连接

(1)在src下创建druid.properties文件

driverClassName=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/jdbc?useSSL=false&serverTimezone=UTC
username=root
password=root
# 初始化连接数量
initialSize=5
# 最大连接数
maxActive=10
# 最大等待时间
maxWait=3000

(2)主代码

public static void main(String[] args) throws Exception {
        Properties prop = new Properties();
        prop.load(new FileInputStream("src/druid.properties"));
        DataSource dataSource = DruidDataSourceFactory.createDataSource(prop);
        Connection connection = dataSource.getConnection();
        System.out.println(connection);
    }

4.案例

(1)在src下新建druid.properties配置文件

driverClassName=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/jdbc?useSSL=false&serverTimezone=UTC
username=root
password=root
# 初始化连接数量
initialSize=5
# 最大连接数
maxActive=10
# 最大等待时间
maxWait=3000

(2)初始化Account实体类

@Data
public class Account {
    //这里不用int是因为int有初始值
    private Integer id;
    private String name;
    private Double balance;
}

(3)查询account所有用户

public static void main(String[] args) throws Exception {
        Properties prop = new Properties();
        prop.load(new FileInputStream("src/druid.properties"));
        DataSource dataSource = DruidDataSourceFactory.createDataSource(prop);
        Connection connection = dataSource.getConnection();
        String sql = "select * from account";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        ResultSet resultSet = preparedStatement.executeQuery();
        List<Account> accountList = new ArrayList<Account>();
        while (resultSet.next()){
            int id = resultSet.getInt("id");
            String name = resultSet.getString("name");
            double balance = resultSet.getDouble("balance");
           accountList.add(new Account(id,name,balance));
        }
        System.out.println(accountList);
    }

(4)添加一个用户数据

public static void main(String[] args) throws Exception {
        Properties prop = new Properties();
        prop.load(new FileInputStream("src/druid.properties"));
        DataSource dataSource = DruidDataSourceFactory.createDataSource(prop);
        Connection connection = dataSource.getConnection();
        String sql = "insert into account values(null,?,?)";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        Scanner scanner  = new Scanner(System.in);
        String name = scanner.next();
        Double balance = scanner.nextDouble();
        preparedStatement.setString(1,name);
        preparedStatement.setDouble(2,balance);
        int i = preparedStatement.executeUpdate();
        System.out.println(i == 1 ?"成功":"失败");
        connection.close();
    }

(5)根据id删除一个用户

 public static void main(String[] args) throws Exception {
        Properties prop = new Properties();
        prop.load(new FileInputStream("src/druid.properties"));
        DataSource dataSource = DruidDataSourceFactory.createDataSource(prop);
        Connection connection = dataSource.getConnection();
        String sql = "delete from account where id = ?";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        Scanner scanner  = new Scanner(System.in);
        Integer id = scanner.nextInt();
        preparedStatement.setInt(1,id);
        int i = preparedStatement.executeUpdate();
        System.out.println(i == 1 ?"成功":"失败");
        connection.close();
    }

(6)跟据id更新用户数据

public static void main(String[] args) throws Exception {
        Properties prop = new Properties();
        prop.load(new FileInputStream("src/druid.properties"));
        DataSource dataSource = DruidDataSourceFactory.createDataSource(prop);
        Connection connection = dataSource.getConnection();
        String sql = "update account set name = ? where id = ?";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        Scanner scanner  = new Scanner(System.in);
        String name = scanner.next();
        Integer id = scanner.nextInt();
        preparedStatement.setString(1,name);
        preparedStatement.setInt(2,id);
        int i = preparedStatement.executeUpdate();
        System.out.println(i == 1 ?"成功":"失败");
        connection.close();
    }

三、Maven


仓库方便管理。符合企业化开发。

1.pom.xml

依赖管理        dependencies/dependcy:依赖引入

依赖范围        scope配置范围        compile        test        provided        runtime        system        import

四、MyBatis


持久层框架;半成品软件;高效的框架;JavaEE三层架构:表现层、业务层、数据层

1.MyBatis快速入门

步骤:

        (1)创建表(2)创建模块,导入坐标(3)编写MyBatis核心配置文件  --> 替换连接信息 解决编码问题

        (4)编写SQL映射文件 --> 统一管理sql语句,解决编码问题

        (5)编码

                1.编写POJO类。2.加载核心配置文件,获取SqlSessionFactory 对象3.获取SqlSession对象,执行SQL语句。4.释放资源

导入MyBatis坐标 pom.xml

<dependency>
   <groupId>org.mybatis</groupId>
   <artifactId>mybatis</artifactId>
   <version>3.5.5</version>
</dependency>

编写MyBatis配置文件 在resourese/mybatis-config.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
<!--                mybatis的核心配置文件-->
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/jdbc?useSSL=false&amp;serverTimezone=UTC"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
<!--                mybatis的映射文件-->
        <mapper resource="UserMapper.xml"/>
    </mappers>
</configuration>

编写SQL映射文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<!--namespace:命名空间-->
<mapper namespace="test">
<!--com.itheima.pojo.Account是pojo类-->
    <select id="selectAccount" resultType="com.itheima.pojo.Account">
        select * from account;
    </select>
</mapper>

编码写POJO类

@Data
public class Account {
    //这里不用int是因为int有初始值
    private Integer id;
    private String name;
    private Double balance;
}

编写主类

public static void main(String[] args) throws Exception {
        //1.加载mybatis的核心配置文件,获取SqlSessionFactory
        String resource = "mybatis-config.xml";
        InputStream resourceAsStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory build = new SqlSessionFactoryBuilder().build(resourceAsStream);
        //2.获取SqlSession对象,用来执行sql
        SqlSession sqlSession = build.openSession();
        //3.执行sql
        List<Account> accounts = sqlSession.selectList("test.selectAccount");
        System.out.println(accounts);
        sqlSession.close();
    }

结构演示图

2.Mapper代理开发

(1)定义SQL映射文件同名的Mapper接口,并且将Mapper接口和SQL映射文件放置在同一个目录下

在java下创建com.itheima.mapper.UserMapper接口文件.方法名为SQL映射文件的ID

public interface UserMapper {
    //selectAll为mapper的id
    List<Account> selectAll();
}

在resourse下创建同名文件夹,将UseMapper文件放入使用这种方法创建文件夹不然会报错 com/itheima/mappper下放UserMapper.xml文件

(2)设置SQL映射文件的namespace属性为Mappper接口全限定名

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<!--namespace:命名空间-->
<mapper namespace="com.itheima.mapper.UserMapper">
    <select id="selectAll" resultType="com.itheima.pojo.Account">
        select * from account;
    </select>
</mapper>

(3)主代码

 public static void main(String[] args) throws Exception {
        //1.加载mybatis的核心配置文件,获取SqlSessionFactory
        String resource = "mybatis-config.xml";
        InputStream resourceAsStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory build = new SqlSessionFactoryBuilder().build(resourceAsStream);
        //2.获取SqlSession对象,用来执行sql
        SqlSession sqlSession = build.openSession();
        //3.执行sql
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        List<Account> accounts = mapper.selectAll();
        System.out.println(accounts);
        sqlSession.close();
    }

3.MyBatis核心配置文件---mybais-config.xml

类型别名:<typeAliases><package name="com.itheima.pojo"></typeAliases>

4.案例

数据库表的字段名称和实体类的属性名称不一样则不能自动封装数据

<mapper namespace="com.itheima.mapper.UserMapper">
    <resultMap id="accountResultMap" type="com.itheima.pojo.Account">
<!--        id:为主键-->
        <id column="id" property="id"></id>
<!--        result为一般字段 column为列名 property为实体类的属性名-->
        <result column="user_name" property="name" />
    </resultMap>

    <select id="selectAll" resultMap="accountResultMap">
        select * from account;
    </select>
</mapper>

参数注入sql语句,使用        #{id}:这个可以防止sql注入,使用?号占位(推荐使用)        ${id}:直接插入不推荐使用        

        注意:字符问题使用转义字符

#mapper接口
public interface UserMapper {
    List<Account> selectById(int id);
}
#mapper映射文件
<mapper namespace="com.itheima.mapper.UserMapper">
    <select id="selectById" resultType="com.itheima.pojo.Account">
        select * from account where id = #{id};
    </select>
</mapper>

SQL语句设置多个参数

<mapper namespace="com.itheima.mapper.UserMapper">
    <select id="selectById" resultType="com.itheima.pojo.Account">
        select * from account where id = #{id} and name like #{name};
    </select>
</mapper>

        (1)散装参数:需要使用@Param("SQL中的参数占位符名称")

public interface UserMapper {
    List<Account> selectById(@Param("id") int id,@Param("name") String name);
}

        (2)实体类封装参数:只要保证sql中的参数名和实体类对应上,即可设置成功

public interface UserMapper {
    List<Account> selectById(Account account);
}

        (3)map集合:只需要保证SQL中的参数名和map集合的键的名称对应上,即可设置成功

public interface UserMapper {
    List<Account> selectById(Map map);
}

动态条件查询

<mapper namespace="com.itheima.mapper.UserMapper">
    <select id="selectById" resultType="com.itheima.pojo.Account">
        select * from account where 1 = 1
        <if test="id != null and id != ''">
            and id = #{id}
        </if>
        <if test="name != null and name != ''">
            and name like #{name}
        </if>
    </select>
</mapper>

5.MyBatis事务

openSession():默认开启事务,进行增删改操作需要使用sqlSession.commit();手动提交

openSession(true):可以设置为自动提交

6.返回添加数据的主键

<insert id="addUser" useGeneratedKeys="true" keyProperty="id">
        insert into account values (#{name},#{balance})
    </insert>

7.注解开发

查询:@Select        添加:@Insert        需改:@Update        删除:@Delete        提示:注解完成简单功能,配置文件完成复杂内容

public interface UserMapper {
    @Select("select * from account where id = #{id}")
    Account selectAccountById(int id);
}

五、HTML、CSS、Vue、Axios、Element_ui


        已学、笔记在宁一篇文档。前端技术,负责页面展示。

六、HTTP


1.HTTP简介

        Hyper Text Transfer protoclo,超文本传输协议,规定了浏览器和服务器之间的数据传输规则

        特点:面向连接安全 ,一次响应对应一次请求。速度快,请求间不能共享数据。

2.HTTP-请求数据格式

        请求行、请求头、请求体

3.HTTP-响应数据格式

        相应行、响应头、响应体        400:响应中        200:成功        300:重定向        400:客户端错误        500:服务器错误

七、Tomcat


        web服务器软件,

1.修改服务端口

        在tomcat目录下的conf\service.xml里面修改

八、Servlet


1.servlet快速入门

创建web项目,导入Servlet依赖坐标---注意jdk版本为1.8哦

dependency>
   <groupId>javax.servlet</groupId>
   <artifactId>javax.servlet-api</artifactId>
   <version>3.1.0</version>
   <scope>provided</scope>
</dependency>

创建:定义一个类,实现Servlet接口,并重写接口中所有方法,并在service方法中输入一句话

配置:在类上使用@WebServlet注解,配置该Servlet的访问路径

访问:启动Tomcat,浏览器输入URL,访问该Servlet

@WebServlet("/demo1")
public class ServletDemo1 implements Servlet {
    public void init(ServletConfig servletConfig) throws ServletException {

    }

    public ServletConfig getServletConfig() {
        return null;
    }

    public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
        System.out.println("tomcat快速入门");
    }

    public String getServletInfo() {
        return null;
    }

    public void destroy() {

    }
}

2. Servlet的生命周期

@WebService(urlPatterns="/demo",loadOnStartup = 1)   loadOnStartup:负整数第一次访问创建,0或正整数:启动时创建,数字越小优先级越高

Servlet周期:加载和实例化        初始化:init()方法,只调用一次        请求处理:service()访问就触发        服务终止:destroy()垃圾回收

Servlet其他方法(不常用):获取ServletConfig对象 ServletConfig getServletConfig()        获取Servlet信息   String getServletInfo()

3.Servlet体系结构

Servlet(Servlet体系结构根接口)<====GenericServlet(Servlet抽象实现类)<====HttpServlet(对HTTP协议封装的Servlet实现类)

我们将来开发B/S架构的web项目,都是针对HTTP协议,所以我们自定义Servlet,会继承HttpServlet

@WebServlet("/demo2")
public class Demo2Controller 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...");
    }
}

4.urlPattern配置

一个Servlet可以匹配多个urlPattern:@WebServlet(urlPatterns={"/demo1","/demo2"})

urlPattern匹配规则:

        精确匹配:WebServlet("/user/select")

        目录匹配:WebServlet("/user/*")

        扩展名匹配:WebServlet("*.do")

        任意匹配:WebServlet("/") 或 WebServlet("/*")

5.XML配置Servlet(了解)

Servlet从3.0版本之后开始支持使用注解配置(@WebServlet),3.0版本前只支持XML的配置方式

        步骤:1.编写Servlet类 2.在web.xml中配置Servlet

        xml文件在webapp/WEB-INF/web.xml

<web-app>
  <display-name>Archetype Created Web Application</display-name>
  <servlet>
    <servlet-name>demo3</servlet-name>
    <servlet-class>com.itheima.controller.Demo3Controller</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>demo3</servlet-name>
    <url-pattern>/demo3</url-pattern>
  </servlet-mapping>
</web-app>

九、Request


1.Request获取请求数据

请求行:

        String getMethod():获取请求方式;GET        

        String getContextPath():获取虚拟牡蛎:/requset-demo

        StringBuffer getRequesrURL():获取URL(统一资源定位符):http://localhost/request-demo/req1

        String getRequstURL():获取URL(统一资源定位标识符):requset-demo/req1

        String getQieryString():获取请求参数(GET方式):username=zhangsan&password=123

请求头:String getHeader(String name):根据请求头名称,获取值

请求体:

        ServletInputStream getInputStream():获取字节输入流

        BufferedReader getReader():获取字符输入流

获取参数的通用方式:

        Map<String,String[]> getParamterMaper():获取所有参数Map集合

        String[] getParameterValues(String name):根据名称获取参数值(数组)(常用)

        String getParametr(String name):根据名称获取参数值(单个值)

在doPost里面调用doGet方法:this.doGet(request,response)

2.请求参数中文乱码处理

设置:request.setCharacterEncoding("UTF-8")    POST请求的

GET在Tomcat8之后他自己解决了

3.Request请求转发

实现方式:request.getRequestDispatcher("资源B路径").forward(req,resp);

请求转发资源间共享数据:使用Requst对象

        void setAttribute(String name,Object p):存储数据到request域中

        Object getAttribute(String name):根据key,获取值

        void removeAttribute(String name):根据key,删除该键值对

十、Response


1.设置Response

响应行:void setStatus(int sc):设置响应状态码

响应头:void setHeader(String name,String value):设置响应头键值对

响应体:printWriter getWriter():获取字符输出流

ServletOutPutStream getOuptPutStream():获取字节输出流

2.Response-重定向

实现方式一:response.setStatus(302);        response.setHeader("location","资源B的路径"); 

实现方式二:response.sendRedirect("资源B的路径");

3.路径问题

4. Response响应字符数据

response.setContentType("text/html;charset=utf-8")设置编码        PrintWriter writer = resp.getWriter();        writer,writer("aaa")    

5.Response响应字节数据

使用:ServletOutPutSteam outputStream = resp.getOutPutStream();        outputStream.write(字节数据)

IOUtils工具类使用

        1.导入坐标:

<dependency>
      <groupId>commons-io</groupId>
      <artifactId>commons-io</artifactId>
      <version>2.6</version>
</dependency>

        2.使用:IOUtils.copy(输入流,输出流);

6、response、request登录、注册案例

环境准备:

        pom.xml:

  <dependencies>
    <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.23</version>
    </dependency>
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>druid</artifactId>
      <version>1.1.12</version>
    </dependency>
    <dependency>
      <groupId>org.projectlombok</groupId>
      <artifactId>lombok</artifactId>
      <version>RELEASE</version>
      <scope>compile</scope>
    </dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>3.1.0</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>org.projectlombok</groupId>
      <artifactId>lombok</artifactId>
      <version>RELEASE</version>
      <scope>compile</scope>
    </dependency>
  </dependencies>

        在resource下添加mybatis-config.xml配置文件------知识点包扫描mapper

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
<!--                mybatis的核心配置文件-->
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/jdbc?useSSL=false&amp;serverTimezone=UTC"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
<!--        包扫描mapper-->
        <package name="com.itheima.mapper"/>
    </mappers>
</configuration>

        java下新建com.itheima.pojo.Account实体类

@Data
public class Account {
    //这里不用int是因为int有初始值
    private Integer id;
    private String name;
    private Double balance;
}

登录功能

        在java下创建com.itheima.mapper.UserMapper接口

public interface UserMapper {
    @Select("select * from account where name = #{name} and balance = #{balance}")
    Account login(@Param("name") String name,@Param("balance") String balance);
}

        在java下创建com.itheima.LoginController用于登录

@WebServlet("/login")
public class LoginController extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {}

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取请求数据
        req.setCharacterEncoding("UTF-8");
        String name = req.getParameter("name");
        String balance = req.getParameter("balance");

        //mybatis获取数据库数据
        String resource = "mybatis-config.xml";
        InputStream resourceAsStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory build = new SqlSessionFactoryBuilder().build(resourceAsStream);
        //2.获取SqlSession对象,用来执行sql
        SqlSession sqlSession = build.openSession();
        //3.执行sql
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        Account account = mapper.login(name,balance);

        resp.setContentType("text/html;charset=utf-8");
        resp.setStatus(201);
        PrintWriter writer = resp.getWriter();
        if(account != null){
            writer.write("登录成功");
        }else{
            writer.write("登陆失败");
        }
    }
}

        前端页面代码在webapp下创建login.html

<form action="/login" method="post">
    <input type="text" name="name" placeholder="请输入账号">
    <input type="password" name="balance" placeholder="请输入密码">
    <input type="submit" value="登录">
</form>

注册功能:------一定要注意commit要提交事务否则不会更新数据库

        mapper映射文件

@Insert("insert into account values(null,#{name},#{balance})")
int register(@Param("name") String name,@Param("balance") int balance);

        RegisterController文件

@WebServlet("/register")
public class RegisterController extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {}

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取请求数据
        req.setCharacterEncoding("UTF-8");
        String name = req.getParameter("name");
        Integer balance = Integer.parseInt(req.getParameter("balance"));

        //mybatis获取数据库数据
        String resource = "mybatis-config.xml";
        InputStream resourceAsStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory build = new SqlSessionFactoryBuilder().build(resourceAsStream);
        //2.获取SqlSession对象,用来执行sql
        SqlSession sqlSession = build.openSession(true);
        //3.执行sql
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        int len = mapper.register(name,balance);

        resp.setContentType("text/html;charset=utf-8");
        resp.setStatus(201);
        PrintWriter writer = resp.getWriter();
        if(len != 0){
            writer.write("注册成功");
        }else{
            writer.write("注册失败");
        }
    }
}

        前端注册页面代码

<form action="/register" method="post">
    <input type="text" name="name" placeholder="请输入账号">
    <input type="password" name="balance" placeholder="请输入密码">
    <input type="submit" value="注册">
</form>

项目----文件目录展示

十一、JSP


        JSP技术已经过时,现在学习也只是为了维护老项目

1.JSP快速入门

导入坐标

<dependency>
  <groupId>javax.servlet.jsp</groupId>
  <artifactId>jsp-api</artifactId>
  <version>2.2</version>
  <scope>provided</scope>
</dependency>

创建JSP文件        编写HTML标签 和 Java代码

<body>
<h1>Hello World</h1>
<% System.out.println("jsp hello~");%>
</body>

2.JSP脚本分类

<%...%>:内容会直接放在_jspService()方法之中

<%=...%>:内容会放到out.print()中,作为out.prin()的参数

<%!...%>:内容会放到_jspService()方法之外,被类直接包含

3.案例使用JSP展示Account用户数据

        报错不用管没事~,软件问题

<%@ page import="java.util.ArrayList" %>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ page import="com.itheima.pojo.Account" %><%
    ArrayList<Account> accounts = new ArrayList<>();
    accounts.add(new Account(1,"张三",3000.00));
    accounts.add(new Account(2,"李四",4000.00));
    accounts.add(new Account(3,"王五",4500.00));
%>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>首页</title>
</head>
<body>
<table>
    <tr><th>ID</th><th>姓名</th><th>工资</th></tr>
    <%
        for (int i = 0 ; i < accounts.size(); i ++){
    %>
    <tr>
        <td><%= accounts.get(i).getId() %></td>
        <td><%= accounts.get(i).getName() %></td>
        <td><%= accounts.get(i).getBalance() %></td>
    </tr>
    <%
        }
    %>
</table>
</body>
</html>

4.EL表达式

语法:${expression}  获取存在setAttribute域里面的值

index.jsp代码

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ page isELIgnored="false" %>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>首页</title>
</head>
<body>
    ${accounts}
</body>
</html>

请求代码:注意要先访问请求页面,让他跳转到index.jsp才能有数据        localhost/demo2

@WebServlet("/demo2")
public class Demo2Controller extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ArrayList<Account> accounts = new ArrayList<>();
        accounts.add(new Account(1,"张三",3000.00));
        accounts.add(new Account(2,"李四",4000.00));
        accounts.add(new Account(3,"王五",4500.00));

        req.setAttribute("accounts",accounts);

        req.getRequestDispatcher("/index.jsp").forward(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("POST...");
    }
}

5.JSTL标签

导入坐标

<dependency>
  <groupId>jstl</groupId>
  <artifactId>jstl</artifactId>
  <version>1.2</version>
</dependency>
<dependency>
  <groupId>taglibs</groupId>
  <artifactId>standard</artifactId>
  <version>1.1.2</version>
</dependency>

在JSP页面上引入JSTL标签库

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

使用

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ page isELIgnored="false" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>首页</title>
</head>
<body>
<c:if test="true">
    <h1>我是对的时候展示</h1>
</c:if>
<c:if test="false">
    <h1>我是错的时候展示</h1>
</c:if>
</body>
</html>

上图使用setAttribute跳转,显示

@WebServlet("/demo2")
public class Demo2Controller extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setAttribute("status",1);
        req.getRequestDispatcher("/index.jsp").forward(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("POST...");
    }
}

index.jsp文件

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ page isELIgnored="false" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>首页</title>
</head>
<body>
<c:if test="${status == 1}">
    <h1>1</h1>
</c:if>
<c:if test="${status == 0}">
    <h1>0</h1>
</c:if>
</body>
</html>

<c:forEach>:相当于for循环-----------数据依旧使用setAttribute和forward跳转传递

        items:被遍历的容器

        var:遍历产生的临时变量

<%@ page import="com.itheima.pojo.Account" %>
<%@ page import="java.util.ArrayList" %>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ page isELIgnored="false" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>首页</title>
</head>
<body>
    <table>
        <tr><th>ID</th><th>姓名</th><th>工资</th></tr>
        <c:forEach items="${accounts}" var="user">
            <td>${user.getId()}</td>
            <td>${user.getName()}</td>
            <td>${user.getBalance()}</td>
        </c:forEach>
    </table>
</body>
</html>

6.MVC模式

MVC是一种分层开发的模式,其中    M:Model,业务模型,处理业务   V:view,视图,界面展示     C:Controller,控制器,处理请求,调用模型和视图

优点:职责单一,互不影响,有利于分工协作,有利于组件重用 

7.三层模型

数据访问层:对数据库的SRUD基本操作

业务逻辑层:对业务逻辑进行封装,组合数据访问层层中基本功能,形成复杂的业务逻辑功能

表现层:接收请求,封装数据,调用业务逻辑层,响应数据

8.案例----Account增删改查 步骤

创建新的模块,引入坐标

        mybatis        mysql        servlet        jsp        坐标

创建三层架构的包结构 web         service     pojo        dao        mapper

创建数据库表、创建实体类   Account

MyBatis基础环境:mybatis-config.xml        BrandMapper.xml        BrandMapper接口

十二、会话跟踪技术


        多次请求之间共享数据

1.客户端会话跟踪技术:Cookie

cookie基本使用:将数据保存在客户端,以后每次请求都携带Cookie数据进行访问

        创建Cookie对象,设置数据:Cookie cookie  =  new Cookie("key","value");

        发送Cookie客户端:使用response对象:response.addCookie(cookie);

        获取客户端携带的所有Cookie,使用request对象:Cookie[] cookies = request.getCookies();

        遍历数组,获取每一个Cookie对象:for

        使用Cookie对象方法获取数据:cookie.getName();        cookie.getValue();

使用细节

        cookie设置存活时间  setMaxAge(int seconds):正数,到时间销毁。负数:浏览器关闭就删除。零:删除对应Cookie

2.服务端会话跟踪技术:Session

将数据保存到服务端

        获取Session对象 HttpSession session = request.getSession();

        void setAttribute(String name,Object o):存储数据到session域中

        Object getAttribute(String name):根据key,获取值

        void removeAttribute(String name):根据key,删除键值对

使用细节

        默认情况下,无操作,30分钟自动销毁。在webapp下的web.xml中配置

<session-config>
    <session-timeout>30</session-timeout>
</session-config>

        调用Session对象的invalidate()方法销毁

十三、Filter


概念:Filter表示过滤器,是JavaWeb三大组件(Servlet,Filter,Listener)之一、

过滤器可以把资源的请求拦截下来,从而实现一些特殊的功能。

过滤器一般完成一些通用的操作,比如:权限控制、统一编码处理,敏感字符处理等等...

1.filter快速入门

定义类,实现Filter接口,并重写其所有方法

public class FilerDemo implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

    }

    @Override
    public void destroy() {

    }
}

配置Filter拦击资源的路径:在类上定义@WebFilter注解

@WebFilter("/*")
public class FilerDemo implements Filter {

在doFilter房中输出一句话并放行

@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
      System.out.println("hello filter");
      filterChain.doFilter(servletRequest,servletResponse);
}

2.Filter访问路径

@WebFilter("/*")

        拦截具体的资源:/index.jsp:只有访问index.jsp时才会被拦截。

        目录拦截:/user/*:访问/usr下的所有资源,都会被拦截

        后缀名拦截:*.jsp:访问后缀名为jsp的资源都会被拦截

        拦截所有:/*:访问所有资源,都会被拦截

十四、Listener(不常用了)


JavaWeb撒表达组件之一

基本使用:继承ServletConextListener再加上@WebListener注解。里面的contextInitalized方法负责加载资源。contextDestroyed方法释放资源

十五、AJAX-AXIOS


异步的Javascript        和        XML        前端技术略过

十六、JSON


1.数据格式

var user = {name:"张三",age:18}

2.Java对象转换为JSON格式

Fastjson是阿里巴巴提供的一个Java语言编写的高性能功能完善的JSON库,是目前Java语言中最快的JSON库,可以实现Java对象和JSON对象相互转换

导入坐标

<dependency>
   <groupId>com.alibaba</groupId>
   <artifactId>fastjson</artifactId>
   <version>1.2.76</version>
</dependency>

Java对象转JSON:String jsonStr = JSON.toJSONString(obj)

JSON字符串转Java对象:User user = JSON.parseObject(jsonStr,User.class);

3.案例

直接总结知识点:返回数据使用

resp.getWriter().write(JSON.toJSONString(accounts));
  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值