Java basics (review and arrangement)

8 basic data types ( others are reference types )

byte occupies 1 byte range -128~127

short occupies 2 bytes: -32768~32767

int occupies 4 bytes

long occupies 8 bytes, for example: 30L, followed by L

float occupies 4 bytes, followed by F

double occupies 8 bytes

char occupies 2 bytes

boolean occupies one place, only true and false

A bit is the smallest unit of internal storage in a computer

Byte (byte) is the basic unit of processing data in a computer, and it is customary to use B to represent it

1B = 8bit

Characters: Refers to letters, numbers, words and symbols used by computers

1KB = 1024B

1MB = 1024KB

1024M=1G

Encoding Unicode 2 bytes 0-65536 Excel 2's 16th row

Instance variables, belonging to objects

Class variables, static, come out with the class and are destroyed together

Except for basic types, the rest are null by default

0, 0.00, Boolean type, default false

Constant: uppercase + underscore

Local variable name: first letter lowercase + hump principle

Class name: capitalized first letter + hump principle

Method name: lowercase first letter and camel case principle

Ternary operator

public class Demo01 {
    
    
    public static void main(String[] args) {
    
    
        int score = 50 ;
        String s = score<60 ? "不及格":"及格";
        System.out.println(s);

    }
}
//不及格

for loop:

  • The initialization step is performed first, a type can be declared, but one or more loop control variables can be initialized, or an empty statement

  • Then, check the value of the Boolean expression, if it is true, the loop body is executed; if it is false, the loop terminates, and the statement after the loop body starts to be executed

  • Check boolean expressions again. Loop through the above process

// 死循环
for(;;;){
    
    
    
}

Constructor essence

A constructor is essentially a method

1. Using the new keyword (instantiate an object), the essence is to call the constructor

2. Used to initialize the value

classes and objects

  • classes and objects

    A class is a template and an object is a concrete instance

  • method

    ​ Definition and call

  • object reference

    ​ Reference type, basic type (8)

    ​ Objects are manipulated by reference: stack -> heap

  • properties of the object

    ​ field, member variable

    ​ Default initialization:

    ​Number: 0 0.00

    ​ char :u0000

    ​ boolean : false

    ​ Quote: null

    ​ Modifier, attribute type attribute name = attribute value

  • Object creation and use

    ​ You must use the new keyword to create objects, constructors

    ​ Object properties

private cannot be inherited

To call the superclass constructor, it must be the first line of the subclass constructor

  • Super attention points:
    1. super calls the parent class constructor, must be the first in the constructor
    2. super must only appear in subclass methods or constructors
    3. super and this cannot call the constructor at the same time

Rewriting is the rewriting of methods, and has nothing to do with attributes

The reference of the parent class points to the subclass, and the method call is only related to the defined data type

Must be a non-static method to rewrite, must be a public method to rewrite

static static method, belongs to the class, not to the instance, cannot be overridden

The final method cannot be overridden and is a constant

private methods cannot be overridden

instance of

Converting a subclass to a parent class may lose some of its original methods

A parent class reference points to an object of a subclass

Convert the subclass to the parent class and transform upwards

Convert parent class to subclass, downcast, forced transformation

Convenience method call, reduce duplication of code!

Abstraction: encapsulation, inheritance, polymorphism; abstract class, interface,

The idea of ​​programming, continuous learning, and practice the ideas in your own brain

//抽象类
public abstract class Action {
    
    
//约束,有人帮我们实现
//    abstract,抽象方法,只有方法名字,没有方法实现
    public abstract void doSomething();

//    1.抽象类不能new,只能靠子类实现
//    2. 抽象类可以写普通方法
//    3.抽象方法必须在抽象类中
    
//    抽象类有构造器吗?
//    抽象类的意义何在?
}

Interface function:

  1. constraint
  2. Define some methods for different people to implement
  3. public abstract abstract method
  4. public static final constant
  5. Interface cannot be instantiated, interface has no constructor
  6. implements can implement multiple interfaces
  7. The method in the interface must be overridden

Ctrl+Alt+T, select, add around, condition, catch exception

  • reflection

    Normal way: introduce "package class" name -> new instantiation -> get instantiated object

    Reflection method: instantiate object -> getClass() method -> to the full "package class" name

package com.example.demoDuxiaowei.model;

//测试Class类的创建方式有哪些
public class reflection {
    
    
    public static void main(String[] args) throws ClassNotFoundException {
    
    
        Person person = new Student();
        System.out.println("这个人是:"+person.name);

        //方式一:通过对象获得
        Class personClass = person.getClass();
        System.out.println(personClass.hashCode());

//        方式二:forname获得
        Class aClass = Class.forName("com.example.demoDuxiaowei.model.Student");
        System.out.println(aClass.hashCode());

//        方式三:通过类名.class获得
        Class studentClass = Student.class;
        System.out.println(studentClass.hashCode());

    }
}

class Person{
    
    
    public String name;

    public Person() {
    
    
    }

    public Person(String name) {
    
    
        this.name = name;
    }

    @Override
    public String toString() {
    
    
        return "Person{" +
                "name='" + name + '\'' +
                '}';
    }
}

class Student extends Person{
    
    
    public Student(){
    
    
        this.name="学生";
    }

}

class Teacher extends Person{
    
    
    public Teacher(){
    
    
        this.name="老师";
    }
}
//这个人是:学生
//149928006
//149928006
//149928006

package com.example.demoDuxiaowei.model;


import lombok.Data;

import java.util.Objects;

//@Data
public class User {
    
    
    private Long id;
    private String name;
    private int age;

    public User() {
    
    
        this.id = id;
        this.name = name;
        this.age = age;
    }
    public User(Long id, String name, int age) {
    
    
        this.id = id;
        this.name = name;
        this.age = age;
    }

    public void setId(Long id) {
    
    
        this.id = id;
    }

    public void setName(String name) {
    
    
        this.name = name;
    }

    public void setAge(int age) {
    
    
        this.age = age;
    }

    public Long getId() {
    
    
        return id;
    }

    public String getName() {
    
    
        return name;
    }

    public int getAge() {
    
    
        return age;
    }
}

package com.example.demoDuxiaowei.model;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

//abstract 抽象类,extends 单继承
public class A {
    
    
    public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException, NoSuchFieldException {
    
    
//        通过反射拿user类
        Class user = Class.forName("com.example.demoDuxiaowei.model.User");
//        调用无参构造器
        User wucanUser = (User)user.newInstance();
        System.out.println(wucanUser);

//       调用有参构造器
        Constructor user2 = user.getDeclaredConstructor(Long.class,String.class,int.class);
        Object youcanUser2 = user2.newInstance(1234L, "杜晓伟", 35);
        System.out.println(youcanUser2);

//      通过反射调用普通方法,通过反射获取一个方法
        Method setName = user.getDeclaredMethod("setName", String.class);
//        invoke:激活的意思
//        (对象,“方法的值”)
        setName.invoke(wucanUser,"狂神");
        System.out.println(wucanUser.getName());

//        通过反射操作属性
        User user4 = (User)user.newInstance();
        Field name = user.getDeclaredField("name");

//        不能直接操作私有属性,我们需要关闭程序的安全监测,
//        属性,方法setAccessible(true)
        name.setAccessible(true);
        name.set(user4,"狂神666");
        System.out.println(user4.getName());


    }

}

web

  • tomcat

    Default webapps

    <Host name="www.duxiaowei.com" appBase="webapps"
          unpackWARs="true" autoDeploy="true">
    

Talk about how the website is accessed!

  1. Enter the domain name, withdraw
  2. Check whether there is this domain name mapping under the local C:\Windows\System32\drivers\etc\HOSTS configuration file;
  3. Yes: Directly return the corresponding ip address, which contains the web program we need to access directly
  4. None: go to the DNS server to find, return if found, return if not found

[External link image transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the image and upload it directly (img-aZoTiGzq-1671025928313) (C:\Users\duxiaowei\AppData\Roaming\Typora\typora-user-images\image-20221125125442505.png)]

publish a website

–webapps: the web directory of the tomcat server

​ -ROOT

​ -kuangstudy: website directory

​ -WEB-INF

​ -classes : java program

​ -lib : The jar package that the web application depends on

​ -web.xml : The configuration file of the website

​ -index.html default home page

​ -static

​ -css

​ -style.css

​ -js

​ -img

Maven

convention over configuration

Maven, jar package address: https://mybatis.org/mybatis-3/zh/sqlmap-xml.html#cache

Cookie、Session

7.1 Session

Session : The user opens a browser, clicks many hyperlinks, visits many web resources, and closes the browser. This process is called a session

  • The server sends a letter to the client, and the next time the client visits the server, it is enough to bring the letter: cookie

  • The server registers that you have been here, and I will match you next time you come: session

    Cookie

7.2 Cookie

  1. Get the cookie from the request

  2. The server responds to the client cookie

    public class CookieDemo01 extends HttpServlet {
          
          
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
          
          
            req.setCharacterEncoding("utf-8");
            resp.setCharacterEncoding("utf-8");
    
            PrintWriter out = resp.getWriter();
            //服务器从客户端获取 cookie
            Cookie[] cookies = req.getCookies();//返回数组说明有多个
            //判断Cookie是否存在
            if(cookies!=null){
          
          
                //如果存在怎么办
                out.write("您上一次访问的时间是:");
                for (Cookie cookie : cookies) {
          
          
                    if(cookie.getName().equals("lastLoginTime")){
          
          
                        long lastLoginTime = Long.parseLong(cookie.getValue());
                        Date date = new Date(lastLoginTime);
                        out.write(date.toString());
                    }
                }
    
            }else {
          
          
                out.write("这是您第一次访问本站:");
            }
            //服务器给客户端响应一个cookie
            Cookie cookie = new Cookie("lastLoginTime", System.currentTimeMillis() + "");
            resp.addCookie(cookie);
    
        }
    
    }
    
    <?xml version="1.0" encoding="UTF-8"?>
    
    <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
                            http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
             version="4.0"
             metadata-complete="true">
    
        <servlet>
            <servlet-name>cookieTest</servlet-name>
            <servlet-class>com.du.servlet.CookieDemo01</servlet-class>
        </servlet>
        <servlet-mapping>
            <servlet-name>cookieTest</servlet-name>
            <url-pattern>/c1</url-pattern>
        </servlet-mapping>
    
    </web-app>
    

    7.3 Session

    • The server will create a Session object for each user (browser)

    • A Session monopolizes a browser, as long as the browser is not closed, the Session exists

    • After the user logs in, he can visit the entire website! –>Save user information, save shopping cart information...

          <session-config>
              <!-- 15分钟后Session失效,一分钟为单位-->
              <session-timeout>15</session-timeout>
          </session-config>
      
    • scenes to be used

      1. Save a login information
      2. shopping cart information
      3. The data that is often used throughout the website, we save it in the Session
      //手动注销Session
      session.invalidate()
      

7.4 Difference between Session and Cookie

  • Cookie is to write the user's data to the user's browser, and the browser saves it (multiple can be saved)

  • Session writes the user's data to the user's exclusive Session, and saves it on the server side (save important information and reduce the waste of server resources)

  • Session objects are created by the server

    //RestFul: style

    @RequestMapping(“/add/{a}/{b}”,method=RequestMethod.GET)

    public String test1(@PathVariable int a ,@PathVariable int b,Model model){

    }

Guess you like

Origin blog.csdn.net/u013080870/article/details/128322691