栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

SpringMVC

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

SpringMVC


















































































































SpringMVC


ExController

package com.kkb.controller;

import com.kkb.exceptions.TeamException;
import com.kkb.exceptions.TeamIdException;
import com.kkb.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}/{loc}")
    public ModelAndView test01(@PathVariable("id") Integer teamId,@PathVariable String loc,@PathVariable("name") String teamName) throws TeamException {
        ModelAndView mv = new ModelAndView();
        if(teamId<=1000){
            throw new TeamIdException("teamId不合法!必须在1000之上!");
        }
        if("test".equals(teamName)){
            throw  new TeamNameException("teamName不合法!不能使用test!");
        }
        if("test".equals(loc)){
            throw  new TeamException("team属性异常!");
        }
        mv.setViewName("ok");
        return mv;
    }

    
}

FileController

package com.kkb.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.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

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


@Controller
@RequestMapping("file")
public class FileController {

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


    @RequestMapping("upload")
    public String upload(@RequestParam("myFile") MultipartFile myFile, HttpServletRequest request){
        //获取文件的原始名称 txcat.jsp
        String originalFilename = myFile.getOriginalFilename();
        //实际开发中,一般都要将文件重新命名进行存储
        //存储到服务器的文件名称=随机字符串+根据实际名称获取到源文件的后缀
        String fileName = UUID.randomUUID().toString().replace("-","") + originalFilename.substring(originalFilename.lastIndexOf("."));
        System.out.println(fileName);
        //文件的存储路径
        String realPath = request.getServletContext().getRealPath("/uploadFile")+"/";

        try {
            myFile.transferTo(new File(realPath+fileName));//真正的文件上传到服务器指定的位置
            System.out.println("上传成功! "+realPath+fileName);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "ok";
    }

    @RequestMapping("hello")
    public String helo() {
        return "fileHandler";
    }
}

NavigationController

package com.kkb.controller;

import org.springframework.aop.aspectj.InstantiationModelAwarePointcutAdvisor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;


@Controller
@RequestMapping("navigation")
public class NavigationController {

    //3、转发或者重定向到控制器
    @RequestMapping("test03-1")
    public ModelAndView test031(HttpServletRequest request) {
        System.out.println("test03-1----------转发到控制器");
        ModelAndView mv = new ModelAndView();
        mv.addObject("teamName","lacker");
        mv.setViewName("forward:/navigation/test01-1");
        return mv;
    }

    @RequestMapping("test03-2")
    public ModelAndView test032(HttpServletRequest request) {
        System.out.println("test03-2----------重定向到控制器");
        ModelAndView mv = new ModelAndView();
        mv.addObject("teamName","kaierte");
        mv.addObject("teamId","1003");
        mv.setViewName("redirect:/navigation/test01-1");
        return mv;
    }

    //2、重定向到一个JSP页面
    //使用字符串转发
    @RequestMapping("test02-1")
    public String test021(HttpServletRequest request){
        request.setAttribute("teamName","洛杉矶");
        return "redirect:/jsp/ok.jsp";//参数值直接追加到URL后面
    }

    //使用ModelAndView转发
    @RequestMapping("test02-2")
    public ModelAndView test022(){
        ModelAndView mv = new ModelAndView();
        mv.addObject("teamName","luoshanji");//存储在request作用域中的值以参数的姓氏追加在URL后面 http://localhost:8080/jsp/ok.jsp?teamName=洛杉矶
        mv.addObject("teamId","1001");
        mv.setViewName("redirect:/jsp/ok.jsp");
        return mv;//
    }

    //1、转发到一个JSP页面
    //使用字符串转发
    @RequestMapping("test01-1")
    public String test011(HttpServletRequest request){
        System.out.println("test01-1---------");
        request.setAttribute("teamName","洛杉矶");
        //return "ok";//默认方式:由视图解析器处理之后将逻辑视图转为物理资源路径
        return "forward:/jsp/ok.jsp";//当添加了forward前缀之后,视图解析器中的前后缀就失效了,必须自己编写绝对路径
    }

    //使用ModelAndView转发
    @RequestMapping("test01-2")
    public ModelAndView test012(){
        ModelAndView mv = new ModelAndView();
        mv.addObject("teamName","洛杉矶");
        mv.setViewName("ok");
        //mv.setViewName("forward:/jsp/ok.jsp");
        return mv;//
    }
}

ParamController

package com.kkb.controller;

import com.kkb.pojo.Team;
import com.kkb.vo.QueryVO;
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.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

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

    //9、获取集合型的参数:简单类型可以通过@RequestParam注解实现;对象集合不支持直接获取,必须封装在类中,作为一个属性操作
    @RequestMapping("test09")
    public ModelAndView test09(QueryVO vo){
        System.out.println("test09------------");
        for(Team team : vo.getTeamList()){
            System.out.println(team);
        }
        return new ModelAndView("ok");
    }

    //8、获取集合型的参数:简单类型可以通过@RequestParam注解实现;对象集合不支持直接获取,必须封装在类中,作为一个属性操作
    @RequestMapping("test08")
    public ModelAndView test08(@RequestParam("teamName") List nameList){
        System.out.println("test08------------");
        for(String s : nameList){
            System.out.println(s);
        }
        return new ModelAndView("ok");
    }

    //7、获取数组类型的参数
    @RequestMapping("test07")
    public ModelAndView test04(String[] teamName,HttpServletRequest request){
        System.out.println("test07------------");
        //方式1:
        for(String s : teamName){
            System.out.println(s);
        }
        //方式2:
        String[] teamNames = request.getParameterValues("teamName");
        for(String name : teamNames){
            System.out.println(name);
        }
        return new ModelAndView("ok");
    }

    //6、获取日期类型的参数:实体类中的对应的属性上必须有注解
    @RequestMapping("test06")
    public ModelAndView test06(Team team){
        System.out.println("test06------------");
        System.out.println(team);
        return new ModelAndView("ok");
    }

    //5、直接使用URL地址传参:例如 http://localhost:8080/param/test05/1001/ll/fas
    @RequestMapping("test05/{id}/{name}/{loc}")
    public ModelAndView test05(@PathVariable("id") Integer teamId
            , @PathVariable("name") String teamName
            , @PathVariable("loc") String teamLocation){
        System.out.println("test05------------");
        System.out.println(teamId);
        System.out.println(teamName);
        System.out.println(teamLocation);
        return new ModelAndView("ok");
    }

    //4、使用HttpServletRequest 对象获取参数:跟原来的javaWeb项目中使用的方式是一样的
    @RequestMapping("test04")
    public ModelAndView test04(HttpServletRequest request){
        System.out.println("test04------------");
        String teamId = request.getParameter("teamId");
        String teamName = request.getParameter("teamName");
        String location = request.getParameter("location");
        if(teamId!=null){
            System.out.println(Integer.valueOf(teamId));
            System.out.println(teamName);
            System.out.println(location);
        }
        return new ModelAndView("ok");
    }

    //3、请求参数和方法名称的参数不一致:使用@RequsetParam进行矫正
    //value 属性表示请求中的参数名称
    //require 属性表示参数是否是必须的,true:必须赋值,否则报出400错,false:可以不赋值,结果就是null
    @RequestMapping("test03")
    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("ok");
    }

    //2、使用对象接收多个参数,要求用户请求中携带的参数名称必须是实体类中的属性保持一致,否则获取不到
    @RequestMapping("test02")
    public ModelAndView test02(Team team){
        System.out.println("test02------------");
        System.out.println(team);
        return new ModelAndView("ok");
    }

    
    @RequestMapping("test01")
    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("ok");
    }

    @RequestMapping("hello")
    public ModelAndView hello() {
        return new ModelAndView("hello");
    }
}

RestfulController

package com.kkb.controller;

import com.kkb.pojo.Team;
import com.kkb.vo.AjaxResultVO;
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.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

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


@Controller
public class RestfulController {

    private static List teamList;

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

        }
    }

    
    @RequestMapping(value = "team/{id}",method = RequestMethod.DELETE)
    @ResponseBody
    public AjaxResultVO del(@PathVariable("id")int id){
        System.out.println("更新PUT--发起的请求----");
        for(Team team1 : teamList){
            if(team1.getTeamId() == id){
                teamList.remove(team1);
                return new AjaxResultVO();
            }
        }
        return new AjaxResultVO(500,"要删除的ID不存在!");
    }

    
    @RequestMapping(value = "team/{id}",method = RequestMethod.PUT)
    @ResponseBody
    public AjaxResultVO 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不存在!");
    }

    
    @RequestMapping(value = "team",method = RequestMethod.POST)
    @ResponseBody
    public AjaxResultVO add(Team team){
        System.out.println("更新POST--发起的请求----");
        teamList.add(team);
        return new AjaxResultVO(200,"OK");
    }

    /*
    @RequestMapping(value = "teams",method = RequestMethod.GET)
    @ResponseBody
    public List getAll(){
        System.out.println("查询所有GET--发起的请求----");
        return teamList;
    }*/

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

    /*
    @RequestMapping(value = "team/{id}",method = RequestMethod.GET)
    @ResponseBody
    public Team getOne(@PathVariable("id")int id){
        System.out.println("查询单个GET--发起的请求----");
        for(Team team : teamList){
            if(team.getTeamId() == id){
                return team;
            }
        }
        return null;
    }*/

    
    @RequestMapping(value = "team/{id}",method = RequestMethod.GET)
    @ResponseBody
    public AjaxResultVO  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;
    }

    @RequestMapping("hello")
    public String hello(){
        return "restful";
    }
}

ResultController

package com.kkb.controller;

import com.kkb.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.*;

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

    //4、没有返回 为void :其实就是原生的Servlet的使用方式
    //转发 重定向
    @RequestMapping("test04-1")
    public void test041(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("直接使用HttpServletRequest进行服务器端的转发");
        request.getRequestDispatcher("/jsp/ok.jsp").forward(request,response);
    }
    @RequestMapping("test04-2")
    public void test042(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("直接使用HttpServletResponse重定向转发");
        response.sendRedirect("/jsp/ok.jsp");
    }

    @RequestMapping("test04-3")
    public void test043(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter writer = response.getWriter();
        writer.write("返回void类型测试---直接返回字符串");
        writer.flush();
        writer.close();
    }

    @RequestMapping("test04-4")
    public void test044(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setStatus(302);//设置响应码,302表示重定向
        response.setHeader("Location","/jsp/ok.jsp");
    }

    //3、返回对象类型:Integer Double String 自定义类型 List Map 返回的不是逻辑视图的名称,而直接就是数据返回
    //一般是ajax请求搭配使用,将json格式的数据直接返回,一定要与@ResponseBody
    @ResponseBody
    @RequestMapping("test03-1")
    public Integer test031(HttpServletRequest request) {
        return 666;
    }

    @ResponseBody
    @RequestMapping("test03-2")
    public String test032(HttpServletRequest request) {
        return "test";
    }

    @ResponseBody
    @RequestMapping("test03-3")
    public Team test033() {
        Team team = new Team();
        team.setTeamName("热火");
        team.setTeamId(1002);
        team.setLocation("迈阿密");
        team.setCreateTime(new Date());
        return team;
    }

    @ResponseBody
    @RequestMapping("test03-4")
    public List test034() {
        List list = new ArrayList<>(5);
        for(int i=1;i<=5;i++){
            Team team = new Team();
            team.setTeamName("热火");
            team.setTeamId(1002+i);
            team.setLocation("迈阿密"+i);
            list.add(team);
        }
        return list;
    }

    @ResponseBody
    @RequestMapping("test03-5")
    public Map test035() {
        Map map = new HashMap<>();
        for(int i=1;i<=5;i++){
            Team team = new Team();
            team.setTeamName("热火");
            team.setTeamId(1002+i);
            team.setLocation("迈阿密"+i);
            team.setCreateTime(new Date());
            map.put(team.getTeamId()+"",team);
        }
        return map;
    }

    //2、返回字符串
    @RequestMapping("test02")
    public String test02(HttpServletRequest request) {
        Team team = new Team();
        team.setTeamName("热火");
        team.setTeamId(1002);
        team.setLocation("迈阿密");
        //携带数据
        request.setAttribute("team",team);
        request.getSession().setAttribute("team",team);
        //资源的跳转
        return "result";//经过视图解析器InternalResourceViewResolver的处理,
        // 将逻辑视图名称加上前后缀变为物理资源路径 /jsp/result.jsp
    }

    //返回值是ModelAndView:这种方式既有数据的携带还有资源的跳转,可以选择该种方式
    @RequestMapping("test01")
    public ModelAndView test01() {
        ModelAndView mv = new ModelAndView();//模型与视图
        //携带数据
        mv.addObject("teamName","潮人队");//相当于requst.setAttribute("teamName","潮人队");
        mv.setViewName("result");//经过视图解析器InternalResourceViewResolver的处理,
                                // 将逻辑视图名称加上前后缀变为物理资源路径 /jsp/result.jsp
        return mv;
    }
}

TeamController

package com.kkb.controller;

import com.kkb.service.TeamService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping("team")
public class TeamController {

    @Autowired
    private TeamService teamService;

    @RequestMapping(value = "add.do",method = RequestMethod.GET)
    public ModelAndView addTeam() {
        System.out.println("TeamController---addTeam---");
        ModelAndView mv = new ModelAndView();
        mv.setViewName("team/add");//   /jsp/team/add.jsp

        return mv;
    }

    @RequestMapping(value = "update.do",method = RequestMethod.POST)
    public ModelAndView updateTeam() {
        System.out.println("TeamController---updateTeam---");
        ModelAndView mv = new ModelAndView();
        mv.setViewName("team/update");

        return mv;
    }

    @RequestMapping("/hello.do")
    public ModelAndView add() {
        System.out.println("TeamController---add---");
        teamService.add();
        ModelAndView mv = new ModelAndView();
        mv.addObject("teamName","湖人");//相当于request.setAttribute("teamName","湖人");
        mv.setViewName("index");//未来经过springmvc的视图解析器处理,转换成物理资源路径,相当于request.getRequestDispatcher("index.jsp").forward(req,resp);
        //经过InternalResourceViewResolver对象的处理之后加上前后缀就变为了 /jsp/index.jsp
        return mv;
    }
}

GlobalExceptionHandler

package com.kkb.exceptions;

import org.springframework.stereotype.Controller;
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 exHandler1(Exception ex) {
        ModelAndView mv = new ModelAndView();
        mv.addObject("msg",ex.getMessage());
        
        return mv;
    }

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

    @ExceptionHandler(value = {Exception.class})
    public ModelAndView exHandler3(Exception ex) {
        ModelAndView mv = new ModelAndView();
        mv.addObject("msg",ex.getMessage());

        mv.setViewName("error");
        return mv;
    }

}

TeamException

package com.kkb.exceptions;

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

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

TeamIdException

package com.kkb.exceptions;

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

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

TeamNameException

package com.kkb.exceptions;

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

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

FileInterceptor

package com.kkb.interceptor;

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

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.ws.handler.Handler;
import java.util.Iterator;
import java.util.Locale;
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 fileMap = multipartRequest.getFileMap();
            //遍历文件
            Iterator 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("/jsp/fileTypeError.jsp").forward(request,response);
                    flag = false;
                }
            }
        }

        return flag;
    }
}

MyInterceptor

package com.kkb.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 {

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

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

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

MyInterceptor2

package com.kkb.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 MyInterceptor2 implements HandlerInterceptor {

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

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

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

Team

package com.kkb.pojo;

import com.fasterxml.jackson.annotation.JsonFormat;
import org.springframework.format.annotation.DateTimeFormat;

import java.util.Date;

public class Team {
    private Integer teamId;
    private String teamName;
    private String location;
    @DateTimeFormat(pattern = "yyyy-MM-dd")
    @JsonFormat(pattern = "yyyy-MM-dd")
    private Date createTime;


    public Team() {
    }

    @Override
    public String toString() {
        return "Team{" +
                "teamId=" + teamId +
                ", teamName='" + teamName + ''' +
                ", location='" + location + ''' +
                ", createTime=" + createTime +
                '}';
    }

    public Date getCreateTime() {
        return createTime;
    }

    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }

    public Integer getTeamId() {
        return teamId;
    }

    public void setTeamId(Integer teamId) {
        this.teamId = teamId;
    }

    public String getTeamName() {
        return teamName;
    }

    public void setTeamName(String teamName) {
        this.teamName = teamName;
    }

    public String getLocation() {
        return location;
    }

    public void setLocation(String location) {
        this.location = location;
    }
}

TeamService

package com.kkb.service;

import org.springframework.stereotype.Service;

@Service
public class TeamService {

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

AjaxResultVO

package com.kkb.vo;

import java.util.List;


public class AjaxResultVO {

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

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

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

    public AjaxResultVO(Integer code, List list) {
        this.code = code;
        this.list = list;
    }

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

    public AjaxResultVO(Integer code, String msg, List 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 getList() {
        return list;
    }

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

    public T getObj() {
        return obj;
    }

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

QueryVO

package com.kkb.vo;

import com.kkb.pojo.Team;

import java.util.List;

public class QueryVO {

    private List teamList;

    public List getTeamList() {
        return teamList;
    }

    public void setTeamList(List teamList) {
        this.teamList = teamList;
    }
}

applicationContext.xml



    

    

springmvc.xml




    

    
    

    
    
    
    
        
        
    

    
    
    
    ";
                        }
                        $("#showResult").html(str);
                    }else
                        $("#showResult").html(vo.msg);
                }
                
            });
        });

        //给 查询单个GET 按钮绑定单击事件
        $("#btnGetOne").click(function (){
            //发起异步请求
            $.ajax({
                type:"GET",
                url:"/team/"+$("#teamId").val(),//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+"
"); } }else $("#showResult").html(vo.msg); } }); }); });

result.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>


    result
    



result-----------

test01-----${teamName}-----

test02-----request作用域获取${requestScope.team.teamName}----${requestScope.team.teamId}---${requestScope.team.location}

test03-----session作用域获取${sessionScope.team.teamName}----${sessionScope.team.teamId}---${sessionScope.team.location}

ajax请求自定义对象的结果展示

ajax请求List的结果展示

ajax请求Map的结果展示

web.xml




    
    
        contextConfigLocation
        classpath:applicationContext.xml
    
    
        org.springframework.web.context.ContextLoaderListener
    

    
    
        dispatcherServlet
        org.springframework.web.servlet.DispatcherServlet
        
            contextConfigLocation 
            classpath:springmvc.xml
        
        1
    
    
        dispatcherServlet
        /
    

    
        httpMethodFilter
        org.springframework.web.filter.HiddenHttpMethodFilter
    
    
        httpMethodFilter
        /*
    

    
    
        characterEncodingFilter
        org.springframework.web.filter.CharacterEncodingFilter
        
            encoding
            UTF-8
        
        
            forceRequestEncoding
            true
        
        
            forceResponseEncoding
            true
        
    
    
        characterEncodingFilter
        /*
    

pom.xml



    4.0.0

    com.kkb
    springmvc01
    1.0-SNAPSHOT


    war

    
        
            org.springframework
            spring-webmvc
            5.2.13.RELEASE
        
        
            javax.servlet
            javax.servlet-api
            4.0.1
            provided
        
        
            com.fasterxml.jackson.core
            jackson-core
            2.9.0
        
        
            com.fasterxml.jackson.core
            jackson-databind
            2.9.0
        
        
        
            commons-fileupload
            commons-fileupload
            1.3.1
        
    

    
        
            
                org.apache.maven.plugins
                maven-compiler-plugin
                3.8.0
                
                    1.8
                    1.8
                
            
            
                org.apache.tomcat.maven
                tomcat7-maven-plugin
                2.2
                
                    /
                    8080
                
            
        
    


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/288639.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号