springMVC project learning 01

springMVC project configuration


Tip: The following is the content of this article, the following cases are for reference

1 springMVC learning

1.1 springMVC传参

1.1.1 Request path parameter transmission

 //请求路径传参数
    @RequestMapping("/t1")
    public  void test1(String name,Integer age){
    
    
        //servlet中需要频繁的强制转换,springMVC框架可以自动转换
        System.out.println("name:"+name);
        System.out.println("age:"+age);

    }

1.1.2 Obtaining parameters through the HttpServletRequest object

Import servlet-api dependency

<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>3.1.0</version>
    <scope>provided</scope>
</dependency>

The shortcut key of the output statement System.out.println(); in IDEA: sout

//通过HttpServletRequest对象获取参数
    @RequestMapping("/t2")
    public  void test2(HttpServletRequest request){
    
    
        String name = request.getParameter("name");
        String age = request.getParameter("age");
        System.out.println("name:"+name);
        System.out.println("age:"+age);

    }

1.1.3 Pass the name attribute value of the form as a parameter to the background

1.1.3.1 get request

1.1.3.1.1 get request implementation

First create a new form jsp page (request with get, default get), add action="/t3" method="get" to the form tag (t3 is the background @RequestMapping("/t3"))

<%--
  Created by IntelliJ IDEA.
  User: 16338
  Date: 2021/2/23
  Time: 13:57
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<form action="/t3" method="get">
    <p>
        用户名:<input type="text" name="username" placeholder="请输用户名">
    </p>
    <p>
        密码:<input type="password" name="pwd" placeholder="请输密码">
    </p>
    <p>
        邮箱:<input type="text" name="email" placeholder="请输邮箱">
    </p>
    <p>
        <input type="submit" value="注册">
    </p>

</form>
</body>
</html>

Backstage:

//通过表单的name属性值作为参数传到后台
    @RequestMapping("/t3")
    public  void test3(String username,String pwd,String email){
    
    
        System.out.println("username:"+username);
        System.out.println("pwd:"+pwd);
        System.out.println("email:"+email);

    }
    
1.1.3.1.2 Dealing with garbled codes in get requests

Dealing with garbled code in get requests: add uriEncoding tag to tomcat dependency and use utf-8

<!-- 导入tomcat插件-->
        <plugin>
          <groupId>org.apache.tomcat.maven</groupId>
          <artifactId>tomcat7-maven-plugin</artifactId>
          <version>2.2</version>
          <configuration>
            <port>8066</port>
            <path>/</path>
            <uriEncoding>utf-8</uriEncoding>
          </configuration>
        </plugin>

1.1.3.2 post request

1.1.3.2.1 Post request implementation

If the form is changed to a post request, the
background @RequestMapping is changed to:

 @RequestMapping(value = "/t3",method = RequestMethod.POST)
1.1.3.2.2 Handling the garbled problem of post request

Dealing with garbled code
in post requests: add a filter to the web-app tag of the web.xml file

<!-- 乱码处理filter过滤器 -->
  <filter>
    <filter-name>encodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>

    <!-- 指定编码集 -->
    <init-param>
      <param-name>encoding</param-name>
      <param-value>utf8</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>encodingFilter</filter-name>

    <!-- 指定拦截方式 -->
    <url-pattern>/*</url-pattern>
  </filter-mapping>

1.1.3.3 get and post requests

If both get and post requests in the form are available, the
background @RequestMapping is changed to:

 @RequestMapping(value = "/t3",method = {
    
    RequestMethod.POST,RequestMethod.GET})

1.1.4 Encapsulated entity class passing parameters

If there are many parameters
submitted in the form, it is not appropriate to use test3 to pass the parameters. Therefore, for the form with many parameters, you can use the name attribute value of the form to encapsulate the object, and pass the object to the server to
ensure that the attributes and form of the encapsulated object are guaranteed. If the name attribute value is the same, SpringMVC will complete the automatic encapsulation

For example, encapsulate the name attribute in the form to the User class
, create a new User class in the pojo package, and generate the attribute get set toString method

package com.qst.pojo;

public class User {
    
    
    //这个类属性表单name属性一致
    private Integer id;
    private String username;
    private String pwd;
    private String email;

    //生成 get set toString 方法

    public Integer getId() {
    
    
        return id;
    }

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

    public String getUsername() {
    
    
        return username;
    }

    public void setUsername(String username) {
    
    
        this.username = username;
    }

    public String getPwd() {
    
    
        return pwd;
    }

    public void setPwd(String pwd) {
    
    
        this.pwd = pwd;
    }

    public String getEmail() {
    
    
        return email;
    }

    public void setEmail(String email) {
    
    
        this.email = email;
    }

    @Override
    public String toString() {
    
    
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", pwd='" + pwd + '\'' +
                ", email='" + email + '\'' +
                '}';
    }
}

Use the encapsulated User class directly in the background

@RequestMapping(value = "/t5",method = RequestMethod.POST)
    public void tset5(User user){
    
    
        System.out.println(user);
    }

1.1.4 Use ajax to pass parameters

slightly

1.2 How does the server respond to data to the client

1.2.1 Use ModelAndView to encapsulate views and models

New test.jsp

<%--
  Created by IntelliJ IDEA.
  User: 16338
  Date: 2021/2/24
  Time: 10:16
  To change this template use File | Settings | File Templates.
--%>
<%@page isELIgnored="false" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<%--EL表达式--%>
<h2>欢迎 ${username} 登录系统</h2>
</body>
</html>

Create a new Test1Controller class in the background:

/*服务端如何响应数据给客户端*/
@Controller
@RequestMapping("/admin")//访问:localhost:8066/admin/t1
public class Test1Controller {
    
    
    //使用ModelAndView 封装视图和模型
    @RequestMapping("/t1")
    public ModelAndView test1(ModelAndView modelAndView){
    
    
        //使用ModelAndView封装数据
        modelAndView.addObject("username","张三");
        //使用ModelAndView封装视图
        modelAndView.setViewName("test");//视图名称
        return modelAndView;
    }
}

1.2.2 Use Model object to encapsulate data return

Change the EL expression on the test.jsp page.
Backstage:

//使用Model对象封装数据返回
    @RequestMapping("/t2")
    public String test2(Model model){
    
    
        model.addAttribute("address","江苏如皋");
        model.addAttribute("price","888");
        return "test";
    }

1.2.3 Use HttpServletRequest to bind data

Change the EL expression on the test.jsp page.
Backstage:

//使用HttpServletRequest绑定数据
    @RequestMapping("/t3")
    public String test3(HttpServletRequest request){
    
    
        request.setAttribute("address","江苏如皋");
        request.setAttribute("price","888");
        return "test";//视图名 默认是转发
    }

1.2.4 Use HttpSession to bind data

Change the EL expression on the test.jsp page.
Backstage:

//使用HttpSession绑定数据
    @RequestMapping("/t4")//HttpServletRequest request或传HttpSession,HttpServletRequest里包含HttpSession
    public String test4(HttpServletRequest request){
    
    
        HttpSession session = request.getSession();
        //使用session绑定数据
        session.setAttribute("name","张三");
        session.setAttribute("code","7799");
        return "test";//视图名 默认是转发
    }

1.2.5 Use ServletContext to bind data

Change the EL expression on the test.jsp page.
Backstage:

//使用ServletContext绑定数据
    @RequestMapping("/t5")
    public String test5(HttpServletRequest request){
    
    
        ServletContext context = request.getServletContext();
        //使用context绑定数据
        context.setAttribute("email","[email protected]");
        context.setAttribute("code","7788");
        return "test";//视图名 默认是转发
    }

1.2.6 Use HttpServletResponse response object

Change the EL expression on the test.jsp page.
Backstage:

//使用HttpServletResponse响应对象
    @RequestMapping("/t6")
    public void test6(HttpServletResponse response)throws IOException {
    
    
        response.setContentType("text/html;charset=utf-8");
        PrintWriter writer = response.getWriter();
        writer.write("code:7788");
    }

1.3 json

Now company page views often use html, because it is fast and efficient.
HTML often sends ajax requests, the data type returned by the server is called json, and jsp can also send ajax requests.
Advantages: Lightweight, clear structure, fast parsing speed.
JSON format such as:
"{"name":"zhangsan","age":10}"
is "{key:value,key:value,key:value…}"
Import plugin

<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.9.8</version>
</dependency>

Backstage:

//将一个对象转成json字符串输出
    //在Springmvc中提供了一个注解@ResponseBody, 能够将字符串、对象、集合转成JSON字符串
    @RequestMapping("/t7")
    @ResponseBody
    public User toJson1(){
    
    
        //首先给User封装数据
        User user = new User();
        user.setId(1);
        user.setUsername("张三");
        user.setPwd("123456");
        user.setEmail("[email protected]");
        //会以JSON格式输出{"id":1,"username":"张三","pwd":"123456","email":"[email protected]"}
        return user;
    }

Insert picture description here

Guess you like

Origin blog.csdn.net/qq_43881663/article/details/113992974