SpringMvc框架

1.什么是MVC

MVC全名是Model View Controller,是模型(model)-视图(view)-控制器(controller)的缩写,一种软件设计典范,用一种业务逻辑、数据、界面显示分离的方法组织代码,将业务逻辑聚集到一个部件里面,在改进和个性化定制界面及用户交互的同时,不需要重新编写业务逻辑。MVC被独特的发展起来用于映射传统的输入、处理和输出功能在一个逻辑的图形化用户界面的结构中。
  MVC 是一种使用 MVC(Model View Controller 模型-视图-控制器)设计创建 Web 应用程序的模式:
  Model(模型)表示应用程序核心(比如数据库记录列表)。
  View(视图)显示数据(数据库记录)。
  Controller(控制器)处理输入(写入数据库记录)。
  MVC 模式同时提供了对 HTML、CSS 和 JavaScript 的完全控制。
  Model(模型)是应用程序中用于处理应用程序数据逻辑的部分。
  通常模型对象负责在数据库中存取数据。
  View(视图)是应用程序中处理数据显示的部分。
  通常视图是依据模型数据创建的。
  Controller(控制器)是应用程序中处理用户交互的部分。
  通常控制器负责从视图读取数据,控制用户输入,并向模型发送数据。
  MVC 分层有助于管理复杂的应用程序,因为您可以在一个时间内专门关注一个方面。例如,您可以在不依赖业务逻辑的情况下专注于视图设计。同时也让应用程序的测试更加容易。
  MVC 分层同时也简化了分组开发。不同的开发人员可同时开发视图、控制器逻辑和业务逻辑。

2.什么是SpringMvc框架

springMVC它是spring框架的一个分支,该springMVC框架主要完成的功能是:==接收浏览器的请求响应,对数据进行处理,然后返回页面进行显示== 可以把它理解为和Servlet干的工作是一样的。

3.如何使用SpringMvc

1.1.引入依赖 spring-webmvc
2.注册DispatcherServlet到web.xml文件。需要指定加载的springmvc配置文件的路径
tomcat启动时会加载servlet
3.创建springmvc的配置文件。 
4.创建一个类,在类上加上@Controller  并且在方法上加上@RequestMapping注解

(1)创建一个maven-web工程。 注意: 用现在的web.xml文件替换原来的web.xml文件

<?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">
</web-app>

(2)引入springmvc的依赖

  <dependencies>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>5.2.15.RELEASE</version>
    </dependency>
  </dependencies>

 (3) 注册DispatcherServlet到web.xml文件上

<?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">

    <!--默认DispactherServlet加载的springmvc配置文件:WEB-INF/[servlet-name]-servlet.xml
        能不能你指定加载的配置文件呢:可以。
    -->
    <servlet>
        <servlet-name>DispactherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <!--classpath:表示编译后的路径-->
            <param-value>classpath:springmvc.xml</param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>DispactherServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

(4) 创建我们的springmvc配置文件

<?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: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">
    <!--包扫描-->
    <context:component-scan base-package="com.ykq.controller"/>

</beans>

(5)创建一个controller类

@RestController//该注解标记该类为处理层类---类似@WebServlet
public class StudentController {

    @RequestMapping("save")//把请求路径映射到该方法上。
    public String login(Student  stu){
        System.out.println(stu);
        return "hello.jsp";//响应一个页面
    }
}

4.SpringMvc的运行流程

 1. 客户端发生请求http://localhost:8080/springmvc01
 *     2. 来到tomcat服务器。
 *     3. springmvc的前端控制器DipatcherServlet接受所有的请求。
 *     4. 查看你的请求地址和哪个@RequestMaping匹配。
 *     5. 执行对应的方法。方法会返回一个字符串。springmvc把该字符串解析为要转发的网页。
 *     6. 把该字符串经过视图解析器拼接。
 *     7. 拿到拼接的地址,找到对应的网页。
 *     8. 渲染该网页给客户

 5.如何在controller接受请求的参数

request.getParamter("name")这种接受参数的问题,麻烦。类型都是String.需要手动转型。

 5.1接收少量参数

 5.2 接收大量参数

表单提交。

封装一个实体类来接受这些参数:

发现接受的参数值乱码:只能添加过滤器

(1)自己创建编码过滤器. jdk1.8一定要重写init和destory方法 1.9以后可以不写

@WebFilter(filterName = "MyFilter",urlPatterns = "/*")
public class MyFilter implements Filter {
    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        chain.doFilter(req, resp);
    }

    public void init(FilterConfig config) throws ServletException {

    }

}

(2)springmvc提供了一个编码过滤

 <filter>
        <filter-name>encodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>encodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

 5.3 接受的参数含有日期类型

解决办法:

在时间类型的属性上添加一个注解:@DateTimeFormat(pattern = "yyyy-MM-dd")

 //yyyy年  MM:月 dd日  24小时制  
    @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private Date birthday;//出生日期

在springmvc配置文件上开启注解驱动

 <!--开启注解驱动-->
    <mvc:annotation-driven/>

5.4 处理静态资源

什么是静态资源: 比如: css, js, img,html

无法加载图片: 原因:springmvc的前端控制器DispatcherSerlvet也把静态资源拦截器。放行静态资源

 <!--放行静态资源:哪些资源为静态资源。css img js html-->
    <mvc:default-servlet-handler/>

6. 如何把controller数据返回到网页并回显。

以前我们学到servlet时,如何把数据保存并可以在网页上获取该数据。

request: 作用范围: 同一个请求内有效。setAttribute(key,value)

session:作用范围: 同一个会话有效,只要会话不关闭会一直有效。setAttribute(key,value)

网页如何获取保存的数据呢:可以使用EL表达式。${scope.key}

6.1 转发跳转

@Controller
@SessionAttributes(value = {"user","user2"}) //设置哪些model的key在session范围
public class StudentController {
    @RequestMapping("/list")
    public String list(HttpServletRequest request){
        //查询到一个学生信息。
        Student student=new Student("张三",1,"北京",new Date());
        //可以保存到request中,同一个请求
        request.setAttribute("s",student);
        return "list.jsp"; //转发
    }
    @RequestMapping("/list2")
    public String list2(Model model){ //如果你使用request,你和tomcat容器绑定了。 建议使用Model.
        //查询到一个学生信息。
        Student student=new Student("王五",1,"上海",new Date());
        //可以保存到model中,同一个请求 和request是一样。
        model.addAttribute("s2",student);
        return "list.jsp"; //转发
    }
    //上面讲解都是保存request范围。如何保存到session范围。
    @RequestMapping("/list3")
    public String list3(HttpSession session){
        Student student=new Student("溜溜",0,"天津",new Date());
        session.setAttribute("user",student);
        return "list.jsp"; //转发
    }
//model 保存到session
    @RequestMapping("/list4")
    public String  list4( Model model){
        Student student=new Student("张海",1,"北京",new Date());
        Student student2=new Student("张浩",1,"上海",new Date());
        model.addAttribute("user",student);
        model.addAttribute("user2",student2); //默认在request范围
        return "list.jsp"; //转发
    }

}

6.1 如何使用重定向跳转

在方法的返回字符串的内容时加上redirect:

 @RequestMapping("list5")
    public String list5(){
        System.out.println("!!!!!!!!!!!!!!!!!");
        return "redirect:list.jsp"; //当springmvc看到你返回的字符串钟含有redirect:时 它认为你要进行重定向跳转
    }

7. springmvc返回json数据

(1)什么时候需要返回json数据。

         异步请求时,ajax请求时。

(2)之前在servlet时如何返回json数据呢?  

借助了Fastjson---手动把java对象转换为json格式的数据,并使用out.print(json)输出json数据。 关闭out对象。

springmvc如何返回json数据呢!

(1)内置了一个jar. jackson的jar包

<!--jackson依赖 可以把java对象转换为json对象-->
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.13.2.2</version>
    </dependency>

  (2) 在controller返回的数据类型变成javabean对象。

@Controller
public class StudentController01 {
    @RequestMapping("json01")
    @ResponseBody
    public List<Student> json01(){
        List<Student> list=new ArrayList<Student>();
        list.add(new Student ("张三",0,"aa",new Date()));
        list.add(new Student ("李四",0,"aa",new Date()));
        list.add(new Student ("王五",0,"aa",new Date()));
        list.add(new Student ("溜溜",0,"aa",new Date()));
        return list;
    }

}

 发现: 上面返回的时间类型的json数据显示的为毫秒,正常情况应该显示时间格式。如何解决。

 @JsonFormat(pattern = "yyyy-MM-dd",timezone ="GMT-8" )//转发·json格式的时间

8. springmvc的全局异常处理类

(1)如何使用全局异常处理类

[1] 创建一个异常类: @ControllerAdvice注解

@ControllerAdvice //表示该为类controller的异常处理类
public class MyExceptinHandle {


     @ExceptionHandler(value = RuntimeException.class) //当发生RuntimeException就会触发该方法
     public String error(){
         return "error.jsp";
     }

    @ExceptionHandler(value = Exception.class) //当发生Exception就会触发该方法
    public String error2(){
        return "error2.jsp";
    }
}

[2] 保证springmvc能够扫描到该类。

 <context:component-scan base-package="com.aaa"/>

如果是ajax请求返回的应该是一个json数据。

 9. springmvc拦截器

过滤器: 过滤掉某些资源,

拦截器只会拦截controller层的资源路径。

如何使用拦截器:

(1)创建一个类,并实现HandlerInterceptor

public class MyInterceptor implements HandlerInterceptor {

    //拦截器的处理方法。
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("经过了该拦截器");

        return true;//true:表示拦截器放行 false:不放行
    }
}

(2) 把该类注册到springmvc配置文件上。

<!--拦截器的配置-->
    <mvc:interceptors>
        <mvc:interceptor>
            <!--mapping:哪些路径需要经过拦截器
               /**: 表示n层路径
               /*:表示一层路径
                -->
            <mvc:mapping path="/**"/>
            <!--exclude-mapping:设置不经过该拦截的路径-->
            <mvc:exclude-mapping path="/list2"/>
            <mvc:exclude-mapping path="/list3"/>
            <!--bean表示你自定义的拦截器类路径-->
            <bean class="com.aaa.interceptor.MyInterceptor"/>
        </mvc:interceptor>
    </mvc:interceptors>

10.文件上传

 10.1文件上传到本地服务器

(1)导入文件上传的依赖。

<!--文件上传的依赖-->
    <dependency>
      <groupId>commons-fileupload</groupId>
      <artifactId>commons-fileupload</artifactId>
      <version>1.4</version>
    </dependency>

 (2) 创建一个页面

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
   <%--
      method: 提交方式 文件上传必须为post提交。
      enctype:默认application/x-www-form-urlencoded 表示提交表单数据
              multipart/form-data:可以包含文件数据

      input的类型必须为file类型,而且必须有name属性
   --%>
   <form method="post" action="upload01" enctype="multipart/form-data">
       <input type="file" name="myfile"/>
   </form>
</body>
</html>

(3)在springmvc中配置文件上传解析器

  <!--
     id的名称必须叫multipartResolver
     -->
     <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
          <!--这里的单位为字节10M*1024K*1024-->
          <property name="maxUploadSize" value="10485760"/>
     </bean>

(4)创建upload接口方法

 //注意:MultipartFile 参数名必须和<input type="file" name="myfile"/>中name属性相同
    @RequestMapping("/upload")
    public String upload01(MultipartFile myfile, HttpServletRequest request) throws Exception{

        //(1)得到本地服务目录的地址
        String path = request.getSession().getServletContext().getRealPath("upload");
        //(2)判断该目录是否存在
        File file=new File(path);
        if(!file.exists()){
             file.mkdirs();
        }
        //(3)//把myfile保存到本地服务中某个文件夹下。 缺点:文件的名称
        String filename= UUID.randomUUID().toString().replace("-","")+myfile.getOriginalFilename();
        File target=new File(path+"/"+filename);
        myfile.transferTo(target); //把myfile转移到目标目录下
        return "";
    }

 10.2 elementui+vue+axios完成文件上传

(1)页面的布局

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
    <!--引入element得css样式-->
    <link type="text/css" rel="stylesheet" href="css/index.css"/>
    <!--引入vue得js文件 这个必须在element之前引入-->
    <script type="text/javascript" src="js/vue.js"></script>
    <script type="text/javascript" src="js/qs.min.js"></script>
    <script type="text/javascript" src="js/axios.min.js"></script>
    <!--element得js文件-->
    <script type="text/javascript" src="js/index.js"></script>
</head>
<body>
    <div id="app">
        <%--action:文件上传的路径--%>
        <el-upload
                class="avatar-uploader"
                action="/upload02"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload">
            <img v-if="imageUrl" :src="imageUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
    </div>
</body>
<script>
     var app=new Vue({
           el:"#app",
           data:{
               imageUrl:"",
           },
           methods:{
               //上传成功后触发的方法
               handleAvatarSuccess(res, file) {
                   this.imageUrl=res.data;
               },
               //上传前触发的方法
               beforeAvatarUpload(file) {
                   const isJPG = file.type === 'image/jpeg';
                   const isPNG = file.type === 'image/png';
                   const isLt2M = file.size / 1024 / 1024 < 2;
                   if (!isJPG) {
                       this.$message.error('上传头像图片只能是 JPG 格式!');
                   }
                   if (!isLt2M) {
                       this.$message.error('上传头像图片大小不能超过 2MB!');
                   }
                   return isJPG && isLt2M;
               }
           }
     })
</script>

<style>
    .avatar-uploader .el-upload {
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
    }
    .avatar-uploader .el-upload:hover {
        border-color: #409EFF;
    }
    .avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 178px;
        height: 178px;
        line-height: 178px;
        text-align: center;
    }
    .avatar {
        width: 178px;
        height: 178px;
        display: block;
    }
</style>
</html>

 (2)后台的接口

@RequestMapping("/upload02")
    @ResponseBody
    public Map upload02(MultipartFile file, HttpServletRequest request) {
        try {
            //1.获取上传到服务器的文件夹路径
            String path = request.getSession().getServletContext().getRealPath("upload");
            File file1 = new File(path);
            //判断指定的目录是否存在
            if (!file1.exists()) {
                file1.mkdirs();
            }
            //设置上传后的文件名称
            String filename = UUID.randomUUID().toString().replace("-", "") + file.getOriginalFilename();
            File target = new File(path+"/"+filename);
            file.transferTo(target);
            Map map=new HashMap();
            map.put("code",2000);
            map.put("msg","上传成功");
            //通过访问服务器地址来访问图片.
            map.put("data","http://localhost:8080/upload/"+filename);
            return map;
        }catch (Exception e){
            e.printStackTrace();
        }
        Map map=new HashMap();
        map.put("code",5000);
        map.put("msg","上传失败");
        return map;
    }

10.3 上传到oss阿里云的服务器

上传到本地服务器的缺点: 如果搭建集群,导致文件无法在集群中共享。 它的解决方法就是把文件专门上传到一个文件服务器上,这些tomcat服务器都操作同一个文件服务器。

10.3.1普通的文件上传到OSS文件服务器

(1)引入阿里云的OSS依赖

<dependency>
    <groupId>com.aliyun.oss</groupId>
    <artifactId>aliyun-sdk-oss</artifactId>
    <version>3.10.2</version>
</dependency>

(2)上传代码

@RequestMapping("/upload03")
    public String upload03(MultipartFile myfile,HttpServletRequest request){
        // Endpoint以华东1(杭州)为例,其它Region请按实际情况填写。
        String endpoint = "oss-cn-hangzhou.aliyuncs.com";

        // 阿里云账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维,请登录RAM控制台创建RAM用户。
       String accessKeyId = "yourAccessKeyId";
        String accessKeySecret = "yourAccessKeySecret";
        // 填写Bucket名称,例如examplebucket。
         // 填写Bucket名称,例如examplebucket。
        String bucketName = "examplebucket";
        //你上传到oss后的名字 会根据日期帮你创建文件夹。
        Calendar calendar=Calendar.getInstance();
        String objectName =calendar.get(Calendar.YEAR)+"/"+(calendar.get(Calendar.MONTH)+1)+"/"+
                calendar.get(Calendar.DATE)+"/"+UUID.randomUUID().toString().replace("-","")+
                myfile.getOriginalFilename();

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        try {
            InputStream inputStream =myfile.getInputStream();
            // 创建PutObject请求。
            ossClient.putObject(bucketName, objectName, inputStream);
        } catch (Exception oe) {

        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        //回显图片地址 用el表达式
        String url="https://"+bucketName+"."+endpoint+"/"+objectName;
        request.setAttribute("imgUrl",url);
        return "success.jsp";
    }     

10.3.2 elementui 异步上传OSS服务器

(1)前端代码

<%--
  Created by IntelliJ IDEA.
  User: 16623
  Date: 2022-06-12
  Time: 16:12
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
    <!--引入element得css样式-->
    <link type="text/css" rel="stylesheet" href="css/index.css"/>
    <!--引入vue得js文件 这个必须在element之前引入-->
    <script type="text/javascript" src="js/vue.js"></script>
    <script type="text/javascript" src="js/qs.min.js"></script>
    <script type="text/javascript" src="js/axios.min.js"></script>
    <!--element得js文件-->
    <script type="text/javascript" src="js/index.js"></script>
</head>
<body>
<div id="app">
    <el-upload
            class="avatar-uploader"
            action="upload03"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload">
        <img v-if="imageUrl" :src="imageUrl" class="avatar">
        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
    </el-upload>
</div>
</body>
<script>
    var app=new Vue({
        el:"#app",
        data:{
            imageUrl:"",
        },
        methods:{
            handleAvatarSuccess(res, file) {
                this.imageUrl=res.data;
                console.log(res);
            },
            beforeAvatarUpload(file) {
                const isJPG = file.type === 'image/jpeg';
                const isPNG = file.type === 'image/png';
                const isLt2M = file.size / 1024 / 1024 < 2;
                if (!isJPG) {
                    this.$message.error('上传头像图片只能是 JPG 格式!');
                }
                if (!isLt2M) {
                    this.$message.error('上传头像图片大小不能超过 2MB!');
                }
                return isJPG && isLt2M;
            }
        }
    })
</script>

<style>
    .avatar-uploader .el-upload {
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
    }
    .avatar-uploader .el-upload:hover {
        border-color: #409EFF;
    }
    .avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 178px;
        height: 178px;
        line-height: 178px;
        text-align: center;
    }
    .avatar {
        width: 178px;
        height: 178px;
        display: block;
    }
</style>
</html>

(2)后端代码

将上传的代码写在一个工具类中,后续调用即可

package com.aaa.untils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.Calendar;
import java.util.UUID;

/**
 * @ClassName: OssUtils
 * @Description: TODO
 * @Author: DD
 * @Date: 2022-06-12 16:13
 * @Version: v1.0
 */
public class OssUtils {
    public static String upload(MultipartFile myfile){
        String endpoint = "oss-cn-hangzhou.aliyuncs.com";
        String accessKeyId = "";
        String accessKeySecret = "";
        String bucketName = "";
        String objectName =fileName(myfile);
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        try {
            InputStream inputStream =myfile.getInputStream();
            ossClient.putObject(bucketName, objectName, inputStream);
        } catch (Exception oe) {

        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        String url="https://"+bucketName+"."+endpoint+"/"+objectName;
        return url;
    }

    //获取上传到oss后的名字
    private static String fileName(MultipartFile myfile){
        Calendar calendar=Calendar.getInstance();
        String name=calendar.get(Calendar.YEAR)+"/"+(calendar.get(Calendar.MONTH)+1)+"/"+
                calendar.get(Calendar.DATE)+"/"+ UUID.randomUUID().toString().replace("-","")+
                myfile.getOriginalFilename();

        return name;
    }
}

(3) controller接口

   @RequestMapping("upload03")
    @ResponseBody
    public CommonResult upload03(MultipartFile file) {
        try {
            String url = OssUtils.upload(file);
            return new CommonResult(5000,"上传成功",url);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new CommonResult(2000,"上传失败",null);
    }

10.3.3 存用户信息--头像

注意:要保证实体类中的属性名和前端传递的数据的v-model中的属性名一致
关键代码,为表单对象添加头像地址的属性

   //为表单对象添加头像地址的属性
                this.userForm.avatarUrl=this.imageUrl;

 (前端代码)

<%--
  Created by IntelliJ IDEA.
  User: 16623
  Date: 2022-06-12
  Time: 17:10
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
    <!--引入element得css样式-->
    <link type="text/css" rel="stylesheet" href="css/index.css"/>
    <!--引入vue得js文件 这个必须在element之前引入-->
    <script type="text/javascript" src="js/vue.js"></script>
    <script type="text/javascript" src="js/qs.min.js"></script>
    <script type="text/javascript" src="js/axios.min.js"></script>
    <!--element得js文件-->
    <script type="text/javascript" src="js/index.js"></script>
</head>
<body>
<div id="app">
    <el-form  label-width="80px" :model="userForm">
        <el-form-item label="头像:">
            <el-upload
                    class="avatar-uploader"
                    action="/uploadAvatar"
                    :show-file-list="false"
                    :on-success="handleAvatarSuccess"
                    :before-upload="beforeAvatarUpload">
                <img v-if="imageUrl" :src="imageUrl" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
        </el-form-item>
        <el-form-item label="账号:">
            <el-input v-model="userForm.name"></el-input>
        </el-form-item>
        <el-form-item label="密码:">
            <el-input v-model="userForm.pwd"></el-input>
        </el-form-item>
        <el-form-item label="地址:">
            <el-input v-model="userForm.address"></el-input>
        </el-form-item>
        <el-form-item>
            <el-button type="primary" @click="onSubmit">提交</el-button>
        </el-form-item>
    </el-form>
</div>
</body>
<script>
    var app=new Vue({
        el:"#app",
        data:{
            userForm:{},
            imageUrl:""
        },
        methods:{
            handleAvatarSuccess(result,file){
                this.imageUrl=result.data;
                //为表单对象添加头像地址的属性
                this.userForm.avatarUrl=this.imageUrl;
            },
            //提交
            onSubmit(){
                axios.post("addUser",this.userForm).then(function(result){

                });
            },
            //上传前触发的方法
            beforeAvatarUpload(file) {
                const isJPG = file.type === 'image/jpeg';
                const isPNG = file.type === 'image/png';
                const isLt2M = file.size / 1024 / 1024 < 2;
                if (!isJPG) {
                    this.$message.error('上传头像图片只能是 JPG 格式!');
                }
                if (!isLt2M) {
                    this.$message.error('上传头像图片大小不能超过 2MB!');
                }
                return isJPG && isLt2M;
            }
        }
    })
</script>
<style>
    .avatar-uploader .el-upload {
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
    }
    .avatar-uploader .el-upload:hover {
        border-color: #409EFF;
    }
    .avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 178px;
        height: 178px;
        line-height: 178px;
        text-align: center;
    }
    .avatar {
        width: 178px;
        height: 178px;
        display: block;
    }
</style>
</html>

(后端代码)

/**
 * @ClassName: UserController
 * @Description: TODO
 * @Author: DD
 * @Date: 2022-06-12 17:12
 * @Version: v1.0
 */
@Controller
public class UserController {

    @RequestMapping("uploadAvatar")
    @ResponseBody
    public CommonResult uploadAvatar(MultipartFile file) {
        try {
            String avatar = OssUtils.upload(file);
            return new CommonResult(2000, "上传成功", avatar);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new CommonResult(5000, "失败", null);
    }

    //@RequestBody:把请求体中json数据转换为java对象
    @RequestMapping("addUser")
    @ResponseBody
    public CommonResult addUser(@RequestBody User user){
        System.out.println(user);
        //TODO 调用dao完成保存到数据库--省略
        return new CommonResult(2000,"成功",null);
    }
}

 (实体层代码)

/**
 * @ClassName: User
 * @Description: TODO
 * @Author: DD
 * @Date: 2022-06-12 17:13
 * @Version: v1.0
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
    private String name;
    private int pwd;
    private String address;
    private Object avatarUrl;
}

11. springmvc中的注解

@RestController----类上等价于 @COntroller+@ResponseBody
    该注解下所有的方法都是返回json数据
    
@RequestMapping: 作用: 把请求路径映射到响应的方法上。 

@RequestParam(value = "u"):设置你接受的请求参数名。查询参数

@RequestMapping(value = "/addUser",method = RequestMethod.POST)
       method:表示该接口接受的请求方式.不设置可以接受任意请求方式。
       
@GetMapping("addUser"):表示只接受get提交方式的请求     

@RequestBody:把请求的json数据转换为java对象。从前端到后端
@ResponseBody:把java转换为json数据   从后端转前端

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值