Java-SpringMVC-2(数据返回网页,全局处理异常类,拦截器)

一、Controller层数据返回网页回显

1.保存在request中

request的作用范围:同一个请求中有效

request.setAttribute(key(键),value(值)),可以将数据存放在当前

request中.

前端调用使用${键名}

 @RequestMapping(value = "m1")
    public String m1(HttpServletRequest request){
        //存放在request中
        Student student=new Student("王五",new Date(),1,"南京");
        request.setAttribute("s",student);
        return "index.jsp";
    }

2.保存在Model中

model的作用等同于request,也相当于保存在同一个请求中。

如果使用request的话相当于你和tomcat容器绑定了, 建议使用Model。

model.addAttribute(key(键),value(值)),将数据存放在当前model中(等同于存放在request中)

前端获取的方法与request一样

@RequestMapping(value="mo1")
    public String mo1(Model model){
        //model与request一样
        Student student=new Student("张三",new Date(),1,"武汉");
        //将数据存入到model中
        model.addAttribute("m1",student);
        return "mod.jsp";
    }

3.保存在session中

session的作用范围:在同一个会话中有效,会话不关闭就一直有效。

session.setAttribute(key(键),value(值)),可以将数据存在当前session中

 @RequestMapping(value ="mo2")
    public String mo2(HttpSession session){
        Student student=new Student("李四",new Date(),1,"武汉");
        //存放数据到session中
       session.setAttribute("s",student);
        return "mod.jsp";
    }

4.Model如何等价与session

model等价于request

我们也可以位model加上一个注解将其升级位于session等价

@SessionAttributes(value = "")

value中写需要变为session的,存储在request中的键名

@SessionAttributes(value = "s")//s与下方存放在request中的键名对应
@RequestMapping(value = "m1")
    public String m1(HttpServletRequest request){
        Student student=new Student("王五",new Date(),1,"南京");
        //存放在request中的数据
        request.setAttribute("s",student);
        return "index.jsp";
    }

二、重定向跳转

我们通常 return返回一个字符串如果写的是页面就相当于请求转发

想要将页面进行重定向跳转需要用到 redirect

 @RequestMapping(value ="mo2")
    public String mo2(HttpSession session){
        Student student=new Student("李四",new Date(),1,"武汉");
       session.setAttribute("s",student);
       //springmvc看到返回的字符串中含有redirect时,spring会认为你要重定向跳转
        return "redirect:mod.jsp";
    }

三、SpringMVC返回json数据

当我们使用异步请求时需要我们controller返回一个json数据来给前台

之前我们在servlet中返回数据使用阿里巴巴的fastjson将java对象手动的转为json格式的数据,使用ot.print(json)将数据数据输出给前台。

SpringMVC返回json数据需要以下几步

1.引入springmvc中内置的转换json格式的jar包,jackson

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.13.2.2</version>
  </dependency>

2.在controller层加上@ResponseBody注解

 @RequestMapping(value = "json1")
    @ResponseBody
    public List<Student> json1(){
        List<Student> list=new ArrayList<Student>();
        list.add(new Student("李四",new Date(),1,"武汉"));
        list.add(new Student("王五",new Date(),1,"郑州"));
        return list;
    }

这样我们就完成了json格式的转换

四、将json日期类型(毫秒)转为正常日期格式(yyyy-MM-dd)

我们只需要在实体类的日期属性中加上@JsonFormat(pattern = "yyyy-MM-dd")注解

pattern:可以定义日期格式

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Student {
    private String name;
    @DateTimeFormat(pattern = "yyyy-MM-dd")
    @JsonFormat(pattern = "yyyy-MM-dd")
    private Date birthday;
    private int sex;
    private String address;

}

五、SpringMVC全局异常处理类

作用:

全局异常处理类的作用: 当controller发生异常,则有全局异常类来处理并执行相应的处理方法。

使用全局异常处理类

1.@ControllerAdvice注解

创建一个全局异常处理类并为其加上@ControllerAdvice注解

@ControllerAdvice
public class Exhandler {
    @ExceptionHandler(value = RuntimeException.class) //当发生RuntimeException就会触发该方法
    //@ExceptionHandler(value = Exception.class) //当发生Exception就会触发该方法
    @ResponseBody
    public Map error(){
       Map map=new HashMap();
       map.put("code","5000");
       map.put("msg","出现错误");
       return map;
    }
}

2.在spring,xml中扫描异常处理类

一定要保证扫描包时一定可以扫描到异常处理类

六、SpringMVC拦截器

作用:过滤掉某些资源

作用范围:只会拦截controller层的资源路径

使用拦截器:

1.创建一个拦截器类,并实现HandlerInterceptor接口,重写preHandle方法

//1.实现implements HandlerInterceptor
public class Myinterceptors implements HandlerInterceptor {
    //2.重写preHandle方法
    public boolean preHandle(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response, java.lang.Object handler) throws java.lang.Exception {
        System.out.println("经过了过滤器");
        //3.true表示通过,false表示不通过
        return true;
    };
}

2.将创建的拦截器类注册到spring.xml配置文件中

 <!--拦截器-->
    <mvc:interceptors>
        <mvc:interceptor>
            <!--mapping:表示需要经过拦截器的路径-->
            <!--/**:表示n层路径,/*:表示一层路径-->
            <mvc:mapping path="/**"/>
            <mvc:mapping path="json1"/>
            <!--exclude-mapping:可以社长哪些路径不需要经过过滤器-->
            <mvc:exclude-mapping path="mo2"/>
            <!--bean:表示自己定义的拦截器所在的路径-->
            <bean class="com.gsh.interceptors.Myinterceptors"/>
        </mvc:interceptor>
    </mvc:interceptors>

*3.实现拦截未登录进入主页面

(1)再xml文件中配置拦截器的路径

<!--拦截器-->
    <mvc:interceptors>
        <mvc:interceptor>
            <!--"mapping:需要拦截的路径 /**:表示n层路径 /*表示一层路径"-->
            <mvc:mapping path="/**"/>
             <!--设置不拦截的路径-->
            <mvc:exclude-mapping path="/user/login/**"/><!--如果有多级我们需要逐级进行拦截-->
            <mvc:exclude-mapping path="/css/**"/>
            <mvc:exclude-mapping path="/js/**"/>
            <mvc:exclude-mapping path="/images/**"/>
            <!--自己定义的拦截器路径-->
            <bean class="com.gsh.interceptor.LoginInterceptor"/>
        </mvc:interceptor>
    </mvc:interceptors>

(2)创建过滤器

//实例化接口
public class LoginInterceptor implements HandlerInterceptor {        
    //重写pre方法
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //编码格式
        response.setContentType("application/json;charset=utf-8");
        //判断session钟是否有值
        HttpSession session = request.getSession();
        //获取session中的值
        Object user = session.getAttribute("user");
        if(user!=null){
            return true;
        }
        PrintWriter writer = response.getWriter();
        CommonResult result=new CommonResult(5001,"请先登录",null);
        ObjectMapper objectMapper=new ObjectMapper();
        String json = objectMapper.writeValueAsString(result); //把java对象转换为json字符串。
        writer.print(json);
        writer.flush();
        writer.close();
        return false;
    }

}

(3)改前端页面

                //查询所有方法,页面加载就会调用的方法
                initTable(){
                    var that=this;
                    axios.get("student/findAll").then(function (result){
                        //判断状态码
                        if(result.data.code===2000) {
                            that.tableData = result.data.data;
                        }else if(result.data.code===5001){
                            //如果没登录就进入主界面就会弹出错误信息
                            that.$message.error(result.data.msg);
                            //跳转到登录界面
                            location.href="login.jsp"
                        }
                        else {
                            that.$message.error(result.data.msg);
                        }
                    })
                },

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值