Spring MVC 学习日志2.请求参数处理+请求映射(使用IDEA)

1、配置maven项目步骤

(1)在pom.xml中添加依赖,配置spring-mvc

    <!--1.加入依赖-->
    <dependencies>
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.2.6.RELEASE</version>
        </dependency>
    </dependencies>

(2)修改项目为WebApplication

(3)添加配置(Add Configuration),使用Tomcat服务器,配置部署虚拟路径,并在WEB-INF文件夹下创建lib文件夹,将maven的jar包导入

(4)在resources文件夹下新建spring-mvc.xml,配置扫描包

(5)配置web.xml,使用DispatcherServlet以及拦截请求配置

(6)编写控制器Controller类

1.1、spring-mvc.xml(静态资源访问配置)

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"

       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">

        <!-- 扫描包 -->
        <context:component-scan base-package="cn.tulingxueyuan"></context:component-scan>
        <!--配置访问静态资源-->
        <!--底层会用新的实现类处理 -->
        <mvc:annotation-driven/>
        <!--mapping:请求  location:资源所在文件夹-->
        <!--1.将映射的地址直接指向静态资源文件夹,springmvc将不会将此映射作为handler-->
        <mvc:resources mapping="/images/**" location="/images/"/>
        <!--2.当springmvc没有映射到一个某请求时,就会调用默认servlet处理-->
        <!--<mvc:default-servlet-handler></mvc:default-servlet-handler>-->

</beans>

2、请求参数(基本数据类型以及复杂数据类型)

2.1、jsp文件

<%--
  Created by IntelliJ IDEA.
  User: lenovo
  Date: 2021/1/22
  Time: 21:57
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Ti tle</title>
</head>
<body>
    <h2>简单参数演示</h2>
    <%-- 表单元素的名字要与action 调用的请求(params01)处理方法一致--%>
    <form action="${pageContext.request.contextPath}/params01" method="post">
        <%-- 表单元素的名字要与action 调用的请求(params01)处理方法一致
            因为客户端的根目录是在localhost:8080/这一级,而请求要在localhost:8080/springmvc/这一级
            所以action要等于动态获取的目录。
        --%>
    姓名:<input  name="username" type="text"><p></p>
    <input type="submit" value="提交">
    </form>


    <h2>复杂参数演示</h2>
    <%-- 表单元素的名字要与action 调用的请求(params01)处理方法一致--%>
    <form action="${pageContext.request.contextPath}/params02" method="post">
        <%-- 表单元素的名字要与action 调用的请求(params01)处理方法一致
            因为客户端的根目录是在localhost:8080/这一级,而请求要在localhost:8080/springmvc/这一级
            所以action要等于动态获取的目录。
        --%>
    <%--
    private Integer id;
    private String name;
    private String[] alias; // 外号
    private List<String> hobbies; //爱好
    private Map<String,String> relatives; //亲属
    private Role role;
    private List<User> friends; //朋友
    --%>
        id:<input  name="user.id" type="text"><p></p>
        姓名:<input  name="user.name" type="text"><p></p>
        <%--value属性在浏览器看不到,但是value才会传到服务器--%>
        <%--当是List这样有序的数据结构时,
            List<基本数据类型> 不用加下标,如下面hobbies
            List<定义的类> 要加下标,如下面relatives
        --%>
        外号:<input  name="user.alias" type="checkbox" value="小野" checked>小野
             <input  name="user.alias" type="checkbox" value="狗剩" checked>狗剩 <p></p>
        爱好:<input  name="user.hobbies" type="checkbox" value="唱歌" checked>唱歌
        <input  name="user.hobbies" type="checkbox" value="跳舞" checked>跳舞 <p></p>
        亲属:<input  name="user.relatives['father']" type="checkbox" value="爸爸" checked>爸爸
        <input  name="user.relatives['mom']" type="checkbox" value="妈妈" checked>妈妈 <p></p>

        角色:<input  name="user.role.name" type="text" > <p></p>
        朋友:<input  name="user.friends[0].name" type="text" value="张三"> <br>
            <input  name="user.friends[1].name" type="text" value="李四"><p></p>

        <h2>新增角色</h2>
        id:<input  name="role.id" type="text" > <p></p>
        name:<input  name="role.name" type="text" > <p></p>
            <input type="submit" value="提交">
    </form>

</body>
</html>

2.2、web.xml(拦截请求配置以及post中文乱码过滤器配置、html不支持put、delete解决过滤器配置)

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">
        <servlet>
            <servlet-name>springmvc</servlet-name>
            <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
            <init-param>
                <param-name>contextConfigLocation</param-name>
                <param-value>classpath:spring-mvc.xml</param-value>
            </init-param>
            <load-on-startup>1</load-on-startup>
        </servlet>
        <servlet-mapping>
            <servlet-name>springmvc</servlet-name>
            <url-pattern>/</url-pattern>
        </servlet-mapping>
        <!-- 配置编码过滤器 CharacterEncodingFilter 解决post中文乱码问题 编码过滤器一定写在所有过滤器的前面-->
        <filter>
            <filter-name>characterEncodingFilter</filter-name>
            <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
            <!-- encoding 编码格式-->
            <init-param>
                <param-name>encoding</param-name>
                <param-value>UTF-8</param-value>
            </init-param>
            <!-- 同时开启请求和响应的编码设置-->
            <init-param>
                <param-name>forceEncoding</param-name>
                <param-value>true</param-value>
            </init-param>
        </filter>
        <!-- 配置拦截哪些请求进行过滤-->
        <filter-mapping>
            <filter-name>characterEncodingFilter</filter-name>
            <!-- 拦截规则-->
            <!--
                <url-pattern></url-pattern> 根据url请求进行匹配 *
                <servlet-name>springmvc</servlet-name> 指定具体过滤哪个servlet
            -->
            <servlet-name>springmvc</servlet-name>
        </filter-mapping>
        <!--处理HTML不支持PUT、DELETE的问题-->
        <filter>
            <filter-name>hiddenHttpMethod</filter-name>
            <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
        </filter>
        <filter-mapping>
            <filter-name>hiddenHttpMethod</filter-name>
            <servlet-name>springmvc</servlet-name>
        </filter-mapping>

<!--
    <filter>
        <filter-name>xxxfilter</filter-name>
        <filter-class>自定义过滤器</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>hiddenHttpMethod</filter-name>
        <servlet-name>springmvc</servlet-name>
        <dispatcher>FORWARD</dispatcher>
    </filter-mapping>

    -->

</web-app>

2.3、ParasController(使用@RequestParam注解 管理请求参数)

package cn.tulingxueyuan.controllers;

import cn.tulingxueyuan.entity.Role;
import cn.tulingxueyuan.entity.User;
import cn.tulingxueyuan.entity.UserDTO;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 *
 *
 * 处理请求参数
 * 之前使用servlet 需要自己绑定参数
 * requset.getParameter("name")
 * 在spingmvc中只需要在处理方法中声明对应的参数就可以自动接受请求的参数并且自动转换类型
 * 自动转换体现在
 * servlet api:
 *  if(requset.getParameter("name")!=null){
 *      /转换
 *  }
 *  报错400:参数问题
 *  匹配规则:
 *  请求的参数名必须与处理方法的参数名一致
 *  如果未传入参数,会自动传入null
 *  如果请求的参数名必须与处理方法的参数名不一致:
 *  可以利用 @RequestParam 管理请求参数,用了此注解后,必须要传入参数值否则报错400
 *  value 用来重命名参数
 *  required 用来指定参数是否必须传入值
 *      true(default) 必须要传入,否则报错
 *      false 可以不传入
 *      :
 *      注意:不用用基础类型,因为他不能接受null,要用包装类
 * defaultValue(默认值):当参数为null时自动设置一个默认值
 *      注意:当设置了默认值时,可以省略flase
 *  处理请求参数乱码:
 *      GET:直接设置tomcat目录下conf/server.xml 里的<Connector URIEncoding="utf-8"></Connector>
 *      POST:
 *          (1)在使用servlet时期:
 *              在每个处理请求的方法内,获取参数之前,设置request.setCharacterEncoding("utf-8")
 *              这样,非常麻烦,所以我们选择使用过滤器解决编码问题(终极解决方式)
 *          (2)使用springmvc提供的编码过滤器解决乱码问题:CharacterEncodingFilter,在web.xml配置
 *    复杂数据类型
 *      对象:不用加上参数名字(不用对象的具体名字),直接传入该对象对应的属性名字
 *          如果是包装类的基础数据类型,直接输入属性名字=表单元素的name,如name="id"
 *          如果是数组,要保证这一组表单元素都是同样的name,如name="alias"
 *          List:必须加上[索引],如name="list[0]" List<User> :name="list[0].name"
 *          Map:必须加上[key],如name="map['key']"
 *          实体类:只能给某个属性去赋值 name="object.xxx"
 *      注意:如果出现多个对象参数的情况(如User user,Role role),只能再次封装一层javaBean(DTO: data transfer object)
 */
@Controller
public class ParasController {
    @RequestMapping("/params01")
    public String params01(@RequestParam(value="username",required = false,defaultValue = "qqa") String name){
        System.out.println(name);
        return "/index.jsp";
        // return "redirect:index.jsp";
    }

    /**
     * 复杂数据类型参数自动绑定
     * @param
     * @return
     * User类有id,name;Role类也有id,name;无法正确的自动绑定
     * @param userDTO
     * @return
     */
    @RequestMapping("/params02")
    public String params02(UserDTO userDTO){//(User user, Role role){
        System.out.println(userDTO);
        return "/index.jsp";
    }

    /**
     * 抓取请求头信息
     * @RequestHeader 注解
     * 里面也有 required 和 defaultValue
     * servelt:request.getHeader()
     * @param host
     * @return
     */
    @RequestMapping("/header")
    public String header(@RequestHeader("Host") String host){
        System.out.println(host);
        return "/index.jsp";
    }

    /**
     *  抓取cookie的值
     *  servlet:
     *      Cookie [] cookies  = request.getCookies();
     *      for(Cookie cookie:cookies){
     *          if(cookie.getValue.equals("JSESSIONID")){
     *              //getName
     *          }
     *
     *      }
     * @param jsessionId
     * @return
     */
    @RequestMapping("/cookie")
    /*获取所有cookie:@CookieValue Map<Stirng,String>*/
    public String cookie(@CookieValue("JSESSIONID") String jsessionId){
        System.out.println(jsessionId);
        return "/index.jsp";
    }

    /**
     * servlet原生支持,获取servlet api
     * 可以和springmvc结合起来一起用,会自动绑定
     * @param username
     * @param request
     * @param response
     * @return
     * @throws IOException
     */
    @RequestMapping("/servlet")
    public String servlet(String username,HttpServletRequest request, HttpServletResponse response)throws IOException {
        request.getSession();
        request.getUserPrincipal();
        request.getLocale();
        response.getWriter();
        response.getOutputStream();
        String name = request.getParameter("name");
        request.setAttribute("name",name);
        System.out.println(name);
        return "/index.jsp";
    }
    /**
     *
     * @param user
     * @return
     *     @RequestMapping("/params02")
     *     public String params02(User user){
     *         System.out.println(user);
     *         return "/index.jsp";
     *     }
     */


    /**
     *     public String params01(@RequestParam("username") String name){
     *         System.out.println(name);
     *         return "/index.jsp";
     *         // return "redirect:index.jsp";
     *     }
     */

    /**
     *     public String params01(String name){
     *         System.out.println(name);
     *         return "/index.jsp";
     *         // return "redirect:index.jsp";
     *     }
     */


    /**
     *
     *     public String params01(Integer age){
     *         System.out.println(age);
     *         return "/index.jsp";
     *     }
     *
     *
     *
     */
}

2.4、数据传输对象(Data Transfer Object 数据传输对象,再次封装,防止自动绑定参数混淆)

package cn.tulingxueyuan.entity;

//UserDTO(User Data Transfer Object 用户数据传输对象)
public class UserDTO {
    private User user;
    private Role role;

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public Role getRole() {
        return role;
    }

    public void setRole(Role role) {
        this.role = role;
    }

    @Override
    public String toString() {
        return "UserDTO{" +
                "user=" + user +
                ", role=" + role +
                '}';
    }
}

2.5、MappingController(使用@RequestMapping注解 来处理URL映射,将请求映射到处理方法中)

package cn.tulingxueyuan.controllers;

import org.omg.CORBA.Request;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

/**
 *
 *
 *
 * @RequestMapping 用来处理URL映射 将请求映射到处理方法中
 *
 */
@Controller
/**
 * @RequestMapping
 * 除了可以用在方法上,还可以用在类上:
 * (1)将请求的URL模块化
 * (2)解决请求重复的情况,因为基本每一个Controller类都会有增删查改
 *  如果加在类上面,该类所有请求方法的映射都必须加上类的映射:
 *      例如@RequestMapping("/mapping"),请求必须为 /mapping/xxx
 *  参数:
 *      (1)value:设置请求映射名字
 *      (2)method:设置请求方式 GET/POST
 *              可以同时设置多个请求方式:method = {RequestMethod.POST, RequestMethod.GET}
 *              如果不写,可以匹配所有请求方式
 *   从spring4.3开始,提供了一套请求方式的注解
 *     @GetMapping
 *     @PutMapping
 *     @DeleteMapping
 *   (例如@PostMapping("/mapping01"),等同于@RequestMapping(value = "/mapping01",method = {RequestMethod.POST}))
 *   直接通过URL的话是GET请求
 *   错误:HTTP Status 405 – Request method 'GET' not supported (method属性)
 *   params:设置请求必须携带的某些参数
 *      方式:1.必须要有某些参数 例如,必须要有username,params = {"username"}
 *            2.必须没有某些参数 例如,必须不能有username,params = {"!username"}
 *            3.某些参数的值必须要等于什么 例如,params = {"username=wxy"}
 *            4.某些参数的值必须不能等于什么 例如,params = {"username!=wxy"}
 *   headers:请求头必须包含每个值 例如,headers = {"Accept-Language=zh-CN,zh;q=0.9" }
 *   consumes:设置请求内容类型为指定值
 *              常见的请求内容类型:
 *                  1.application/x-www-form-urlencoded form表单提交默认的内容类型(getParameter)
 *                      `consumes = {"application/x-www-form-urlencoded" }
 *                  2.multipart/form-data form表单提交文件流的内容类型
 *                  3.application/json ajax提交的json内容类型
 *   错误:HTTP Status 415 – Unsupported Media Type (请求内容类型不匹配,consumes属性)
 *   produces:设置响应内容类型为指定值
 *      produces = {"application/json" }
 *  映射的URL还可以是通配符 /ANT style
 *      1.? 匹配单个字符(a-z0-9)1
 *      2.* 匹配任意多个字符(a-z0-9)1
 *      3** 匹配任意个字符任意层次 /** /
 *      如果映射存在包含关系,会优先交给更精确的那个映射处理
 *      none>?>*>**
 *      ant? ant*  /** /ant ant
 *      localhost:8080/springmvc/mapping/ant -> ant
 *      localhost:8080/springmvc/mapping/ant1 -> ant?
 *      localhost:8080/springmvc/mapping/ant12 -> ant*
 */
@RequestMapping("/mapping")
public class MappingController {
    //@PostMapping("/mapping01") 等同于下面的写法

    @RequestMapping(value = "/mapping01",method = {RequestMethod.POST, RequestMethod.GET})
    public String mapping01() {
        System.out.println("Mapping success!");
        return "/index.jsp";
    }

    @RequestMapping(value = "/params", params = {"username=wxy"})
    public String mapping03(){
        System.out.println("Request success!");
        return "/index.jsp";
    }

    @RequestMapping(value = "/headers", headers = {"Accept-Language=zh-CN,zh;q=0.9" })
    public String mapping04(){
        System.out.println("Request header mapping!");
        return "/index.jsp";
    }
//   请求的内容类型
    @RequestMapping(value = "/consumes", consumes = {"application/x-www-form-urlencoded" })
    public String mapping02(){
        System.out.println("Request content type mapping!");
        return "/index.jsp";
    }


    //   响应的内容类型
    @RequestMapping(value = "/produces", produces = {"application/json" })
    public String mapping05(){
        System.out.println("Response content type!");
        return "/index.jsp";
    }
    //通配符
    //localhost:8080/springmvc/mapping/ant1
    //?和*都能匹配时,?优先,他更具体,更细粒度
    @RequestMapping(value = "/ant?")
    public String mapping06(){
        System.out.println("通配符之?");
        return "/index.jsp";
    }
    @RequestMapping(value = "/ant*")
    public String mapping07(){
        System.out.println("通配符之*");
        return "/index.jsp";
    }
    @RequestMapping(value = "/**/ant")
    public String mapping08(){
        System.out.println("通配符之**");
        return "/index.jsp";
    }



//    @RequestMapping(value = "/mapping01",method = RequestMethod.POST)
//    public String mapping01() {
//        System.out.println("Mapping success!");
//        return "/index.jsp";
//    }


    //    @RequestMapping("/mapping01")
//    public String mapping01() {
//        System.out.println("Mapping success!");
//        return "/index.jsp";
//    }

}

2.6、PathvariableController(@PathVariable注解,是用在参数上面的(顾名思义,参数变量),专门用来获取URL目录级别的参数)

package cn.tulingxueyuan.controllers;

import cn.tulingxueyuan.entity.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
/*
*   获取URL路径中的值
*   @PathVariable 是用在参数上面的(顾名思义,参数变量)
*   专门用来获取URL目录级别的参数
*   比如:http://localhost:8080/springmvc/path/user/123/qqa
*       想要获得123 @RequestMapping("/user/{id}") @PathVariable("id") Integer id
*
*       如果是单个参数接受的话,必须要使用@PathVariable来声明对应的参数占位符名字
*       如果是JavaBean,则可以省略@PathVariable,但是要保证占位符的名字与JavaBean属性名字一致对应
*
* */
@Controller
@RequestMapping("/path")
public class PathvariableController {
    /**
     *  获取用户实体 传入id
     */
    @RequestMapping("/user/{id}/{username}")
    public String path01(@PathVariable("id") Integer id, @PathVariable("username") String name ){
        System.out.println(id);
        System.out.println(name );
        return "/index.jsp";
    }

    @RequestMapping("/user02/{id}/{username}")
    public String path02(User user ){
        System.out.println(user);
        return "/index.jsp";
    }
}

3.REST:Representantial State Transfer(表述性状态传递) 

客户端映射到服务器资源的一种架构设计

URL restful

一种优雅的URL风格

万维网 http协议 设计时比较随意 URL没有相应的命名规范

混乱:每一个都有一套自己的命名风格

根据id查询一个用户

user/getUser.do?id=1

user.do/action=getUser&id=1

user.do/action=a&id=xx

user.do/chaxunyonghu?id=1

user.do/CXYH?id=1

user.do/quliankeji_cxyh?id=1

user/a.do/action=b?c=xx

四个请求

(1)查询用户:http://localhost:8080/app/user.do?action=getUser&id=xxx GET

(2)增加用户:http://localhost:8080/app/user_add.do POST

(3)修改用户:http://localhost:8080/app/xiugaiuser.do POST

(4)删除用户:http://localhost:8080/app/delete.do?id=1 GET/POST

统一规范

之前的命名方式:使用动词的形式,表示接下来要做什么

REST:面向资源,使用名词的形式

(1)查询用户:http://localhost:8080/xxx/user/1 GET---查询

(2)查询多个用户:http://localhost:8080/xxx/users GET

(3)新增用户:http://localhost:8080/xxx/user POST---新增

(4)修改用户:http://localhost:8080/xxx/user/1 PUT---修改

(5)删除用户:http://localhost:8080/xxx/user/1 DELETE---删除

看URL就知道要什么,看http method 就知道干什么

html不支持put、delete,http支持

3.1、rest.jsp

<%--
  Created by IntelliJ IDEA.
  User: lenovo
  Date: 2021/3/10
  Time: 9:50
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<% request.setAttribute("basepath",request.getContextPath()) ; %>
<html>
<head>
    <title>Title</title>
</head>
<body>

<%--
    <form action="${pageContext.request.contextPath}/rest/user/1" method="get">
    与下面相同
--%>
    <form action="${basepath}/rest/user/1" method="get">
        <input type="submit" value="查询">
    </form>

    <form action="${basepath}/rest/user" method="post">
        id:<input  name="id" type="text"><p></p>
        姓名:<input  name="name" type="text"><p></p>
        <input type="submit" value="新增">
    </form>
    <%--
        html不支持put、delete,但http支持
        SpringMVC框架已经定义好了如何将http设置为put/delete
        我们只需要增加一个hidden隐藏域
        例如:<input type="hidden" value="put" name="_method">
    --%>
    <form action="${basepath}/rest/user/1" method="post">
        <input type="hidden" value="put" name="_method">
        id:<input  name="id" type="text"><p></p>
        姓名:<input  name="name" type="text"><p></p>
        <input type="submit" value="修改">
    </form>

    <form action="${basepath}/rest/user/1" method="post">
        <input type="hidden" value="delete" name="_method">
        <input type="submit" value="删除">
    </form>

</body>
</html>

3.2、

(1)单体服务器(前后端)

RestController.java

package cn.tulingxueyuan.controllers;

import cn.tulingxueyuan.entity.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
/**
 *
 * form 表单提交put和delete出现问题:会将put和delete作为get提交,因为html不支持put和delete
 *      解决:
 *          1.需要添加HiddenHttpMethodFilter过滤器
 *          2.需要在表单中添加一个隐藏域,<input type="hidden" value="put" name="_method"> value就是对应的请求方式
 *          3.将form的method设为post
 *          4.过滤器就会自动将post请求修改成隐藏域对应值(put/delete)得请求
 *
 * tomcat 7以上的版本对request.method更加严格:只支持get/post/head
 * HTTP Status 405 – Method Not Allowed
 *      解决方法1:
 *          1.同tomcat7
 *          2.不用转发用重定向(重定向有两次请求服务)
 *          3.将jsp的page指定isErrorPage属性改成true(isErrorPage,出现错误时,给用户一个友好的界面,后台记录日志)
 *          4.自己写一个filter过滤器,将request.method改回POST
 */

//加到IOC容器当中
@Controller
@RequestMapping("rest")
public class RestController {
    //    查询
    @GetMapping("/user/{id}")
    public String get(@PathVariable("id") Integer id){
        System.out.println("select from user "+id);
        return "/index.jsp";
    }
    //    新增
    @PostMapping("/user")
    public String add(User user){
        System.out.println("insert user "+user);
        return "/index.jsp";
    }
    //    修改
    @PutMapping("/user/{id}")
    public String update(User user){
        System.out.println("update user "+user);
        return "redirect:/index.jsp";
    }
    //    删除
    @DeleteMapping("/user/{id}")
    public String delete(@PathVariable("id") Integer id){
        System.out.println("delete user "+id);
        return "redirect:/index.jsp";
    }


}

(2)服务器api(前后端分离)RestfulController.java

package cn.tulingxueyuan.controllers;

import cn.tulingxueyuan.entity.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.RestController;

/**
 * 基于服务api的方式使用restful api
 * 返回的不是视图名字,而是返后一个json数据
 *
 */

//加到IOC容器当中
@RestController
@RequestMapping("restful")
public class RestfulController {
    //    查询
    @GetMapping("/user/{id}")
    public String get(@PathVariable("id") Integer id){
        System.out.println("select from user "+id);
        return "{'id':'001','name':'qqa'}";
    }
    //    新增
    @PostMapping("/user")
    public String add(User user){
        System.out.println("insert user "+user);
        return "{'msg':'success'}";
    }
    //    修改
    @PutMapping("/user/{id}")
    public String update(User user){
        System.out.println("update user "+user);
        return "{'msg':'success'}";
    }
    //    删除
    @DeleteMapping("/user/{id}")
    public String delete(@PathVariable("id") Integer id){
        System.out.println("delete user "+id);
        return "{'msg':'success'}";
    }


}

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Go语言(也称为Golang)是由Google开发的一种静态强类型、编译型的编程语言。它旨在成为一门简单、高效、安全和并发的编程语言,特别适用于构建高性能的服务器和分布式系统。以下是Go语言的一些主要特点和优势: 简洁性:Go语言的语法简单直观,易于学习使用。它避免了复杂的语法特性,如继承、重载等,转而采用组合和接口来实现代码的复用和扩展。 高性能:Go语言具有出色的性能,可以媲美C和C++。它使用静态类型系统和编译型语言的优势,能够生成高效的机器码。 并发性:Go语言内置了对并发的支持,通过轻量级的goroutine和channel机制,可以轻松实现并发编程。这使得Go语言在构建高性能的服务器和分布式系统时具有天然的优势。 安全性:Go语言具有强大的类型系统和内存管理机制,能够减少运行时错误和内存泄漏等问题。它还支持编译时检查,可以在编译阶段就发现潜在的问题。 标准库:Go语言的标准库非常丰富,包含了大量的实用功能和工具,如网络编程、文件操作、加密解密等。这使得开发者可以更加专注于业务逻辑的实现,而无需花费太多时间在底层功能的实现上。 跨平台:Go语言支持多种操作系统和平台,包括Windows、Linux、macOS等。它使用统一的构建系统(如Go Modules),可以轻松地跨平台编译和运行代码。 开源和社区支持:Go语言是开源的,具有庞大的社区支持和丰富的资源。开发者可以通过社区获取帮助、分享经验和学习资料。 总之,Go语言是一种简单、高效、安全、并发的编程语言,特别适用于构建高性能的服务器和分布式系统。如果你正在寻找一种易于学习使用的编程语言,并且需要处理大量的并发请求和数据,那么Go语言可能是一个不错的选择。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值