JAVA-WEB学习笔记(包含基本组件)

Java Web的三大组件是

Filter、Servlet和Listener

Get和Post请求形式区别

image-20240608112700835

请求和响应

DispatcherServlet(类) :核心/前端控制器

解析前端信息并封装到:HttpServletRequest

响应前端并封装到:HttpServletReponse

image-20240609084749708

请求

@RestController作用(类 Mapper层)

一、在Spring中@RestController的作用等同于@Controller + @ResponseBody。

所以想要理解@RestController注解就要先了解@Controller和@ResponseBody注解。

二、@Controller注解

在一个类上添加@Controller注解,表明了这个类是一个控制器类。这里省略对Controller注解的说明了。

三、@ResponseBody注解

@ResponseBody可以将对象中的Result对象转为json数据格式返回给前端。

参数

在集合中需要使用@RequestPara注解:将请求参数绑定到方法的参数上。

image-20240609112400081

@RestController
public class hello {
    @RequestMapping("/hello")
    public String hello() {
        System.*out*.println("hello");
        return "hello";
    }


    @RequestMapping("/simple")
    public String simple1(@RequestParam(name = "name",required = false) String username, Integer age){  //name设置不是必须的
        System.*out*.println("name:"+username+",age:"+age);
        return "OK";
    }
    @RequestMapping("/simple1")
    public String simple2(User user) {
        System.*out*.println(user);
        return "OK";
    }
    @RequestMapping("/simple2")
    public String arrayParam(String[] hobby) {
        System.*out*.println(Arrays.*toString*(hobby));
        return "OK";
    }


    //列表参数
    @RequestMapping("/simple3")
    public String listParam(@RequestParam List<String> hobby) {
        System.*out*.println(hobby);

        return "OK";
    }
    //日期时间参数
    @RequestMapping("/simple4")
    public String dataParam(@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime localDateTime) {
        System.*out*.println(localDateTime);
        return "OK";
    }

    //json参数
    @RequestMapping("jsonParam")
    public String jsonParam(@RequestBody User user){
        System.*out*.println(user);
        return "OK";
    }

    @RequestMapping("/path/{id}/{name}")
    public String pathParam(@PathVariable Integer id,@PathVariable String name){
        System.*out*.println(id+'\n'+name);
        return "Ok";
    }

}

响应

image-20240609114748518

image-20240609114718504

以下要进行分层解耦:

image-20240609202540359

image-20240609201453739

image-20240609202437296

分层解耦IOC/DI

image-20240609204700158

image-20240609205608059

image-20240609220219115

数据库

Sql分类

image-20240609220602508

image-20240609220906844

数据库约束

image-20240609221906817

基本

数据类型

image-20240609222131587

image-20240609222608305

DDL

建表语句:show create table 表名;

image-20240609223245030

DML

image-20240609223541180

date_time:可以使用now()函数获取当前时间

image-20240609224036268

image-20240609224212984

DQL

image-20240609224339261

基本查询

image-20240609224423758

条件查询

image-20240609224647535

聚合函数

image-20240609224808199

分组查询

image-20240609225433070

排序查询

image-20240611092146587

分页查询

image-20240611092501210

image-20240611093924153

表达式

if(gender = 1,‘男’,‘女’)别名

(case job when 1 then ‘班主任’ when 2 then ‘讲师’ else ‘未分配职位’ end) 别名

image-20240611093815978

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

外键约束

image-20240611094340626

已经不推荐使用物理外键,而是从代码上进行逻辑外键的构建!

多对多

表连接

内连接

image-20240611210022424

image-20240611210652144

外连接

image-20240611210801911

image-20240611211119660

子查询

标量子查询

image-20240611211619258

列子查询

image-20240611211740161

行子查询

image-20240611211954177

表子查询

image-20240611212159925

事务

原子性

image-20240611221033274

四大特性:

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

image-20240611221118531

索引

image-20240611222428418

image-20240611222524086

image-20240611223108587

image-20240611223125747

Mybatis

是一款优秀的持久层框架,用于简化JDBC的开发。

image-20240611224357272

image-20240612105140532

image-20240612105153112

JDBC与Mybatis

image-20240612131744546

数据库连接池

image-20240612135642319

image-20240612135856629

lombok

image-20240612140524452

基本操作

删除

image-20240612144150451

预编译优势

image-20240612150417878

image-20240612145209047

安全#{}:预编译
不安全${}:拼接

image-20240612150253459

插入(新增)

image-20240612151053743

新增的主键返回

image-20240612151327896

image-20240612151622927

修改(更新)

image-20240612153021103

查询(根据ID)

封装问题:

image-20240612153324362

解决:

1.起别名与实体类属性一致就行

image-20240612153413562

  1. 通过@Results,@Results注解手动封装(繁琐)

image-20240612153848883

3.开启mybatis的驼峰命名自动映射开关(严格命名:推荐)

image-20240612154208925

条件查询

第一个不安全

image-20240612155207764

上边使用到了concat拼接函数;

image-20240612155325018

XML映射文件

高度规范

image-20240612160058602

image-20240612162950049

image-20240612163317848

动态SQL

三个标签

image-20240612163642265

image-20240612164031715

< where >标签会自动排除and

image-20240612164148523

< set >自动排除多余的”,“

image-20240612170337253

image-20240612170441178

image-20240612171116541

image-20240612171450549

image-20240612171517641

案例

开发规范

image-20240612224214409

image-20240612224647649

查询部门

image-20240613150419440

@slfj4作用(方法 Mapper层)

自动生成记录日志对象,then log.info(“查询全部部门数据”);

image-20240613151754558

@RequestMapping @GetMapping(方法 Mapper层)

@RequestMapping(“/depts”):映射到/dept前端地址:localhost:8080/depts

@GetMapping(“/depts”):限制请求方式为GET

@Autowired(方法)

依赖注入

删除部门

@PathVariable

路径参数注解

image-20240613170405659

image-20240613170503936

增加部门

@RequestBody

将json数据封装到实体类中

image-20240613173500496

image-20240613175337804

分页查询条件

image-20240618092140232

映射文件中的sql语句不要加分号“;”

类型是LocalDate不是LocalDateTime

批量删除

image-20240618093249302

(1,2,3)和

foreach是等效的

文件上传

image-20240618105213398

image-20240618105338743

image-20240618152240780

阿里云配置:

image-20240618160827929

yml和yaml配置文件

image-20240618161103498

只支持yml/yaml和properties配置文件

基本语法

image-20240618161215990

数据格式

image-20240618161402791

@ConfigurationProperties注解和@Value

image-20240618180845701

登录校验

统一拦截

image-20240618203525730

会话

image-20240618203932737

三种会话跟踪技术对比
cookie

image-20240618205100617

Session和令牌

image-20240618205922084

JWT令牌(登录校验)

Json Web Token

image-20240618210453499

JWT-生成

@Test
public void testGenJWT(){
    Map<String,Object> claims = new HashMap<>();
    claims.put("id",1);
    claims.put("name","tom");
    String jwt = Jwts.*builder*()
            .signWith(SignatureAlgorithm.*HS256*,"ICEi")//签名算法:至少4个字符
            .setClaims(claims)//自定义内容(载荷)
            .setExpiration(new Date(System.*currentTimeMillis*() + 3600 * 1000))
            .compact();//设置有效期为1H
    System.*out*.println(jwt);
}

//解码
@Test
    public void testParseJwt(){
        Claims claims = Jwts.parser()
                .setSigningKey("ICEi")//指定签名密钥             		.parseClaimsJws("eyJhbGciOiJIUzI1NiJ9.eyJuYW1lIjoidG9tIiwiaWQiOjEsImV4cCI6MTcxODcyMTM2N30._sXspQGLMg6tzCyl4AZeOiwGwnliu-81pETRVndXz_Y")
                .getBody();
        System.out.println(claims);
    }

image-20240618214002309

过滤器(Filter 拦截)

image-20240618215658916

入门

image-20240618215852669

拦截实现

@WebFilter(urlPatterns = "/*")
public class Demofilter implements Filter {

   @Override//初始化方法,只调用一次
   public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("Init初始化发法执行!");
    }

    @Override//拦截到请求后调用,调用多次
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws 	IOException, ServletException {
        System.out.println("拦截到了请求!");
        //放行
        filterChain.doFilter(servletRequest,servletResponse);
    }

    @Override//只调用一次
    public void destroy() {
        System.*out*.println("销毁!");
    }
}

image-20240618221058508

详解

image-20240618221600089

过滤器链

按类名首字母进行排序

image-20240618222146117image-20240618221617446

image-20240618222211721

Filter登录校验过滤

image-20240618222509094

image-20240618222607571

Login过滤

@Slf4j
@WebFilter
public class LoginCheckFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;
        //1获取请求url
        String url = req.getRequestURL().toString();

        //2判断请求头是否包含login
        if (url.contains("login")){
            *log*.info("登录login放行...");
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }
        //3获取请求头中的令牌
        String jwt = req.getHeader("token");
        //4判断令牌是否存在
        if (!StringUtils.*hasLength*(jwt)){
            *log*.info("token为空,令牌不存在!");
            Result error = Result.*error*("NOT_LOGIN");
            String nologin = JSONObject.*toJSONString*(error);
            resp.getWriter().write(nologin);
            return;
        }
        //5解析token 失败返回(未登录)
        try {
            JwtUtils.*parseJWT*(jwt);
        }catch (Exception e){
            e.printStackTrace();
            *log*.info("令牌解析失败,返回未登录信息!");
            Result error = Result.*error*("NOT_LOGIN");
            String nologin = JSONObject.*toJSONString*(error);
            resp.getWriter().write(nologin);
            return;
        }
        //6放行
        filterChain.doFilter(servletRequest,servletResponse);
    }
}

Interceptor拦截器

image-20240619190314641

image-20240619190517561

拦截路径

image-20240619191640047

执行流程

image-20240619192029281

image-20240619192540158

登录校验

image-20240619192630091

异常处理

image-20240619195654268

事务

image-20240619203314652

@Transactional

image-20240619203350908

image-20240619205128219

事务传播行为

image-20240619212018128

image-20240619215817474

image-20240619215902656

AOP(面向切面编程)

image-20240619220048077

image-20240619220226734

快速入门

image-20240619220955978

image-20240619221816174

AOP核心概念

image-20240619222322491

image-20240620110417400

通知顺序

image-20240620112033687

切入点表达式(使用execution())

image-20240620112117557

@PointCut("execution(访问修饰符? 返回值 包名.类名.?方法名(方法参数) throws 异常?)")

@PointCut("execution(public void com.example.sevice.DeptService.Delete(java.lang.Integer))")

image-20240620112905652

语法

image-20240620113557908

根据注解切入点表达式(使用@annotation)

image-20240620113922532

image-20240620114005794

image-20240620114015143

Test运行方法

image-20240620114024341

image-20240620114047737

连接点

image-20240620114400990

image-20240620114406676

案例

image-20240620143226635

@Slf4j
@Component
@Aspect
public class LogAspect {

    @Autowired
    HttpServletRequest request;

    @Autowired
    OperateLogMapper operateLogMapper;

    @Around("@annotation(com.example.anno.Log)")
    public Object recordLod(ProceedingJoinPoint joinPoint) throws Throwable {

        //获取id
        String jwt = request.getHeader("token");
        Claims claims = JwtUtils.*parseJWT*(jwt);
        Integer operateUser = (Integer) claims.get("id");

        //操作时间
        LocalDateTime operateTime = LocalDateTime.*now*();

        //操作类名
        String className = joinPoint.getTarget().getClass().getName();

        //操作方法名
        String methodName = joinPoint.getSignature().getName();

        //操作方法参数
        Object[] args = joinPoint.getArgs();
        String methodParams = Arrays.*toString*(args);

        long begin = System.*currentTimeMillis*();

        //使用原始目标方法运行
        Object result  = joinPoint.proceed();

        long end = System.*currentTimeMillis*();

        //方法返回值
        String returnValue = JSONObject.*toJSONString*(result);

        //方法耗时
        Long costTime = end -begin;

        //记录操作日志
        OperateLog operateLog = new OperateLog(null,operateUser,operateTime,className,methodName,methodParams,returnValue,costTime);
        operateLogMapper.insert(operateLog);

        *log*.info("AOP操作日志:{}",operateLog);

        return result;
    }

}

springboot配置文件

优先级

image-20240620143428847

其他配置

image-20240620143511491

image-20240620143923509

Bean管理

获取bean对象

image-20240620144713278

image-20240620144747689

bean的作用域

image-20240620144858530

image-20240620144905931

@Lazy

延迟初始化:容器启动时初始化(构造函数)

image-20240620145203278

第三方bean的配置

image-20240620160437647

@AliasFor(“”)注解

别名

Springboot原理

起步依赖

image-20240620162237218

自动配置(最核心)

自动配置得原理(高频)

@ComponentScan默认只扫描当前项目包

方案

image-20240620165116419

image-20240620165337811

image-20240620170240771

源码跟踪

image-20240620171120662

image-20240620171831917

@ConditionalOnMissingBean条件注解

image-20240620171954833

总结

image-20240620173958699

image-20240620182149552

总结

image-20240620182617855

Maven高级

image-20240620182907234

分模块

image-20240620183129278

image-20240620190231665

继承

image-20240620190340644

image-20240620190453479

三种打包方式

image-20240620190619985

image-20240620191015103

image-20240620212221727

POM步骤

1.

image-20240620212251246

2.

image-20240620212305431

3.

image-20240620212330849

image-20240620212416524

版本锁定

image-20240620214901188

自定义属性

image-20240620215345090

image-20240620215331178

聚合

image-20240620221453006

Maven私服

image-20240620221851600

资源上传下载

image-20240620222153638

步骤1

image-20240620222350202

步骤2

image-20240620222357641

步骤3

image-20240620222445843

私服配置说明

访问私服:http://192.168.150.101:8081

访问密码:admin/admin

使用私服,需要在maven的settings.xml配置文件中,做如下配置:

  1. 需要在 servers 标签中,配置访问私服的个人凭证(访问的用户名和密码)

    <server>
        <id>maven-releases</id>
        <username>admin</username>
        <password>admin</password>
    </server>
        
    <server>
        <id>maven-snapshots</id>
        <username>admin</username>
        <password>admin</password>
    </server>
    
  2. mirrors 中只配置我们自己私服的连接地址(如果之前配置过阿里云,需要直接替换掉)

    <mirror>
        <id>maven-public</id>
        <mirrorOf>*</mirrorOf>
        <url>http://192.168.150.101:8081/repository/maven-public/</url>
    </mirror>
    
  3. 需要在 profiles 中,增加如下配置,来指定snapshot快照版本的依赖,依然允许使用

    <profile>
        <id>allow-snapshots</id>
            <activation>
            	<activeByDefault>true</activeByDefault>
            </activation>
        <repositories>
            <repository>
                <id>maven-public</id>
                <url>http://192.168.150.101:8081/repository/maven-public/</url>
                <releases>
                	<enabled>true</enabled>
                </releases>
                <snapshots>
                	<enabled>true</enabled>
                </snapshots>
            </repository>
        </repositories>
    </profile>
    
  4. 如果需要上传自己的项目到私服上,需要在项目的pom.xml文件中,增加如下配置,来配置项目发布的地址(也就是私服的地址)

    <distributionManagement>
        <!-- release版本的发布地址 -->
        <repository>
            <id>maven-releases</id>
            <url>http://192.168.150.101:8081/repository/maven-releases/</url>
        </repository>
        
        <!-- snapshot版本的发布地址 -->
        <snapshotRepository>
            <id>maven-snapshots</id>
            <url>http://192.168.150.101:8081/repository/maven-snapshots/</url>
        </snapshotRepository>
    </distributionManagement>
    
  5. 发布项目,直接运行 deploy 生命周期即可 (发布时,建议跳过单元测试)

启动本地私服

  1. 解压: apache-maven-nexus.zip

  2. 进入目录: apache-maven-nexus\nexus-3.39.0-01\bin

  3. 启动服务:双击 start.bat

  4. 访问服务:localhost:8081

  5. 私服配置说明:将上述配置私服信息的 192.168.150.101 改为 localhost

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值