Javaweb final review

javaweb final review

JSP

basic grammar

  • <%@…%>: page directive in the form of directive tag
  • <%!..>: declare class variables, methods, etc.
  • <%…>: JSP script element
  • <%=…%>: JSP expression

built-in object

request

  • getAttribute(String name): Returns the value of the specified attribute, often used in the front end to accept data
  • getParameter(String name): Returns the value of the specified parameter, commonly used to obtain the information submitted by the form, often used in the backend (Servlet or JSP) to obtain front-end data
  • setAttribute(String key, Object obj): Set the value of the specified attribute. Commonly used in the backend to send data back to the frontend

response

redirect
response.sendRedirect("URL")

dispatcher.forward(request,response): can only jump within this website, the pages before and after the jump belong to the same request object
response.sendRedirect("URL"): can jump to any address interface

session

life cycle

The session object is automatically created by the server when the first JSP page or Servlet is loaded, and is destroyed by the server when the user exits each application to complete session management. The session object is released only when the session expires, the client closes the browser, or the server calls the invalidate() method of the session, ending its life cycle.

main method
  • getAttribute(String name): Get the session attribute value associated with the specified name
  • setAttribute(String key, Object obj): Set the session attribute value of the specified name
example
<%
session.setAttribute("name","hello");
out.println(session.getAttribute("name"));
>

other built-in objects

  • application: realize the sharing of data among users
  • out: Send data like the client, and the content sent is the content that the browser needs to display
  • exeception: used for exception handling

MVC pattern

Please add a picture description

advantage

  • Multiple views can share a model
  • The same component can be used by different interfaces
  • Easily change the application's data layer and business rules
  • Controllers can interface with different models and views
  • Conducive to software engineering management

technology

  • M layer: business logic layer, java class or javaBean, data model (DAO layer)
  • Layer C: Servlet
  • V layer: JSP, XML

JOSN

grammar

  • data in key-value pairs
  • data separated by commas
  • Curly braces hold objects
  • Square brackets hold arrays

JavaScript

  • increase, modify
var student={
    
    }
student["ID"]="12345";
  • value query
name=student["name"];
  • traversal operation
for(var value in student)
  alert(student[value]);
  • delete operation
delete(student["name"]);

Java

Please add a picture description

basic skills

  • The mutual conversion function between JSON string and java object, that is, deserialization
  • The Java object is converted into a JSON string, which is the serial number
  • The Java object array serializes the JSON string, and after it is sent to the front end, it is deserialized by JavaScript and converted into JSON object data in the JavaScript environment
  • Processing of JSONNode with tree structure

core class

JSON class
public static final JSONObject parseObject(String text);
  • JSON string parsed into JSONObject object
JSONObject ob1=JSON.parseObject(JSONStr);
public static final<T>T parseObject(String text,class<T>clazz);
  • JSON string parsed as JSONArray
User user=JSON.parseArray(jsonStr2);
public static final <T>List <T>parseArray(String text,Class<T>clazz);
  • JSON string parsed into JavaBean
JSONObject ob1=JSON.parseObject(jsonStr1,User.class);
pubic static final JSONArray parseArray(String text);
  • Java object serialization to JSON string
String userJsonStr=JSON.toJSONString(user);
public static final Object toJSON(Object JavaObject);
  • Convert JSONObject to Java object
User user=(User)JSON.toJavaObject(jsonobj,User.class);
JSONObject

JSONObject is a subclass of JSON, so all APIs of JSON are inherited by it.
Construction method:
JSONObject()
Commonly used API:
getXxx(key)
Example:

JSONObject obj=new JSONObject();
obj.put("name","tang");
map.put("age",24);
String name=obj.getString("name");
JSONArray

JSONArray has the functionality of JSONObject and ArrayList

axios technology:

axios() standard structure:

 axios({
    
    JSON对象}).then(function(response){
    
    回调函数}).
 catch(function(error){
    
    异常});
{
    
    JSON对象}={
    
    url:"LoginAjax",method:"post",
data:{
    
    name:this.userName,pass:this.password}}

Code sample:

var vm=new vue({
    
    
    el:'#app',
    data:{
    
    promptMess:"",userName:"",passWord:""},
    method:{
    
    
        onSubmit:function(){
    
    
            var self=this;   //回调函数无法获取this
            axios({
    
    url:"LoginAjax",method:"post",
            data:{
    
    name:this.userName,pass:this.password}}).then(function(response){
    
    
                if(response.data=="error")
                self.promptMess="用户名或密码错误";
                else{
    
    
                    self.promptMess="登陆成功";
                    ...
                }
            }).catch(function(error){
    
     })
        }
    }
});

Servlet receives request

BufferedReader rd=request.getReader();
String strJSON="",temp;
while((temp=rd.readLine())!=null){
    
    
  strJSON=strJSON+temp;
}
System.out.println(strJSON);

The backend cannot use request.getParameter() to obtain data, because axios only transmits HTTP request/response messages (actually strings) to the background, not key-value pairs.

simplify

get request


axios.get(url,[其他])
//axios(url,[其他])

example

axios.get('/user?ID=1235')
.then(function(response){
    
    
  console.log(response);
}).catch(function(error){
    
    
  console.log(error);
});

with multiple data

axios.get('/user'.{
    
    params:{
    
    name:"123",pass:"123"}}).then(...);

Servlet

life cycle

  • load
  • instantiate
  • initialization
  • Serve
  • destroy

working process

  • The Tomcat main thread responds to forwarded user requests and creates two built-in objects
  • The URL in the construction request finds the correct Servlet, Tomcat creates or allocates a thread for it, and passes the two built-in objects created to the process at the same time
  • Tomcat calls the service() method, calls the doGet() or dePost() method
  • Execute related do methods, generate static resources, and combine information into response objects
  • When the Servlet thread finishes running, Tomcat converts the response object into an HTTP response and returns it to the user, and deletes the request and response objects at the same time
    Please add a picture description

API

  • init(): Executed when the server loads the Servlet
  • destroy(): executed when the server uninstalls the Servlet
  • service(): Servlet core
  • doPost()
  • doGet()

RequestDispatcher interface

request.setAttribute("key",任意对象数据);
RequestDispatcher dispatcher=null;
dispatcher=getServletContext().getRequestDispatcher("目的界面");
dispatcher.forward(request,response);

filter

main method

  • init(): This method is called after the Servlet container creates a Servlet filter instance
  • doFilter(): When a client requests access to the URL associated with the filter, the Servlet container calls this method
  • destroy(): The Servlet container calls this method before destroying the filter instance

life cycle

  • An instance of the filter is loaded when the server is started, and the init() method is called to initialize the instance.
  • Only call the doFilter() method for each request
  • Call the destroy() method to destroy the instance when the server is stopped

web.xml configuration

<filter>
<filter-name>过滤器名字</filter-name>
<filter-class>过滤器对应的类</filter-class>
<init-param>
<param-name>参数名称</param-name>
<param-value>参数值</param-value>
</init-param>
</filter>

listener

Listener object creation and destruction

  • ServletContextListener: The ServletContext object is created when the Web server is started, triggering contextInitialized(); the ServletContext object is destroyed when the Web server is shut down, triggering contextDestroyed()
  • HttpSessionListener: The session object is created when the session between the browser and the server starts, and sessionCreated() is fired; when the session object is invalidated or destroyed, sessionDestroyed() is fired
  • ServletRequestListener: The request object is created at the beginning of each request, triggering requestInitialized(); the request object is destroyed at the end of each visit, triggering requestDestroyed()

Listen for object property changes

  • SessionContextAttributeListener: When the servletContext object attributes are added, modified, or deleted, the three methods of attributeAdded(), attributeReplaced(), and attributeRemoved() are triggered.
  • HttpsessionAttributeListener: Same as above
  • ServletRequestListener: Same as above

Monitor object status

  • HttpSessionActivationListener
  • HttpSessionAttributeListener

JDBC

step

  • Register to load a database driver
  • Create database connection
  • Create SQL statements
  • The database executes the SQL statement
  • User programs process the results of executing SQL statements

Application example

FistJDBC.java
import java.sql.*;
public class FitstJDBC{
    
    
  public static void main(String arg[]){
    
    
    String driver="com.mysql.jdbc.Driver";
    String user="root";
    String pass="123456";
    String url="jdbc:mysql://127:0.0.1:3306/test?useUnicode=true&characterEncoding="utf-8";
    Connection con=null;
    Statement stmt=null;
    ResultSet rs=null;
    try{
    
    
    //加载驱动程序
      Class.forName(driver)//连接数据库
      con=DriverManager.getConnection(url,user,pass);
      //创建执行查询的Statemen对象
      stmt=con.createStatement();
      String sql="select * from tb_user";
      rs=stmt.executeQuery(sql);
      String name,password,tel;
      while(re.next()){
    
    
        name=rs.getString(1);
        password=rs.getStirng(2);
        tel=rs.getString("tel");
      }
    }catch(ClassNotFoundException e)
    catch(SQLException el)
    finally{
    
    
      try{
    
    
        rs.close();
        stmt.close();
        con.close();
      }catch(SQLException e)
    }
  }
}

interface

Statement: Used to execute static SQL statements and return its result set object
PreparedStatement: Represents precompiled SQL statement objects with or without IN, SQL statements are precompiled and stored in PreparedStatement objects CallableStatement
: Interface for executing SQL stored procedures

result set

After Statement executes a query SQL statement, it will get a ResultSet object, that is, the result set, which is a collection of results.

A scrollable, modifiable ResultSet object

The Statement interface corresponds to the createStatement(int resultSetType, int resultSetConcurrency) method
. The resultSetType parameter is used to specify the scrolling type. Common values ​​are as follows:

  • TYPE_FORWARD_ONLY: indicates that the cursor can only scroll forward
  • TYPE_SCROLL_INSENSITIVE: Indicates that the cursor is scrollable, but is generally not affected by changes to the data to which the ResultSet is connected.
  • TYPE_SCROLL_SENSITIVE: Indicates that the cursor is scrollable, but is generally affected by changes in the data to which the ResultSet is connected.
    The resultSetConcurrency parameter is used to specify whether the result set can be modified. Common values ​​are as follows:
  • CONCUR_READ_ONLY: Indicates non-updatable concurrent mode
  • CONCUR_UPDATABLE: Indicates a concurrent mode that can be updated

method:

  • boolean first(): Move the cursor to the first row of the ResultSet object
  • boolean last(): Move the cursor to the last row of the ResultSet object
  • boolean isFirst(): Determine whether the cursor is in the first line of the ResultSet object
  • boolean isLast(): Determine whether the cursor is in the last line of the ResultSet object
  • boolean previo(): Move the cursor to the previous line of the current line of the ResultSet object

JDBC metadata

Metadata is data about data, used to represent the properties of the data.

ResultSetMetaData interface

Common methods:

  • int getColumnCount(): returns the number of columns in the ResultSet object
  • String getColumnTypeName(int column): Get the type name of the specified column
  • String getColumnName(int column): Get the name of the specified column
example
public static void main(String[]args){
    
    
  Connection connection=DBConnection.getConn();
  Statement statement=null;
  ResultSet resultSet=null;
  ResultSetMetaData resultSetMetdData=null;
  int columnCount;
  try{
    
    
    statement=conccetion.createStatement();
    String sql="select * from tb_user";
    resultSet=statemen.executeQuery(sql);
    resultSetMetaData=resultSet.getMetaData();
    columnCount=resultSetMetaData.getColumnCount();
    System.out.println(columnCount)
    for(int i=1;i<=columnCount;i++){
    
    
      System.out.println(resultSetMetadata.getColumnName(i),resultSetMetaDataTypeName(i));
    }
  }catch(SQLException e){
    
    
    e.printStackTrace();
  }finally{
    
    
    DBconnection.close(connection,statement,resultSet);
  }
}

DAO

Please add a picture description

connection pool

Core idea: connection reuse, avoiding the overhead of frequent establishment and closure of the database

Connection pool initialization

Static connection pool: The connection in the connection pool has been allocated when the system is initialized, and the connection cannot be closed at will.

Connection Allocation Management Policy

The connection allocation management strategy of the connection pool is the core of the connection pool mechanism

Connection pool release

data source

advantage:

  • Programs don't need to be hardcoded like using DriverManager
  • Many servers and mainstream frameworks provide connection pool implementations for data sources, improving development efficiency

MyBatis

advantage

  • easy to learn
  • flexible
  • Decoupling the SQL statement from the program code
  • Provides mapping tags for Java objects and relational data tables
  • Provides XMl tags to support writing dynamic SQL statements

core object

  • SqlSession
  • Executor
  • MappedStatement
  • ResultHandler

Core process:

  • Read the configuration file of MyBatis
  • load map file
  • Build a session factory
  • create session object
  • Start Executor (executor)
  • Create a MappedStatement object
  • Input parameter mapping
    Please add a picture description

DAO layer design

pack com.example.demo.dao
import java.utils.List;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import com.example.demo.entity.User;
@Mapper
public interface DAOUserTable{
    
    
  @Inerst("insert into tb_user(userName,passWord,tel)values(#{userName},#{passWord},#{tel})")
  public boolean addUser(User u);
}

Common Notes

@Result: When the attribute name of the entity class is inconsistent with the field name of the database table, the corresponding mapping relationship can be manually established, column is the database field name, porperty is the attribute name of the entity class, jdbcType is the field data type, and whether id is the primary key Example
:

@Result(column="name",property="userName",jdbcType=JdbcType.INTEGER)

@Param: Name the parameter
Example:

User getUserByNameAandPass(@Param("name")String str1,@Param("pass")String str2);

Transaction processing @Transactional annotation

characteristic

  • atomicity
  • consistency
  • isolation
  • Persistence
checked exception

Abnormalities that must be detected, such as file non-existence, network or database link errors, etc.
Rollback operations:

@Transactional(rollbackFor=Exception.class)
unchecked exception

Refers to the exception that the java code does not need to detect, it is a subclass of RuntimeException, that is, the real-time operation exception, indicating the logic error of the program

Spring

Please add a picture description

Spring IOC

One of the two most important core features of Spring is Dependency Injection (DI) and Inversion of Control (IOC)

Spring XML configuration file

<beans xmlns="http://www.springframework.org/schema/beans">
<bean id="helloworld"class="SpringFirst.HelloWorld">
<property name="message"value="HelloWorld"/>
</beans>

The value of the id attribute of the element is a string literal, which can generally have the same name as the corresponding class name, but the first letter is lowercase. The value of the class attribute is the full path class name (including the package name) of the bean object, indicating the data members and attributes of the class represented by the bean

Annotation-based dependency injection

@Autowired annotation
import org.springframework.beans.factory.annotation.Autowired;
public class UserService{
    
    
  @Autowired
  private UserDao userDao;
  @Autowired
  private User user;
  public UserService(UserDao userDao,User user){
    
    
    this.userDao=userDao;
    this.user=user;
  }
}
other notes
  • @Controller: A controller dedicated to the Web
  • @Service: Business classes for the project, including entity classes
  • @Repository: for DAO layer
example
@Service
public class User{
    
    
  private String name;
  public String getName(){
    
    return name;}
  public void setName(String name){
    
    this.name=name;}
}
@Repository
public class UserDao{
    
    
  public void login(User u){
    
    
    System.out.println(u.getName());
  }
}
public class UserService{
    
    
  @AutoWired
  private UserDao userDao;
  @Autowired
  private User user;
  public void loginUser(){
    
    userDao.login(user);}
}

SpringMVC

Operating principle

Please add a picture description

annotation

  • @Controller: controller object, annotation class is not Servlet
  • @RequestMapping: Used to define the mapping between URL requests and Controller methods
  • @ResponseBody: The annotation is used for methods in controller classes or classes. If it is the former, if the method used by the controller has a return value, it will not be handed over to the general controller, but will be written into the body data area of ​​the Response object, and then directly returned to the front-end page.

SpringBoot

Maven

It helps programmers to be liberated from the tedious project configuration work, easily carry out project construction, Jar package management and code compilation, automatically execute unit tests, package and generate reports, and even deploy projects and generate Web sites.

log level

LogBack priority from high to low is: OFF, FATAL, ERROR, WARN, INFO, DEBUG, TRACE, ALL.

SpringBootApplication

package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DemoApplication{
    
    
  public static void main(String[]args){
    
    
    SpringApplication.run(DemoApplication.class,args);
  }
}

annotation

  • @PathVariable: Variables in the path of RequestMapping
  • @RestController: Equivalent to @Controller plus @ResponseBody
  • @GetMapping: RequestMapping for GET requests

example

@RestController
@RequestMapping("/user")
public class UserManagementController{
    
    
  @Autowired
  private UserManagement um;
  @GetMapping("/userNmaeCheck/{name}")
  public String checkUserName(@PathVariable("name")String name){
    
    
    System.out.println(name);
  }
}

Guess you like

Origin blog.csdn.net/m0_53192838/article/details/128160536