• springmvc


    在一个普通的java类上加注解@controller,并开启包扫描的目的是:1.标志这是一个控制层组件,2.交给springioc管理。这样,依赖于spring的springMvc才能够识别这是一个控制器对象

    <context:component-scan base-package="test">context:component-scan>
    <mvc:annotation-driven>mvc:annotation-driven>
    
    • 1
    • 2

    web.xml

    <servlet>
            <servlet-name>springmvcservlet-name>
            <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
            <init-param>
                <param-name>contextConfigLocationparam-name>
                <param-value>classpath:mvc2.xmlparam-value>
            init-param>
    
            <load-on-startup>1load-on-startup>
        servlet>
    
        <servlet-mapping>
            <servlet-name>springmvcservlet-name>
            <url-pattern>/url-pattern>
        servlet-mapping>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    通过配置xml和注解,可以做到依靠注解路径访问浏览器

    @Controller
    @RequestMapping("test")
    public class MyController {
        @GetMapping("ccc")
        @ResponseBody
        public Emp getById(Integer id){
            Emp e = new Emp();
            e.setEmpno(1);
            e.setEname("aaa");
            e.setJob("bbb");
            return e;
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    注解

    接收请求和作出响应时的数据可能是一个复杂对象(实体类),在请求方式是post的情况下,我们只能选择将复杂对象转化为json字符串接收或发送出去
    @ResponseBody 当响应结果是实体,在方法上标注该注解,通过json转换器转换成字符串(也可以注解到类上)
    @RequesBody 当接收参数是实体,在形参旁打上此标注,会将接受的参数转化为对象,一个方法里只能有一个带该注解的参数

    在post请求下,传的参数是json字符串(复杂实体参数)情况下,加@Requesbody才能传

    @JsonInclude(JsonInclude.Include.NON_NULL) 返回类型是json,并且非空不反

    获得servlet对象的方法

    1.当用户发起请求,进入DsipatcherServlet后,把Request与Response封装到:ServletRequestAttributes对象;
    2.把:ServletRequestAttributes对象放在RequestContextHolder类中的线程变量中;

    public class ServletUtil {
    
        public static ServletRequestAttributes getRequestAttribute(){
            RequestAttributes ra = RequestContextHolder.getRequestAttributes();
            return (ServletRequestAttributes)ra;
        }
        public static HttpServletRequest getRequest(){
            return getRequestAttribute().getRequest();
        }
        public static HttpServletResponse getResponse(){
            return getRequestAttribute().getResponse();
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    需要session和servletcontext再从获得的request中拿就可以了

    springmvc 传参

    注解映射地址

    1.@controller+@Responsebody=@RestController
    注册bean并标识是控制层组件并相当于在类上注解@Responsebody
    2.@RequestMapping(“地址”)

    RestUrl

    限定请求方式

    操作请求方式
    添加post
    查询get
    修改pput
    删除delete

    通过描述请求方式和参数定位到具体的资源(方法),格式:

    @RequestMapping(“{参数名}”)

    当参数名与花括号内的名称不一致时,需要@PathVariable来指定路径变量。后面不能跟多个参数
    多个参数不适用resturl方式。直接封成实体类或集合

    //查询
    @GetMapping("emp/{id}") // /test/emp/1
        public Emp getEmpById(Integer id){
            Emp m = new Emp();
            m.setEname("kk");
            m.setEmpno(18);
            m.setJob("kk");
            return m;
        }
    
     @GetMapping("{postid}")
        public String del(@PathVariable("postid") Integer id){
            return "suc";
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    获取域对象

    1.当用户发起请求,进入DsipatcherServlet后,把Request与Response封装到:ServletRequestAttributes对象;
    2.把:ServletRequestAttributes对象放在RequestContextHolder类中的线程变量中;

    public class ServletUtil {
    
        public static ServletRequestAttributes getRequestAttribute(){
            RequestAttributes ra = RequestContextHolder.getRequestAttributes();
            return (ServletRequestAttributes)ra;
        }
        public static HttpServletRequest getRequest(){
            return getRequestAttribute().getRequest();
        }
        public static HttpServletResponse getResponse(){
            return getRequestAttribute().getResponse();
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    异常

    局部异常处理

    @ExceptionHandler(ArithmeticException.class)
    用的少

    全局异常

    全局异常处理,实现HandlerExceptionResolver接口,如果在访问服务器发生异常则自动调用这个类里的resolveException()方法,使用时需要让这个类先进容器(标注解)

    @Component
    public class MyglobalExceptionHandler implements HandlerExceptionResolver {
        @Override
        public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
            HandlerMethod hm = (HandlerMethod) handler;
            System.out.println(hm);
            System.out.println(hm.getMethod()); //会返回调用路径的方法的名字public void test.Test2.t1()
            Class<?> beanType = hm.getBeanType(); //得到异常所在类的类
            ModelAndView mv = new ModelAndView();
            mv.setViewName("error");
            mv.addObject("errorMsg",ex.toString());
            //输出异常所在类的类名和出现异常的方法名
            mv.addObject("name",beanType.getName()+"."+hm.getMethod());
            return mv;
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    缺点:返回的错误信息是固定的,不能返回特定信息

    全局统一异常处理

    其实是aop的通知和局部异常处理结合,在这里只需要一个Exception异常父类和一个自定义异常,就可以对不同的异常做处理了。
    原因:异常父类Exception可以接收任何系统自定义异常,再有响应对象类将异常信息打印出来。自定义异常

    @RestControllerAdvice=@ResponseBudy+@ControllerAdvice
    @ControllerAdvice:控制器增强注解,异常通知

    继承了异常子类的自定义异常方法放上面

    @RestControllerAdvice
    public class GlobalException {
        @ExceptionHandler(MvcException.class)
        public AioxsMsg doException(MvcException m){
            System.out.println(m.getE().getMsg());
            return AioxsMsg.fail(m.getE()); //返回错误信息枚举类
        }
    
        @ExceptionHandler(Exception.class)
        public AioxsMsg doException(Exception e){
            System.out.println(e.getMessage());
            return AioxsMsg.fail(e.getMessage()); //返回错误信息字符串
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    抛出异常

    @PostMapping("me2")
        public void t2(){
            throw new MvcException(E.NO_USER);
        }
    
    • 1
    • 2
    • 3
    • 4

    响应对象

    通常由枚举和响应类组成,用来给前端返回响应消息
    响应对象类

    @JsonInclude(JsonInclude.Include.NON_NULL)
    public class AioxsMsg {
        private Integer code;
        private String msg;
        @JsonInclude(JsonInclude.Include.NON_NULL)
        private Object data;
    
        public AioxsMsg() {
        }
    
        public AioxsMsg(E e, Object data) {
            this.code = e.getCode();
            this.msg = e.getMsg();
            this.data = data;
        }
    
        public AioxsMsg(E e) {
            this.code = e.getCode();
            this.msg = e.getMsg();
        }
    
        //成功则把状态码和对象传回去,并再把返回的消息封装回响应对象
        public static AioxsMsg suc(E e,Object data){
            return new AioxsMsg(E.SUC,data);
        }
    
        public static AioxsMsg fail(E e,Object data){
            return new AioxsMsg(E.FAIL,data);
        }
    
        public static AioxsMsg fail(E e){
            return new AioxsMsg(e);
        }
    
        public static AioxsMsg fail(Object data){
            return new AioxsMsg(E.FAIL,data);
        }
        public Integer getCode() {
            return code;
        }
    
        public void setCode(Integer code) {
            this.code = code;
        }
    
        public String getMsg() {
            return msg;
        }
    
        public void setMsg(String msg) {
            this.msg = msg;
        }
    
        public Object getData() {
            return data;
        }
    
        public void setData(Object data) {
            this.data = data;
        }
    
        @Override
        public String toString() {
            return "AioxsMsg{" +
                    "code=" + code +
                    ", msg='" + msg + '\'' +
                    ", data=" + data +
                    '}';
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70

    枚举

    public enum E {
        SUC(2000,"SUC"),
        FAIL(2001,"FAIL"),
        NO_USER(3000,"该用户不存在")
        ;
        private Integer code;
    
        public Integer getCode() {
            return code;
        }
    
        public void setCode(Integer code) {
            this.code = code;
        }
    
        public String getMsg() {
            return msg;
        }
    
        public void setMsg(String msg) {
            this.msg = msg;
        }
    
        private String msg;
    
        E(Integer code, String msg) {
            this.code = code;
            this.msg = msg;
        }
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
  • 相关阅读:
    iperf
    自动化运维?看看Python怎样完成自动任务调度 ⛵
    050:mapboxGL加载geojson数据,同时包含点、多边形的处理示例
    centos7最简洁的搭建samba服务器
    [AIGC] 字节跳动面试题:简单说说 JVM 的垃圾回收机制
    【小沐学C++】C++ 基于Premake构建工程项目(Windows)
    【node进阶】深入浅出前后端身份验证(下)---JWT
    博世集团启动量子数字孪生计划
    环境变量:JAVA_HOME、PATH 和 CLASSPATH 区别
    【9种优化算法比较】CGO、SCA、GWO、CSA、SSA、HHO、WOA、PSO、TSO智能优化算法比较(Matlab代码实现)
  • 原文地址:https://blog.csdn.net/weixin_43775723/article/details/126670059