SpringMVC02:返回值、json数据、文件上传、拦截器

 一、响应返回值
1、搭建环境(两个webapp,不要选错)
2、响应之返回值是String类型
package cn.itcast.controller;
import cn.itcast.domain.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/user")
public class UserController {
    @RequestMapping("/testString")
    public String testString(Model model){
        System.out.println("testString方法执行了");
        //模拟从数据库中查询数据库的User对象
        User user = new User();
        user.setUsername("美美");
        user.setPassword("123");
        user.setAge(19);
        //model对象
        model.addAttribute("user",user);
        return "success";
    }
}
3、响应之返回值是void类型
package cn.itcast.controller;

import cn.itcast.domain.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

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

@Controller
@RequestMapping("/user")
public class UserController {
    /**
     * 返回值类型是void
     * 请求转发一次请求,不用去编写项目的名称
     * @param request
     * @return
     */
    @RequestMapping("/testVoid")
    public void testVoid(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("testVoid方法执行了");
        //编写请求转发的程序
        //request.getRequestDispatcher("/WEB-INF/pages/success.jsp").forward(request,response);
        //也可以选择重定向,相当于发送了新的请求,需要加项目路径
        //response.sendRedirect(request.getContextPath()+"/index.jsp");
        //也可能会直接进行响应--直接发请求
        //设置中文乱码
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        response.getWriter().print("你好");
        return;
    }
}
4、响应之返回值是ModelAndView类型
package cn.itcast.controller;

import cn.itcast.domain.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

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

@Controller
@RequestMapping("/user")
public class UserController {
    //之前类型的底层也都是ModelAndView
    /**
     * testModelAndView
     * @return ModelAndView 对象
     */
    @RequestMapping("/testModelAndView")
    public ModelAndView testModelAndView(){
        //创建ModelAndView对象
        ModelAndView mv = new ModelAndView();
        System.out.println("testModelAndView方法执行了");
        //模拟从数据库中查询数据库的User对象
        User user = new User();
        user.setUsername("美美");
        user.setPassword("123");
        user.setAge(19);
        //把user对象存储到mv对象中,也会把user对象存入到request对象中
        mv.addObject("user",user);
        //跳转到哪个页面
        mv.setViewName("success");//利用视图解析器进行跳转
        return mv;
    }
}
5、响应之使用forward和redirect进行页面跳转(转发和重定向的关键字)
此时无法使用视图解析器ModelAndView
<a href="user/testForwardOrRedirect">testForwardOrRedirect</a>

package cn.itcast.controller;
import cn.itcast.domain.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Controller
@RequestMapping("/user")
public class UserController {
    /**
     * 使用关键字的方式进行转发或重定向
     * @return
     */
    @RequestMapping("/testForwardOrRedirect")
    public String testForwardOrRedirect(){
        System.out.println("testForwardOrRedirect方法执行了");
        //请求的转发
        return "forward:/WEB-INF/pages/success.jsp";//表明使用请求转发
        //重定向
        //return "redirect:/index.jsp";
    }
}
二、响应json数据
1、响应json数据之过滤静态资源
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
    <%--引入JQuery--%>
    <script src="js/jquery.min.js"></script>
    <script>
        //页面加载,绑定单击事件
        $(function(){
            $("#btn").click(function (){
                alert("hello button");
            });
        });
    </script>
</head>
<body>
    <a href="user/testString">test字符串</a><br>
    <a href="user/testVoid">testVoid</a><br>
    <a href="user/testModelAndView">testVoid</a><br>
    <a href="user/testForwardOrRedirect">testForwardOrRedirect</a><br>
    <button id="btn">发送ajax请求</button>
</body>
</html>
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation=" http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/mvc
       http://www.springframework.org/schema/mvc/spring-mvc.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd">

    <!--配置前端控制器,告诉哪些静态资源不拦截-->
    <!-- 设置静态资源不过滤 -->
    <mvc:resources location="/css/" mapping="/css/**"/> <!-- 样式 -->
    <mvc:resources location="/images/" mapping="/images/**"/> <!-- 图片 -->
    <mvc:resources location="/js/" mapping="/js/**"/> <!-- javascript -->

    <!--开启SpringMVC框架注解的支持-->
    <mvc:annotation-driven/>
</beans>
2、响应json数据之发送ajax的请求
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
    <%--引入JQuery--%>
    <script src="js/jquery.min.js"></script>
    <script>

        //页面加载,绑定单击事件
        $(function(){
            alert("hehe");
            $("#btn").click(function(){
                alert("hehe");
                $.ajax({
                    //编写json格式,设置属性和值
                    url:"user/testAjax",
                    contentType:"application/json;charset=UTF-8",
                    data:'{"username":"hehe","password":"qaz123","age":30}',//便于嵌套
                    dataType:"json",
                    type:"post",
                    success:function(data){
                        //data是服务器端响应的json数据,进行数据解析
                    }
                });
            });
        });
    </script>
</head>
<body>
    <a href="user/testString">test字符串</a><br>
    <a href="user/testVoid">testVoid</a><br>
    <a href="user/testModelAndView">testVoid</a><br>
    <a href="user/testForwardOrRedirect">testForwardOrRedirect</a><br>
    <button id="btn">发送ajax请求</button>
</body>
</html>
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation=" http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/mvc
       http://www.springframework.org/schema/mvc/spring-mvc.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd">
    <!--配置前端控制器,告诉哪些静态资源不拦截-->
    <!-- 设置静态资源不过滤 -->
    <mvc:resources location="/css/" mapping="/css/**"/> <!-- 样式 -->
    <mvc:resources location="/images/" mapping="/images/**"/> <!-- 图片 -->
    <mvc:resources location="/js/**" mapping="/js/**"/> <!-- javascript -->
    <!--开启SpringMVC框架注解的支持-->
    <mvc:annotation-driven/>
</beans>
3、响应json数据之响应json格式数据
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
    <%--引入JQuery--%>
    <script src="js/jquery.min.js"></script>
    <script>

        //页面加载,绑定单击事件
        $(function(){
            // 绑定点击事件
            $("#btn").click(function(){
                $.ajax({
                    url:"user/testAjax",
                    contentType:"application/json;charset=UTF-8",
                    data:'{"addressName":"aa","addressNum":100}',
                    dataType:"json", type:"post",
                    success:function(data){
                    alert(data);
                    alert(data.username);
                    alert(data.password);
                    alert(data.age)
                }
                });
            });
        });

    </script>
</head>
<body>
    <a href="user/testString">test字符串</a><br>
    <a href="user/testVoid">testVoid</a><br>
    <a href="user/testModelAndView">testVoid</a><br>
    <a href="user/testForwardOrRedirect">testForwardOrRedirect</a><br>
    <button id="btn">发送ajax请求</button>
</body>
</html>
package cn.itcast.controller;

import cn.itcast.domain.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

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

@Controller
@RequestMapping("/user")
public class UserController {
    /**
     * 模拟异步请求响应
     * @param user
     */
    @RequestMapping("/testAjax")
    public @ResponseBody User testAjax(@RequestBody User user){
        System.out.println("testAjax方法执行了");
        //客户端发送ajax请求,传递了json字符串,后端已经把json字符串封装到user对象中
        System.out.println(user);
        //做数据的响应,可以模拟查询数据库
        user.setUsername("ahahhah");
        user.setAge(45);
        //数据响应
        return user;
    }
}
三、文件上传
1、上传原理分析和搭建环境
get会写到地址栏上
2、传统方式上传代码回顾
    @RequestMapping("/fileupload1")
    public String fileupload1(HttpServletRequest request, HttpServletResponse response) throws Exception {
        System.out.println("文件上传……");
        //使用servlet组件完成文件上传
        //指定文件上传的位置
        String path = request.getSession().getServletContext().getRealPath("/uploads/");
        //判断该 路径是否存在
        File file = new File(path);
        if (!file.exists()){
            //创建该文件夹
            file.mkdirs();
        }
        //解析request对象,获取到上传的文件项
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        //解析request
        List<FileItem> items = upload.parseRequest(request);
        //遍历
        for (FileItem item : items) {
            //判断当前item是否是上传文件项
            if (item.isFormField()){
                //说明是普通的表单项
            }else{
                //说明是上传文件项
                //获取到上传文件的名称
                String filename = item.getName();
                //把文件名称设置为唯一值
                String uuid = UUID.randomUUID().toString().replace("-", "");
                filename = uuid+filename;
                //完成文件上传
                item.write(new File(path,filename));
                //删除临时文件
                item.delete();
            }
        }
        return "success";
    }
3、Springmvc方式上传原理分析
文件解析器对象:CommonsMultipartResolver
4、Springmvc方式上传代码
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <br>
    <h3>SpringMVC方式文件上传</h3>
    <form action="user/fileupload2" method="post" enctype="multipart/form-data">
        选择文件:<input type="file" name="upload" /> <br>
        <input type="submit" value="上传" />
    </form>
</body>
</html>

    /**
     * Spring MVC方式上传
     * @param request
     * @param upload
     * @return
     * @throws Exception
     */
    @RequestMapping("/fileupload2")
    public String fileupload2(HttpServletRequest request, MultipartFile upload) throws Exception {
        System.out.println("Spring文件上传……");
        //使用servlet组件完成文件上传
        //指定文件上传的位置
        String path = request.getSession().getServletContext().getRealPath("/uploads/");
        //判断该 路径是否存在
        File file = new File(path);
        if (!file.exists()){
            //创建该文件夹
            file.mkdirs();
        }
        //说明是上传文件项
        //获取到上传文件的名称
        String filename = upload.getOriginalFilename();
        //把文件名称设置为唯一值
        String uuid = UUID.randomUUID().toString().replace("-", "");
        filename = uuid+filename;
        //完成文件上传
        upload.transferTo(new File(path,filename));
        return "success";
    }
4、跨服务器上传分析和搭建环境
创建了两个tomcat:SpringMVC和fileupload
5、跨服务器上传代码
<dependency>
      <groupId>com.sun.jersey</groupId>
      <artifactId>jersey-core</artifactId>
      <version>1.18.1</version>
    </dependency> <dependency>
    <groupId>com.sun.jersey</groupId>
    <artifactId>jersey-client</artifactId>
    <version>1.18.1</version>
  </dependency>
    /**
     * 跨服务器文件上传
     * @param upload
     * @return
     * @throws Exception
     */
    @RequestMapping("/fileupload3")
    public String fileupload3(MultipartFile upload) throws Exception {
        System.out.println("跨服务器文件上传……");
        //定义上传文件服务器的路径
        String path = "http://localhost:9090/uploads/";//写加号就不需要拼了
        //说明是上传文件项
        //获取到上传文件的名称
        String filename = upload.getOriginalFilename();
        //把文件名称设置为唯一值
        String uuid = UUID.randomUUID().toString().replace("-", "");
        filename = uuid+filename;
        //完成文件上传,跨服务器上传
        //创建客户端对象
        Client client = Client.create();
        //和图片服务器进行连接
        WebResource webResource = client.resource(path+filename);
        //上传文件
        webResource.put(upload.getBytes());
        return "success";
    }
四、异常处理--友好页面
1、分析和搭建环境
2、异常处理之演示程序异常
package cn.itcast.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/user")
public class UserController {
    @RequestMapping("/testException")
    public String testException() throws Exception{
        System.out.println("testException执行了……");
        //模拟异常
        int i = 1 / 0;
        return "success";
    }
}
3、异常处理代码编写
步骤:
  • 编写自定义异常类(提示信息)
package cn.itcast.exception;

/**
 * 自定义异常类
 */
public class SysException extends Exception{
    public SysException(String message) {
        this.message = message;
    }

    //存储异常信息
    private String message;
    @Override
    public String getMessage() {
        return message;
    }
    public void setMessage(String message) {
        this.message = message;
    }
}
  • 编写异常处理器
package cn.itcast.exception;

import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 异常处理器对象
 */
public class SysExceptionResolver implements HandlerExceptionResolver {
    /**
     * 处理异常的业务逻辑
     * @param httpServletRequest
     * @param httpServletResponse
     * @param o 处理器对象
     * @param ex 异常对象
     * @return
     */
    @Override
    public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception ex) {
        //获取到异常对象
        SysException e = null;
        //判断ex是SysException类型的
        if(ex instanceof SysException){
            e = (SysException) ex;
        }else{
            e = new SysException("系统正在维护");
        }
        //创建ModelAndView对象
        ModelAndView mv = new ModelAndView();
        mv.addObject("errorMsg",e.getMessage());
        mv.setViewName("error");
        return mv;
    }
}
  • 配置异常处理器(跳转到友好提示页面)
<!--配置异常处理器对象-->
<bean id="sysExceptionResolver" class="cn.itcast.exception.SysExceptionResolver" />

<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
${errorMsg}
</body>
</html>
五、SpringMVC拦截器
1、介绍和搭建环境
拦截器链:多个拦截器
拦截器与过滤器的区别:
  • 过滤器什么都能拦,拦截器只能拦controller
2、编写controller
package cn.itcast.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/user")
public class UserController {
    @RequestMapping("/testInterceptor")
    public String testInterceptor() throws Exception{
        System.out.println("testInterceptor执行了……");
        try {
            //模拟异常
            int i = 1 / 0;
        } catch (Exception e) {
            e.printStackTrace();//在控制台打印异常信息,保留
            //向上抛出自定义异常信息
        }
        return "success";
    }
}
3、拦截器入门代码
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation=" http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/mvc
       http://www.springframework.org/schema/mvc/spring-mvc.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd">
    <!--配置拦截器-->
    <mvc:interceptors>
        <!--配置拦截器-->
        <mvc:interceptor>
            <!--要拦截的具体方法-->
            <mvc:mapping path="/user/*"/>
            <!--不要拦截的方法-->
            <!--<mvc:exclude-mapping path=""/>-->
            <!--配置拦截器对象-->
            <bean class="cn.itcast.interceptor.MyInterceptor1"></bean>
        </mvc:interceptor>
    </mvc:interceptors>
    <!--开启SpringMVC框架注解的支持-->
    <mvc:annotation-driven/>
</beans>
package cn.itcast.interceptor;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
 * 自定义拦截器
 */
public class MyInterceptor1 implements HandlerInterceptor {
    //jdk1.8之后,接口中可以对方法进行实现
    /**
     * 预处理controller方法执行前
     * @param request
     * @param response
     * @param handler
     * @return true放行,执行下一个拦截器;如果没有,执行controller中的方法
     *         false不放行
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("MyInterceptor1执行了");
        return true;
    }
}
4、拦截器接口方法演示





posted @ 2021-02-21 18:45  哥们要飞  阅读(144)  评论(0编辑  收藏  举报