The first lesson of Spring, understand the files in IDEA, review Cookie and Session, and how to obtain Session, Cookie, and Header

Table of contents

IDEA Lesson 1 (Familiar with the content) 

Establish connection -@RequestMapping Route mapping

ask        

1. Pass a single parameterEdit

2. Multiple parameters editing

3. Pass array

4. Pass a collection, but a 500 error occurred when we passed it here.

A brief introduction to JSON

Review Cookies and Sessions

The difference between Cookie and Session

Two ways to get cookies

How to set up Session

Problem getting Session

Get Header information in Http request


IDEA Lesson 1 (Familiar with the content) 

resources resource directory

static       /static static file

templates  Mainly configuration related code /templates templates

application .properties    SpringBoot project configuration file - very important

test test code. Note that this is the developer’s test code and has nothing to do with the tester.

As a developer, you need to be responsible for the quality of your own code and cannot rely entirely on testing QA

After the function is developed, it needs to be self-tested first. If the self-test passes, it will be handed over to the tester.

Note⚠️The colors of the folders are also different - blue and green java. Of course you can set it up in the picture below

On the current page we are different from the Servlet we learned earlier. First of allSpring comes with Tomcat.

Secondly, it is different from the path we went to before. The reason is that looking at the log below, he wroteContentPath is "" which is empty.

Now Spring does not require us to download Tomcat ourselves and provides us with an encapsulation, but the actual use is still the http protocol.

Spring Boot helps us build projects quickly

Springmvc is a module of Boot. You can use this project to develop jAVAweb projects. It is a Springmvc project and is improved based on Servlet.

MVC can actually be seen as an idea. The implementation through Spring is called SpringMVC. However, at the current stage, the MVC concept has undergone some changes. Back-end personnel are not involved in the development of front-end pages, so there is no view layer. Now there is a view. A layer of explanation, the view returned before is now more like the data of the returned view.

Learn SpringMVC

Establish connection -@RequestMapping Route mapping

Access address,Class path + method path(For example, if a RequestMapping is added in front of the class below, then the class will also have a path Yes, / can be omitted, but it is recommended not to omit it (standard - add before/do not add after)

RequestMapping is supportedBoth Post and Get are available

@RequestMapping("/hello")
@RestController
public class HelloController {
//此时就限定必须使用Get这个方法
//注解没有写属性名字,默认就是value
    @RequestMapping(value = "/sayhi",method = RequestMethod.GET)
    public String sayHi(){
        return "hi,SpringBoot";
    }
}
ask        
1. Pass a single parameter

Underlying logic: Get the value of the parameter named name from the request parameter, and assign a value to name

2. Multiple parameters

The same is true for multiple parameters. The order does not matter. Note⚠️ha, what I said is that age can be replaced with that name.

But if you use basic basic types, you must learn to pass values. If you don't pass values, an error will be reported. Therefore, we uniformly recommend using packaging classes during development.

Backend parameter renaming - must be passed (if renaming is used - the name in the @RequestParam annotation must be used. If your name is different from the annotation, a 400 error will be reported

If we make changes as shown below, although no error will be reported, the parameters will not be passed, which is the default empty value.

  public  String m5(@RequestParam(value = "name",required = false) String username){
        return "接收到的参数:"+username;
    }

What is written above is for web interaction, which can be said to be SpringMVC.

Pay attention to the question mark query string after the url

3. Pass array

When there are multiple parameters of the same parameter in our request

4. Pass a collection, but a 500 error occurred when we passed it here.

Anything starting with 5 usually means an error occurred on the server side.

Anything starting with 4 is often an error on the client side.

If you see an error starting with 5, your first reaction is to look at the back-end log. Read the back-end log from bottom to top, section by section, starting with the first line of the last section.

What he means is that his default is to pass an array, not a collection, so an annotation is needed to declare that it is a collection, so that he can use the collection

 @RequestMapping("/m6")
    public  String m7(@RequestParam List<String> listParam){
    return "接收到的参数ListParam:"+listParam+"长度"+listParam.size();
    }

A brief introduction to JSON

Essentially a string that represents an object, often called a JSON string

If you want to pass annotations, you must use a RequestBody

public  String m4(@RequestBody Person person){
        return "接收到的参数:"+person.toString();
    }

Get parameters in URL

You can get one, or you can get multiple. If you get multiple, you have to fill them in yourself, but you need to pay attention to their order, and after choosing the order, you need to fill in the request (no less)

Transfer the file to a local folder, which is equivalent to what we usually download

 public String m10(@RequestPart MultipartFile file) throws IOException {
        System.out.println(file.getOriginalFilename());
        file.transferTo(new File("/Users/lcl/Desktop/py/" +file.getOriginalFilename()));
        return "success";
    }

Review Cookies and Sessions

Http is stateless ->http has no memory function. The current request and the request after a while, the same request parameters, will get the same result ->The processing logic is the same, not the data.

Cookie is a client-side mechanism, and Session is a server-side mechanism. They are often used together.

Http is stateless - http has no memory function. The current request and the request after a while, with the same request parameters, will get the same result -> The processing logic is the same

Cookie (equivalent to a student ID card, which can check your information)

Understand Session (server mechanism, according to your xx, you can be found with your information)

First of all, we need to understand what a conversation is.

In the computer field, a session is an uninterrupted request response between a client and a server. The server can recognize that the request comes from the same user. When an unknown user sends the first request to the Web application, a session is started. The session ends when the user explicitly ends the session or when the server does not receive any request from any user within a time limit.

The difference between Cookie and Session

Cookie is a mechanism for the client to save information, and Session is a mechanism for the server to save user information.

Cookie and Session are mainly related through SessionId. SessionId is the bridge between Cookie and Session.

Cookie and Session are often used together, but they do not have to be used together.

Two ways to get cookies
下面是两种方式拿到Cookie,第一种是拿到全部的Cookie. 
@RequestMapping("/getCookie")
    public String getCookie(HttpServletRequest request){
        Cookie[]cookies= request.getCookies();
//        for(Cookie cookie:cookies){
//            System.out.println(cookie.getName()+":"+cookie.getValue());
//        }
        if (cookies!=null) {
            Arrays.stream(cookies).forEach(cookie -> {
                System.out.println(cookie.getName() + ":" + cookie.getValue());
            });
        }
        return "获取cookie成功";
    }


    //使用注解的第二个方式,只能一个一个拿
    @RequestMapping("/getCookie2")
public String getCookie2(@CookieValue String bite,@CookieValue String aaa){
        return "cookie存取的值"+bite+",aaa"+aaa;
    }
How to set up Session
 public String setSession(HttpServletRequest request){
        HttpSession session= request.getSession();
        session.setAttribute("username","zhangsan");
        return "success";
    }
Problem getting Session
//方法1:(原始版本,刚开始session为空。)
@RequestMapping("/getSession")
    public String getSession(HttpServletRequest request){
    HttpSession session= request.getSession(false);
    if(session!=null){
        String username=(String) session.getAttribute("username");
        return "登录用户"+username;
    }
    return "session为空";
}
方法2:
@RequestMapping("/getSession2")
//默认是一个必须传递的参数,所以加上false(这样你不传递参数也不会报错)
public  String getSession2(@SessionAttribute (required = false) String username){
        return "username:"+username;
}
方法3: Spring有一个内置的对象,和第一种方式相像,可以直接使用HttpSession等同于第一种的那个
request.Session(true)
@RequestMapping("/getSession3")
//内置对象,在需要的时候,加上即可,不需要的时候可以不写
public String getSesson3(HttpSession session){
        String username=(String) session.getAttribute("username");
        return "登入用户"+username;
}
Get Header information in Http request
@RequestMapping("/getHeader")
public  String getHeader(HttpServletRequest request){
//User-Agent相当于是一个key
       String userAgent= request.getHeader("User-Agent");
       return "userAgent"+userAgent;
}
@RequestMapping("/getHeader2")
public String getHeader(@RequestHeader("User-Agent")String userAgent){
        return "userAgent"+userAgent;
}

Guess you like

Origin blog.csdn.net/weixin_72953218/article/details/134538620