SpringMVC入门案例

pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.syh</groupId>
    <artifactId>SpringMVC01</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>
    <dependencies>
        <!--单元测试-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>4.0.1</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.2.13.RELEASE</version>
        </dependency>
        <!--ResultController中,返回对象类型需要添加的依赖-->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.9.0</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.9.0</version>
        </dependency>
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3.1</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <!--编译插件-->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.0</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.tomcat.maven</groupId>
                <artifactId>tomcat7-maven-plugin</artifactId>
                <version>2.2</version>
                <configuration>
                    <path>/</path>
                    <port>8080</port>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>


applicationContext.xml 除pom.xml外的配置文件均在resources文件夹下创建
<?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
       http://www.springframework.org/schema/context/spring-context.xsd">

    <!--spring的配置文件:除了控制器之外的bean对象都在这里扫描-->
    <context:component-scan base-package="com.syh.dao,com.syh.service"/>
</beans>


package com.syh.service;

import org.springframework.stereotype.Service;

@Service
public class TeamService {

    public void add(){
        System.out.println("TeamService---add");
    }
}


springmvc.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:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="
       http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/mvc
       http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <!--springmvc的配置文件:控制器的bean对象都在这里扫描-->
    <context:component-scan base-package="com.syh.controller"/>
    <context:component-scan base-package="com.syh.exceptions"/>

    <mvc:annotation-driven/>
    <!--视图解析器-->
    <bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

    <mvc:resources mapping="/js/**" location="/js/"></mvc:resources>
    <mvc:resources mapping="/uploadFile/**" location="/uploadFile/"></mvc:resources>

    <!--配置拦截器-->
    <mvc:interceptors>
        <!--按顺序配置多个拦截器-->
        <mvc:interceptor>
            <mvc:mapping path="/**"/>
            <bean class="com.syh.interceptor.MyInterceptor" id="myInterceptor"></bean>
        </mvc:interceptor>
        <mvc:interceptor>
            <mvc:mapping path="/**"/>
            <bean class="com.syh.interceptor.FileInterceptor" id="fileInterceptor"></bean>
        </mvc:interceptor>
    </mvc:interceptors>

    <!--文件上传-->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!--文件上传的大小限制,以字节B为单位,5m:1024*1024*5-->
        <property name="maxUploadSize" value="5242880"></property>
        <property name="defaultEncoding" value="UTF-8"></property>
    </bean>
</beans>


<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>hello.jsp</title>
</head>
<body>

<h3>8.获取集合类型的参数</h3>
<form action="/param/test08.do" method="post">
    球队1名称:<input type="text" name="teamName"/><br>
    球队2名称:<input type="text" name="teamName"/><br>
    球队3名称:<input type="text" name="teamName"/><br>
    <button type="submit">提交</button>
</form>

<h3>7.获取数组类型的参数</h3>
<form action="/param/test07.do" method="post">
    球队1名称:<input type="text" name="teamName"/><br>
    球队2名称:<input type="text" name="teamName"/><br>
    球队3名称:<input type="text" name="teamName"/><br>
    <button type="submit">提交</button>
</form>

<h3>6.获取日期类型的参数</h3>
<form action="/param/test06.do" method="post">
    球队号码:<input type="text" name="teamId"/><br>
    球队名称:<input type="text" name="teamName"/><br>
    球队位置:<input type="text" name="location"/><br>
    创建日期:<input type="text" name="createTime"/><br>
    <button type="submit">提交</button>
</form>

<h3>5.直接使用URL地址传参</h3>

<h3>4.使用HttpServletRequest 对象获取参数</h3>
<form action="/param/test04.do" method="post">
    球队号码:<input type="text" name="teamId"/><br>
    球队名称:<input type="text" name="teamName"/><br>
    球队位置:<input type="text" name="location"/><br>
    <button type="submit">提交</button>
</form>

<h3>3.请求参数和方法名称的参数不一致</h3>
<form action="/param/test03.do" method="post">
    球队号码:<input type="text" name="teamId"/><br>
    球队名称:<input type="text" name="teamName"/><br>
    球队位置:<input type="text" name="location"/><br>
    <button type="submit">提交</button>
</form>

<h3>2.使用对象接收多个参数</h3>
<form action="/param/test02.do" method="post">
    球队号码:<input type="text" name="teamId"/><br>
    球队名称:<input type="text" name="teamName"/><br>
    球队位置:<input type="text" name="location"/><br>
    <button type="submit">提交</button>
</form>

<h3>1.直接使用方法的参数逐个接收</h3>
<form action="/param/test01.do" method="post">
    球队号码:<input type="text" name="teamId"/><br>
    球队名称:<input type="text" name="teamName"/><br>
    球队位置:<input type="text" name="location"/><br>
    <button type="submit">提交</button>
</form>
</body>
</html>


<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>ok.jsp</title>
</head>
<body>
    <h1>-----ok-----</h1>
</body>
</html>


package com.syh.controller;

import com.syh.pojo.Team;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Controller
@RequestMapping("param")
public class ParamController {

    @RequestMapping("test08.do")
    public ModelAndView test08(@RequestParam("teamName") List<String> nameList) {
        System.out.println("test08-----");
        for (String s : nameList) {
            System.out.println(s);
        }
        return new ModelAndView("param/ok");
    }

    @RequestMapping("test07.do")
    //方式一
    public ModelAndView test07(String[] teamName) {
        System.out.println("test07-----");
        for (String s : teamName) {
            System.out.println(s);
        }
        return new ModelAndView("param/ok");
    }
    //方式二
    /*public ModelAndView test07(HttpServletRequest request){
        System.out.println("test07-----");
        String[] teamNames = request.getParameterValues("teamName");
        for (String s : teamNames) {
            System.out.println(s);
        }
        return new ModelAndView("param/ok");
    }*/

    @RequestMapping("test06.do")
    public ModelAndView test06(Team team) {
        System.out.println("test06-----");
        System.out.println(team);
        return new ModelAndView("param/ok");
    }

    @RequestMapping("test05/{id}/{name}/{loc}.do")
    public ModelAndView test05(@PathVariable("id") Integer teamId,
                               @PathVariable("name") String teamName,
                               @PathVariable("loc") String location) {
        System.out.println("test05-----");
        System.out.println(teamId);
        System.out.println(teamName);
        System.out.println(location);
        return new ModelAndView("param/ok");
    }

    @RequestMapping("test04.do")
    public ModelAndView test04(HttpServletRequest request) {
        System.out.println("test04-----");
        String teamId = request.getParameter("teamId");
        if (teamId != null)
            System.out.println(Integer.valueOf(teamId));
        String teamName = request.getParameter("teamName");
        if (teamName != null)
            System.out.println(teamName);
        String location = request.getParameter("location");
        if (location != null)
            System.out.println(location);
        return new ModelAndView("param/ok");
    }

    @RequestMapping("test03.do")
    public ModelAndView test03(@RequestParam(value = "teamId", required = false) Integer id,
                               @RequestParam(value = "teamName", required = true) String name,
                               @RequestParam("location") String loc) {
        System.out.println("test03-----");
        System.out.println(id);
        System.out.println(name);
        System.out.println(loc);
        return new ModelAndView("param/ok");
    }

    @RequestMapping("test02.do")
    public ModelAndView test02(Team team) {
        System.out.println("test02-----");
        System.out.println(team);
        return new ModelAndView("param/ok");
    }

    @RequestMapping("test01.do")
    public ModelAndView test01(Integer teamId, String teamName, String location) {
        System.out.println("test01-----");
        System.out.println(teamId);
        System.out.println(teamName);
        System.out.println(location);
        return new ModelAndView("param/ok");//未来经过springmvc的视图解析器处理,转换成物理路径
        // 经过internalResourceViewResolver对象处理后,加上前后缀变成 /param/ok.jsp
    }

}


<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>result.jsp</title>
    <script src="/js/jquery-1.11.1.js"></script>
</head>
<body>
<h3>result01-------</h3>
<h3>result02---request作用域获取---${requestScope.team.teamName}---${requestScope.team.teamId}---${requestScope.team.location}</h3>
<h3>result02---session作用域获取---${sessionScope.team.teamName}---${sessionScope.team.teamId}---${sessionScope.team.location}</h3>

<button type="button" id="btn1">ajax请求自定义对象</button>
<div>
    <h3>ajax请求自定义对象的结果展示:</h3>
    <p id="res1"></p>
</div>
<button type="button" id="btn2">ajax请求list</button>
<div>
    <h3>ajax请求list的结果展示:</h3>
    <p id="res2"></p>
</div>
<button type="button" id="btn3">ajax请求map</button>
<div>
    <h3>ajax请求map的结果展示:</h3>
    <p id="res3"></p>
</div>
<script>
    $(function (){
        $("#btn1").click(function (){
            $.ajax({
                type: "POST",
                url: "/result/test04.do",
                data: "",
                success: function(msg){
                    alert( "Data Saved: " + msg );
                    var id = msg.teamId;
                    var name = msg.teamName;
                    var loc = msg.location;
                    $("#res1").html("id:"+id+"name:"+name+"location:"+loc);
                }
            });
        });

        $("#btn2").click(function (){
            $.ajax({
                type: "POST",
                url: "/result/test05.do",
                data: "",
                success: function(list){
                    alert( "Data Saved: " + list );
                    var str = "";
                    for (var i=0;i<list.length;i++) {
                        var obj = list[i];
                        str += "id:"+obj.teamId+",name:"+obj.teamName+",loc:"+obj.location+"<br/>";
                    }
                    $("#res2").html(str);
                }
            });
        });

        $("#btn3").click(function (){
            $.ajax({
                type: "POST",
                url: "/result/test06.do",
                data: "",
                success: function(map){
                    alert( "Data Saved: " + map );
                    var str = "";
                    $.each(map,function (i,obj){
                        str += "id:"+obj.teamId+",name:"+obj.teamName+",loc:"+obj.location+"<br/>";
                    });
                    $("#res3").html(str);
                }
            });
        });
    });
</script>
</body>
</html>


package com.syh.controller;

import com.syh.pojo.Team;
import org.springframework.stereotype.Controller;
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;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("result")
public class ResultController {

    @RequestMapping("test08.do")
    public void test08(HttpServletResponse response) throws IOException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter writer = response.getWriter();
        writer.write("返回void类型测试-----");
        writer.flush();
        writer.close();
        //response.setStatus(302); //设置响应码,302表示重定向
        //response.setHeader("Location","/param/ok.jsp");
    }

    //4.没有返回值void
    @RequestMapping("test07.do")
    public void test07(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("直接使用转发或重定向的方式跳转页面");
        request.getRequestDispatcher("/param/ok.jsp").forward(request, response);
        //response.sendRedirect("/param/ok.jsp");
    }

    @ResponseBody
    @RequestMapping("test06.do")
    public Map<String, Team> test06() {
        Map<String, Team> map = new HashMap();
        for (int i = 0; i < 4; i++) {
            Team team = new Team();
            team.setTeamId(106 + i);
            team.setTeamName("小牛" + i);
            team.setLocation("达拉斯" + i);
            //team.setCreaTime(new date());
            map.put(team.getTeamId() + "", team);
        }
        return map;
    }

    @ResponseBody
    @RequestMapping("test05.do")
    public List<Team> test05() {
        List<Team> list = new ArrayList(4);
        for (int i = 0; i < 4; i++) {
            Team team = new Team();
            team.setTeamId(105 + i);
            team.setTeamName("湖人" + i);
            team.setLocation("洛杉矶" + i);
            list.add(team);
        }
        return list;
    }

    @ResponseBody
    @RequestMapping("test04.do")
    public Team test04() {
        Team team = new Team();
        team.setTeamId(104);
        team.setTeamName("热火");
        team.setLocation("迈阿密");
        return team;
    }

    //3.返回对象的类型:Integer Double String 自定义类型 List Map
    //返回的不是逻辑视图的名称,而是数据,一般是ajax请求搭配使用,将json格式的数据直接返回给响应体
    //对象类型都必须要添加@ResponseBody
    @ResponseBody
    @RequestMapping("test03.do")
    public String test03() {
        return "test03";
    }

    //2.返回值是字符串
    @RequestMapping("test02.do")
    public String test02(HttpServletRequest request) {
        Team team = new Team();
        team.setTeamId(102);
        team.setTeamName("勇士");
        team.setLocation("金州");
        request.setAttribute("team", team);
        request.getSession().setAttribute("team", team);
        return "param/result"; //经过视图解析器处理,加上前后缀转换为物理路径
    }

    //1.返回值是ModelAndView,需要携带数据和资源跳转可以选择这种方式
    @RequestMapping("test01.do")
    public ModelAndView test01() {
        ModelAndView mv = new ModelAndView();
        mv.addObject("teamName", "费城");
        mv.setViewName("param/result");
        return mv;
    }
}


自定义异常类
package com.syh.exceptions;

public class TeamException extends Exception {
    public TeamException() {
    }

    public TeamException(String message) {
        super(message);
    }
}


package com.syh.exceptions;

public class TeamIdException extends TeamException {
    public TeamIdException() {
    }

    public TeamIdException(String message) {
        super(message);
    }
}


package com.syh.exceptions;

public class TeamNameException extends TeamException {
    public TeamNameException() {
    }

    public TeamNameException(String message) {
        super(message);
    }
}


package com.syh.controller;

import com.syh.exceptions.TeamIdException;
import com.syh.exceptions.TeamNameException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping("ex")
public class ExController {

    @RequestMapping("test01/{id}/{name}.do")
    public ModelAndView test01(@PathVariable("id") Integer teamId,
                               @PathVariable("name") String teamName) throws TeamIdException, TeamNameException {
        ModelAndView mv = new ModelAndView();
        if (teamId <= 100)
            throw new TeamIdException("teamId不合法!必须在100以上");
        else if ("test".equals(teamName))
            throw new TeamNameException("teamName不合法!不能为test");
        //System.out.println(10/0); //除0异常,默认跳转至error.jsp
        mv.setViewName("param/ok");
        return mv;
    }

    /*@ExceptionHandler(value = {TeamIdException.class,TeamNameException.class,Exception.class})
    public ModelAndView exHandler(Exception ex){
        ModelAndView mv=new ModelAndView();
        mv.addObject("msg",ex.getMessage());
        if(ex instanceof TeamIdException)
            mv.setViewName("param/idError");
        else if(ex instanceof TeamNameException)
            mv.setViewName("param/nameError");
        else
            mv.setViewName("param/error");
        return mv;
    }*/

}


全局异常处理类
package com.syh.exceptions;

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;

//控制器增强,需要进行包扫描
@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(value = TeamIdException.class)
    public ModelAndView idExHandler(Exception ex) {
        ModelAndView mv = new ModelAndView();
        mv.addObject("msg", ex.getMessage());
        mv.setViewName("param/idError");
        return mv;
    }

    @ExceptionHandler(value = TeamNameException.class)
    public ModelAndView NameExHandler(Exception ex) {
        ModelAndView mv = new ModelAndView();
        mv.addObject("msg", ex.getMessage());
        mv.setViewName("param/nameError");
        return mv;
    }

    @ExceptionHandler(value = Exception.class)
    public ModelAndView exHandler(Exception ex) {
        ModelAndView mv = new ModelAndView();
        mv.addObject("msg", ex.getMessage());
        mv.setViewName("param/error");
        return mv;
    }
}


<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>error.jsp</title>
</head>
<body>
    <h3>默认错误页面-----${msg}</h3>
</body>
</html>


<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>idError.jsp</title>
</head>
<body>
    <h3>idError-----${msg}</h3>
</body>
</html>


<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>nameError.jsp</title>
</head>
<body>
    <h3>nameError-----${msg}</h3>
</body>
</html>


package com.syh.interceptor;

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

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

//自定义拦截器
public class MyInterceptor implements HandlerInterceptor {

    //执行时间:控制器方法执行之前,在ModelAndVies返回之前
    //使用场景:登录验证
    //返回值:true表示放行/false表示拦截
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("preHandler-----");
        return true;
    }

    //执行时间:控制器方法执行之后,在ModelAndVies返回之前,有机会修改返回值
    //使用场景:日志记录...
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("postHandler-----");
    }

    //执行时间:控制器方法执行之后,在ModelAndVies返回之后,没有机会修改返回值
    //使用场景:全局资源的一些操作
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("afterCompletion-----");
    }
}


package com.syh.interceptor;

import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Iterator;
import java.util.Map;

//文件后缀拦截器
public class FileInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        boolean flag = true;
        //判定是不是文件上传的请求
        if (request instanceof MultipartHttpServletRequest) {
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
            //遍历文件
            Iterator<String> iterator = fileMap.keySet().iterator();
            while (iterator.hasNext()) {
                String key = iterator.next();
                MultipartFile file = multipartRequest.getFile(key);
                String originalFilename = file.getOriginalFilename();
                String hz = originalFilename.substring(originalFilename.lastIndexOf("."));
                //判定后缀是否合法
                if (!hz.toLowerCase().equals("png") && !hz.toLowerCase().equals("jpg")) {
                    request.getRequestDispatcher("/param/fileTypeError.jsp").forward(request, response);
                    flag = false;
                }
            }
        }
        return flag;
    }

}


package com.syh.controller;

import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.UUID;

//文件上传
@Controller
@RequestMapping("file")
public class FileController {

    @RequestMapping("download.do")
    public ResponseEntity<byte[]> download(HttpServletRequest request) throws IOException {
        //指定文件的路径
        String realPath = request.getServletContext().getRealPath("/uploadFile") + "/7e48d137255c4689a155c0b915faf62a.jpg";
        //创建响应的头信息的对象
        HttpHeaders headers = new HttpHeaders();
        //标记以流的方式作出响应
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        //以附件的形式响应给用户
        headers.setContentDispositionFormData("attachment", URLEncoder.encode("7e48d137255c4689a155c0b915faf62a.jpg", "UTF-8"));
        File file = new File(realPath);
        ResponseEntity<byte[]> resp = new ResponseEntity<>(FileUtils.readFileToByteArray(file), headers, HttpStatus.CREATED);
        return resp;
    }

    @RequestMapping("upload.do")
    public String upload(MultipartFile myFile, HttpServletRequest request) throws IOException {
        //获取文件的原始名称 cat.jpg
        String originalFilename = myFile.getOriginalFilename();
        //实际开发中,一般都要将文件重新存储
        //存储到服务器的名称=随机的字符串+根据实际名称获取到源文件的后缀
        String fileName = UUID.randomUUID().toString().replace("-", "") + originalFilename.substring(originalFilename.lastIndexOf("."));
        System.out.println(fileName);
        //文件存储路径
        String realPath = request.getServletContext().getRealPath("/uploadFile") + "/";
        myFile.transferTo(new File(realPath + fileName));//真正的文件上传到指定的服务器位置
        System.out.println("上传成功:" + realPath + fileName);
        return "param/ok";
    }

    @RequestMapping("hello.do")
    public String Hello() {
        return "param/fileHandler";
    }
}


<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>文件上传</title>
</head>
<body>
    <form action="/file/upload.do" method="post" enctype="multipart/form-data">
        请选择文件:<input type="file" name="myFile" /><br/>
        <button type="submit">上传文件</button>
    </form>
    <form action="/file/download.do" method="post" enctype="multipart/form-data">
        <button type="submit">下载图片</button>
    </form>
</body>
</html>


<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>fileTypeError</title>
</head>
<body>
    <h3>文件上传的类型有误!后缀必须是.png或者.jpg</h3>
</body>
</html>


<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>restful.jsp</title>
    <script src="/js/jquery-1.11.1.js"></script>
</head>
<body>
<form id="myForm" action="" method="post">
    球队号码:<input type="text" name="teamId" id="teamId"/><br>
    球队名称:<input type="text" name="teamName"/><br>
    球队位置:<input type="text" name="location"/><br>
    <button type="button" id="btnGetAll">查询所有GET</button>
    <button type="button" id="btnGetOne">查询单个GET</button>
    <button type="button" id="btnPost">添加POST</button>
    <button type="button" id="btnPUT">更新PUT</button>
    <button type="button" id="btnDel">删除DELETE</button>
</form>
<p id="showResult"></p>
</body>
</html>
<script>
    //页面加载完毕后,给按钮绑定事件
    $(function () {

        //给 删除DELETE 按钮绑定单击事件
        $("#btnDel").click(function () {
            $.ajax({
                type: "POST",//如果data不需要传参,可直接使用DELETE类型(不推荐)
                url: "/team/" + $("#teamId").val() + ".do",//RESTFUL风格的API定义
                data: "&_method=DELETE",//表单的所有数据以?&的形式追击在URL后面
                dataType: "json",
                success: function (vo) {
                    if (vo.code == 200) {
                        $("#showResult").html("删除成功")
                    } else {
                        $("#showResult").html(vo.msg);
                    }
                }
            });
        });

        //给 更新PUT 按钮绑定单击事件
        $("#btnPUT").click(function () {
            $.ajax({
                type: "POST",
                url: "/team/" + $("#teamId").val() + ".do",//RESTFUL风格的API定义
                data: $("#myForm").serialize() + "&_method=PUT",//表单的所有数据以?&的形式追加在URL后面
                dataType: "json",
                success: function (vo) {
                    if (vo.code == 200) {
                        $("#showResult").html("更新成功")
                    } else {
                        $("#showResult").html(vo.msg);
                    }
                }
             });
        });

        //给 添加POST 按钮绑定单击事件
        $("#btnPost").click(function () {
            $.ajax({
                type: "POST",
                url: "/team.do",//RESTFUL风格的API定义
                data: $("#myForm").serialize(),//表单的所有数据以?&的形式追加在URL后面
                dataType: "json",
                success: function (vo) {
                    if (vo.code == 200) {
                        $("#showResult").html("添加成功")
                    } else {
                        $("#showResult").html(vo.msg);
                    }
                }
             });
        });

        //给 查询所有GET 按钮绑定单击事件
        $("#btnGetAll").click(function () {
            $.ajax({
                type: "GET",
                url: "/teams.do",//RESTFUL风格的API定义
                data: "",
                dataType: "json",
                success: function (vo) {
                    if (vo.code == 200) {
                        var list = vo.list;
                        var str = "";
                        for (var i = 0; i < list.length; i++) {
                            var obj = list[i];
                            str += obj.teamId + "---" + obj.teamName + "---" + obj.location + "<br/>";
                        }
                        $("#showResult").html(str);
                    } else {
                        $("#showResult").html(vo.msg);
                    }
                }
            });
        });

        //给 查询单个GET 按钮绑定单击事件
        $("#btnGetOne").click(function () {
            $.ajax({
                type: "GET",
                url: "/team/" + $("#teamId").val() + ".do",//RESTFUL风格的API定义
                data: "",
                dataType: "json",
                success: function (vo) {
                    if (vo.code == 200) {
                        var obj = vo.obj;
                        if (obj == "") {
                            $("#showResult").html("没有符合条件的数据");
                        } else {
                            $("#showResult").html(obj.teamId + "---" + obj.teamName + "---" + obj.location + "<br/>");
                        }
                    }else {
                        $("#showResult").html(vo.msg);
                    }
                }
            });
        });

    });
</script>


package com.syh.vo;

import java.util.List;

//自己封装返回结果的类型
public class AjaxResultVO<T> {

    private Integer code;//返回的状态码
    private String msg;//返回的信息,一般是错误的信息或者是异常的信息
    private List<T> list;//返回的数据有可能是集合
    private T obj;//返回的数据有可能是对象

    public AjaxResultVO() {
        code = 200;
        msg = "OK";
        list = null;
        obj = null;
    }

    public AjaxResultVO(Integer code, String msg) {
        this.code = code;
        this.msg = msg;
    }

    public AjaxResultVO(Integer code, String msg, List<T> list) {
        this.code = code;
        this.msg = msg;
        this.list = list;
    }

    public AjaxResultVO(Integer code, String msg, T obj) {
        this.code = code;
        this.msg = msg;
        this.obj = obj;
    }

    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 List<T> getList() {
        return list;
    }

    public void setList(List<T> list) {
        this.list = list;
    }

    public T getObj() {
        return obj;
    }

    public void setObj(T obj) {
        this.obj = obj;
    }
}


package com.syh.controller;

import com.syh.pojo.Team;
import com.syh.vo.AjaxResultVO;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@Controller
public class RestfulController {

    private static List<Team> teamList;

    static {
        teamList = new ArrayList<>(3);
        for (int i = 1; i <= 3; i++) {
            Team team = new Team();
            team.setTeamId(100 + i);
            team.setTeamName("湖人" + i);
            team.setLocation("洛杉矶" + i);
            teamList.add(team);
        }
    }

    /**
     * 根据id,删除球队
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "team/{id}.do", method = RequestMethod.DELETE)
    @ResponseBody
    public AjaxResultVO<Team> del(@PathVariable("id") int id) {
        System.out.println("删除DELETE---发起的请求");
        for (Team team2 : teamList) {
            if (team2.getTeamId() == id) {
                teamList.remove(team2);
                return new AjaxResultVO<>(204, "OK");
            }
        }
        return new AjaxResultVO<>(500, "要删除的ID不存在~~~");
    }

    /**
     * 根据id,更新球队信息
     *
     * @param id
     * @param team
     * @return
     */
    @RequestMapping(value = "team/{id}.do", method = RequestMethod.PUT)
    @ResponseBody
    public AjaxResultVO<Team> update(@PathVariable("id") int id, Team team) {
        System.out.println("更新PUT---发起的请求");
        for (Team team1 : teamList) {
            if (team1.getTeamId() == id) {
                team1.setLocation(team.getLocation());
                team1.setTeamName(team.getTeamName());
                return new AjaxResultVO<>();
            }
        }
        return new AjaxResultVO<>(500, "要更新的ID不存在~~~");
    }

    /**
     * 添加一个球队
     *
     * @param team
     * @return
     */
    @RequestMapping(value = "team.do", method = RequestMethod.POST)
    @ResponseBody
    public AjaxResultVO<Team> add(Team team) {
        System.out.println("添加POST---发起的请求");
        teamList.add(team);
        return new AjaxResultVO<>(201, "OK");
    }

    /**
     * 根据id,查询球队
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "team/{id}.do", method = RequestMethod.GET)
    @ResponseBody
    public AjaxResultVO<Team> getOne(@PathVariable("id") int id) {
        System.out.println("查询单个GET---发起的请求");
        for (Team team : teamList) {
            if (team.getTeamId() == id) {
                return new AjaxResultVO<>(200, "OK", team);
            }
        }
        return null;
    }

    /**
     * 查询所有的球队
     *
     * @return
     */
    @RequestMapping(value = "teams.do", method = RequestMethod.GET)
    @ResponseBody
    public AjaxResultVO<Team> getAll() {
        System.out.println("查询所有GET---发起的请求");
        return new AjaxResultVO<>(200, "OK", teamList);
    }

    @RequestMapping("restHello.do")
    public String hello() {
        return "param/restful";
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值