I. Software architecture explanation

Today we are going to start learning about the back end of the server, but before we get to that, we are going to talk about two classic software architecture patterns C/S and B/S.

  1. C/S architecture (QQ, wechat)

The Client computer is required to install a Client program, and the Server computer is required to install the Server program

  • The characteristics of
    1. The server manages access to the database
    2. The client is responsible for the interaction with users, collecting user information, and sending requests to the server through the network.
    3. The client program (foreground program) runs on the client, and the database service program (background program) runs on the application server
  • advantages
    1. Good user experience, cool effect
    2. Information processing is more secure
    3. The client can store some resources, reducing the time and effort of obtaining resources
  • disadvantages
    1. This occupies the space of the local disk
    2. Maintenance trouble, often need to update
    3. Installation may depend on additional environments
  • Common application QQ | WeChat client | thunderbolt…
  1. B/S Architecture (Web Games)

That is, Browser/Server Connects to the Server through the Browser without additional programs

  • The characteristics of
    1. A series of user operations are completed on the browser, which connects to the server
    2. The client is too simple, leaving all the content and calculations on the server.
  • advantages
    1. Easy to maintain and upgrade, only need to pay attention to the browser
    2. You don’t need to install any add-ons. You only need a browser to use it
  • disadvantages
    1. Effects are browser-limited and may not be as cool as C/S
    2. Information security is poor. For example, U shield is used for information encryption in e-banking
    3. Heavy server load (resources, and most computing work on the server side)
  • Common application online banking | | web qq web game…

Second, MVC architecture explanation

  1. Concept to explain

B/S or C/S as explained above is just a big picture separation of client and server. MVC here focuses on the server side from the start. In the evolution of server-side architecture design, MVC is a very classic design. Almost all B/S architecture applications use MVC to design their applications. MVC is actually M(Model), V(View), C(Control), three levels

  • M

Refers to models that represent business rules. Of the three parts of MVC, the model has the most processing tasks. The data returned by the model is neutral and the model is independent of the data format, so that a model can provide data for multiple views, reducing code duplication because code applied to the model can be written once and reused by multiple views

  • V

An interface that the user sees and interacts with. For example, a web page interface consisting of HTML elements, or a software client interface. One of the nice things about MVC is that it can handle many different views for your application. There’s no real processing going on in the view, it’s just a way to output data and allow the user to manipulate it

  • C

The controller takes input from the user and invokes models and views to fulfill the user’s requirements. The controller itself does nothing and does nothing. It simply receives the request, decides which model artifact to call to process the request, and then determines which view to use to display the returned data.

  1. Concrete implementation of MVC architecture

The ABOVE MVC is a design pattern advocated in the early stage, a theoretical basis. When actually coding, the server-side code is logically layered, with three common layers, known as the three-tier architecture. They are: presentation layer, business logic layer, data access layer

  • Implementation framework at a specific level

3. Basic use of Spring

  1. Spring the Boot is introduced

    As analyzed above, each level of our solution has a different framework, and since each framework has its own configuration, the starting point for Spring Boot is to integrate these bloated configurations of the three levels. It is a relatively new project in the Spring community. The goal of the project is to make it easier for developers to create Spring-based applications and services, to make it easier for more people to get started with Spring, and to provide a fixed, convention over configuration style framework for the Spring ecosystemCopy the code
  2. Setting up the Spring Boot environment

  3. Build. gradle adds dependencies

    Dependencies {the compile (” org. Springframework. The boot: spring – the boot – starter – web: 1.5.10. RELEASE “)}

  4. Define the SpringBoot boot class

    @SpringBootApplication public class SampleController {

     public static void main(String[] args) throws Exception {
         SpringApplication.run(SampleController.class, args);
     }
    Copy the code

    }

  5. The first Controller

    @restController Public Class DemoController {private static Final String TAG = “DemoController”; private static Final String TAG = “DemoController”;

    Localhost :8080/ demo@requestMapping ("/demo") Public String save(){system.out.println ("DemoController ") save~! ~ ~!" ); Return "Execution succeeded "; }Copy the code

    }

Iv. Introduction to server software

  • What is a server

In fact, the server is a bit more advanced than the PC computer, more advanced hardware, better performance, stronger computing ability.

  • What is server software

Server software is actually software, and this kind of software allows the code we write to host our web projects so that they can be accessed.

  • Common server software

Apache: Apache tends to be static resource handling

Tomcat: a free small server software provided by Apache that supports the JSP/Servlet specification

WebLogic: fee-based large server software from Bea that supports all EE specifications

WebSphere: IBM charges for large server software that supports all EE specifications

JBoss: A J2Ee-based open source server software core that does not support JSP/ servlets and typically works with Tomcat or Jetty

Five, PostMan use (network debugging tool)

  1. PostMan is introduced

    Users need some methods to track web requests when they develop or debug network programs or web B/S mode programs. Users can use some network monitoring tools such as the famous Firebug and other web debugging tools. Today we introduce this web debugging tool can not only debug simple CSS, HTML, scripts and other simple basic information of the web page, it can also send almost all types of HTTP requests! **Postman** is one of the representative products in the Chrome plugin class for sending WEB HTTP requests.Copy the code

It originally existed as a Chrome plug-in, but now it’s officially available as a standalone desktop installation, and doesn’t necessarily need to be installed as a Chrome plug-in.

  1. PostMan installation

  2. Go to the official website to download

  3. Directly install and use

  4. PostMan used

Vi. Controller CRUD drill

Any knowledge of the server side is related to add and delete check, in a word, do the server side, in fact, is constantly doing CRUD

  1. Get page submission data
  • A. Receive scattered parameters

You can retrieve the data passed by the request by specifying the same name as an argument in the method’s argument

@RequestMapping("login")
public String login(String username , String password){
    
    
}
Copy the code
  • B. Receive object data

Sometimes you need to receive a lot of data, and it can be troublesome to receive all the data with scattered parameters. You can actually use objects to receive data.

public class User{
    
    private String username;
    private String password;
    
   //get & set xxx
    
}

@RequestMapping("login")
public String login(User user){
    
    
}
Copy the code
  1. Increase | save operation

Here is free to a save work to demonstrate, can be to save student information, save commodity information.. There is no limit

  • Receive parameters

Suppose we are going to demonstrate a student management system save, it is important to receive student information (at least basic name, age, address, phone…) from the browser. In general, these operations should be done through a page. The page is not involved here, but can be demonstrated with PostMan

@RequestMapping("/user_save") public String save(String name , int age , String address ){ System.out.println("name=" + name + "==age=" + age + "===addres=" + address); Return "Save successfully "; }Copy the code

Postman demo

  • Complete preservation

You can save the data first, add a few more, and then extract the ID. Mainly in order to modify the data later up more convenient, note to add write

private static int ID = 1 ; @RequestMapping("/user_save") public String save(String name , int age , String content = ID +"#"+ name+"#"+age+"#"+address+"\r\n"; FileWriter fw = new FileWriter("stu.txt",true); fw.write(content); fw.close(); / / id since increase ID++; System.out.println(" write file successfully "); } catch (IOException e) { e.printStackTrace(); } return "Save successfully "; }Copy the code
  1. Delete operation

Since we are working with text, the text content does not support direct deletion operations. We need to read out the content, then delete the corresponding content, and then concatenate and write into the text.

@RequestMapping("/user_delete") public String delete(String id ){ try { FileReader fr = new FileReader("stu.txt"); Br = new BufferedReader(fr); StringBuffer buffer = new StringBuffer(); String line = null; while((line = br.readLine()) ! = null){//1# Tom # 10 # 5 String [] contents = line.split("#"); // compare id if(! Object.equals (contents[0])){buffer.append(line).append("\r\n"); }} // Write it back. FileWriter fw = new FileWriter("stu.txt"); fw.write(buffer.toString()); fw.close(); br.close(); } catch (Exception e) { e.printStackTrace(); } return "delete succeeded "; }Copy the code
  1. The update operation

The update operation needs to specify which piece of data to update and also what data to update. These operations are very common in daily life, such as changing their wechat profile picture, chat background picture, data entry errors, and also need to provide update operations. We’re still working on a file, so we still need to read it out, put it together, and write it back.

@RequestMapping("/user_update") public String update(String id , String address ){ try { FileReader fr = new FileReader("stu.txt"); BufferedReader br = new BufferedReader(fr); String line = null; StringBuilder stringBuilder = new StringBuilder(); while((line = br.readLine()) ! = null){ String [] contents = line.split("#"); If (id.equals(contents[0])){line = line.replace(contents[contents.length-1],address); } // After the modification, remember to concatenate it so that it can be written to the file later. stringBuilder.append(line + "\r\n"); } // write back FileWriter fw = new FileWriter("stu.txt"); fw.write(stringBuilder.toString()); fw.close(); br.close(); } catch (Exception e) { e.printStackTrace(); } return "Update succeeded "; }Copy the code
  1. Query all

    @RequestMapping(“/user_findAll”) public String findAll(){ try { File file = new File(“stu.txt”); FileReader fr = new FileReader(file); BufferedReader br = new BufferedReader(fr);

    String line; while(( line = br.readLine()) ! =null){ System.out.println(line); } br.close(); } catch (Exception e) { e.printStackTrace(); } return "query succeeded ";Copy the code

    }

Seven, package deployment

  1. The jar package

Add this build package configuration to build.gradle to create an executable JAR package.

// Build the packaged configuration jar {// iterate over dependencies, Appended to the String on the someStirng someString = 'configurations. The runtime. Each {someString = someString + "lib / /" + it. The name} / / specified project list Manifest {attributes' main-class ': 'com.itheima.MainApp' // Specifies the starting Class attributes' class-path ': Tasks. withType(JavaCompile) {options.encoding = "utF-8"} // Copy jar, Task copyJar(type:Copy){from Configurations. Runtime into ('build/libs/lib')} // Build a custom task release DependsOn: [build,copyJar] task release(dependsOn: [build,copyJar]){}Copy the code
  1. Deploying the Cloud Server

  2. Upload the JAR package to the server

  3. Run it using java-jar, as shown in the following command

    Run the following command to run the jar package:

    A:

    Java-jar Sharenio. jar Features: The current SSH window is locked. You can press CTRL + C to interrupt the running of the program or close the window to exit the program

    So how do you keep Windows unlocked?

    Way 2

    Java-jar shareniu.jar & & indicates that the command is running in the background.

    Specific: The current SSH window is not locked, but the program is aborted when the window is closed.

    Continue to improve, how to make the window close while the program is still running?

    Methods three

    nohup java -jar shareniu.jar &

    Nohup means to run the command without hanging up, and the program still runs when the account exits or the terminal is closed

    When a job is executed with the nohup command, by default all output of the job is redirected to the nohup.out file unless an output file is specified otherwise.

    Methods four

    Nohup Java -jar shareniu. Jar >temp. TXT

    command >out.file

    Command >out.file redirects the output of the command to the out.file file, that is, the output is not printed to the screen but to the out.file file.

    You can run the jobs command to view background tasks

    Jobs then lists all the jobs that are executed in the background, each preceded by a number. If you want to call a job back to the foreground control, you just need the FG + number.

    Fg 23 Check the PID of the thread occupied by a port

    netstat -nlp |grep :9181