Front-end and back-end interaction process

1. Front-end and back-end interaction:

Front-end and back-end interaction can also be understood as data interaction. The front-end needs to obtain (GET) data and obtain the uploaded (POST) data through a request. The front-end sends a request, and after receiving the request, the back-end operates on the database and returns the data required by the front-end. Complete a front-end and back-end interaction.

The general flow chart is as follows:

 

2. Preparatory work (build server):

To carry out front-end and back-end interaction, you need to build an environment, that is, install a tomcat server, which supports the running of java programs, and then develop a java back-end program, create a javaEE project in the idea, integrate tomcat, and deploy the project into the server.

3. Create a project using Vue-cli

 4. Import ElementUI components

//导入elementUI
import ElementUI from 'element-ui'; 
import 'element-ui/lib/theme-chalk/index.css'; 
Vue.use(ElementUI);

5. Create a landing page and configure routing

import Vue from 'vue'; 
import router from 'vue-router'; /* 导入路由 */ 
import Login from "../Login.vue";//导入组件
/* 定义组件路由 */
 var rout = new router({ 
	 routes: [ 
	 { 
		 path: '/login', //为组件定义地址
		 name: 'login', 
		 component: Login 
		 }
]
});

6. Send request

The front-end user enters the account number and password, clicks to log in, and sends a post request to the back-end. It needs to import axios and encapsulate it with HttpServletRequest to send the request to the back-end. Errors may occur during the sending process (cross-domain errors)

(1) Import axios: (which defines the IP and interface of the server side)

//导入axios
import axios from 'axios';
axios.defaults.baseURL="http://127.0.0.1:8080/webBack/";
Vue.prototype.$http=axios;

(2) Cross-domain issues:

Because we use the method of separating the front and back ends, the front and back ends are on different servers, so the front-end server will have a same-origin policy, and cross-domain problems arise. The same-origin policy is a security function of the browser. The client cannot read and write the resource address of the other party without explicit authorization.

This cross-domain problem can be solved in the back-end filter, and each filter needs to be configured in xml accordingly

public class CorsFilter implements Filter {
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
            throws IOException, ServletException {
        HttpServletResponse httpResponse = (HttpServletResponse) servletResponse;
        HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;
        //允许携带Cookie时不能设置为* 否则前端报错
        httpResponse.setHeader("Access-Control-Allow-Origin", httpRequest.getHeader("origin"));//允许所有请求跨域
        httpResponse.setHeader("Access-Control-Allow-Methods", "*");//允许跨域的请求方法GET, POST, HEAD 等
        httpResponse.setHeader("Access-Control-Allow-Headers", "*");//允许跨域的请求头
        httpResponse.setHeader("Access-Control-Allow-Credentials", "true");//是否携带cookie

        filterChain.doFilter(servletRequest, servletResponse);
    }
}

(3) Send a post request:

 7. Backend receiving:

The backend has a doPost method to receive requests, receive the account password sent by the frontend for verification, connect to the database, query the data in the database for verification, and encapsulate the queried data in the admin object we defined. If the login is successful , generate a token, which carries the user's information, then encrypt the information in admin, encapsulate the admin in the commonResult object we defined, and encapsulate the status code, admin and the information that needs to be returned to the front end in the commonResult , and then use the json format to return it to the front end

(1) doPost receives the request:

 protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //接收数据
        String account = req.getParameter("account");
        String password = req.getParameter("password");
}

(2) The admin object encapsulated by ourselves:

public class Admin {
    private  int id;
    private  String account;
    private  String password;
    private  String token;


    public String getToken() {
        return token;
    }

    public void setToken(String token) {
        this.token = token;
    }

    public int getId() {
        return id;
    }

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

    public String getAccount() {
        return account;
    }

    public void setAccount(String account) {
        this.account = account;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

(3) encryption

//登陆成功,生成token,token中携带用户信息
                String token = JWTUtil.token(admin.getId(),admin.getAccount());
                admin.setToken(token);//在后端将token添加到admin中

JWTUtil:

 (4)CommonResult:

public class CommonResult {
    private int code;
    private Object data;
    private String message;

    public CommonResult(int code, Object data, String message) {
        this.code = code;
        this.data = data;
        this.message = message;
    }
    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public Object getData() {
        return data;
    }

    public void setData(Object data) {
        this.data = data;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }
}

(5) Return the live status code and admin to the front end in json format:

resp.setHeader("Content-Type", "text/html;charset=utf-8");//设置响应呢绒的编码
        PrintWriter printWriter = resp.getWriter();


commonResult=new CommonResult(200,admin,"登陆成功");

ObjectMapper objectMapper = new ObjectMapper();
        String json = objectMapper.writeValueAsString(commonResult);
        printWriter.print(json);

8. Web session tracking technology:

During the interaction between the web front-end and the back-end, the back-end does not know which user is operating here, because the http request is stateless (request-response mode), and there is no identification that can identify the other party in the request. It can be considered that each independent of each request

Then we need to know in actual development that every time a request is sent to the backend, it is the user who sent it. This implemented function is called tracking technology, which is to generate a token (token) in the backend after successful login A string (can carry user information, encrypted)

9. The front end receives the response:

The front end judges the status code after receiving it. If the reception is successful, the token and account are stored in sessionStorage (a session-level storage space provided by the browser, which is cleared immediately after the browser is closed), and then go to main (we log in to Entered interface) interface.

if(resp.data.code==200){
					   //sessionStorage.setItem浏览器提供的一个会话级别的存储空间,浏览器关闭后立刻清除
					   sessionStorage.setItem("account",resp.data.data.account);
					   sessionStorage.setItem("token",resp.data.data.token);
					   //localStorage.setItem("key","value");//长久保存
					   this.$router.push("/main");

(1) Add a response interceptor:

// 添加响应拦截器 
axios.interceptors.response.use((resp) =>{
	//正常响应拦截 
	if(resp.data.code==500){ 
		ElementUI.Message({message:resp.data.message,type:"error"}) 
		}
		if(resp.data==202){
			sessionStorage.clear();//token验证无效,这样就认为登录无效,也可以清空前端存储的数据
			router.replace("/login"); 
			} 
			return resp; 
			});

10. Verify that the user is logged in:

//添加路由导航守卫,每次触发路由组件时,去to.path的路径
rout.beforeEach((to,from,next)=>{ 
	if(to.path=='/login'){
		//如果用户访问的登录页,直接放行 
		return next(); 
	}else{ 
		var account = sessionStorage.getItem("account"); 
		if(account==null){ 
			return next("/login"); 
			}else{ 
				next(); 
		} 
	} 
})

11. Perform some operations in the main interface:

Every operation needs to send a request to the backend, and the token in the frontend needs to be carried when sending the request, and it is verified at the backend.

It will be very troublesome to carry the token every time the front-end and back-end interact, so add an axios request interception in main.js, and carry the token saved by the front-end every time the front-end and back-end interact.

(1) Axios request interception:

//axios 请求拦截 
axios.interceptors.request.use(config =>{
	//向请求头中添加一个自定义请求头
	config.headers.token = sessionStorage.getItem('token'); 
	   return config; 
})

12. The backend receives the request:

After entering the backend, it will enter the filter. The request that can enter the filter has been configured in xml. After the filter is successful, the backend doget method receives the request, and then encapsulates the token in jwt to obtain the information in it. (id account), and then respond back to the front end

(1) Validate token filter:

 (2)JWT

JWT is an implementation of token in the above process. Generally speaking, jwt is a string

It saves the user information in a Json string, and then encodes it to get a JWT token, and this JWT token has signature information, which can be checked for tampering after receiving, so it can be used for security between parties to transfer information as Json objects

13. Front-end receiving

After receiving it, the front end can prompt the user with a message alert("success").

The above is the process of front-end and back-end interaction

Guess you like

Origin blog.csdn.net/weixin_71243923/article/details/127407115