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;
}
/*@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("idError");
}else if(ex instanceof TeamNameException){
mv.setViewName("nameError");
}else {
mv.setViewName("error");
}
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<byte[]> 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<byte[]> 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;
/**
* SpringMVC 导航的方式
*/
@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<String> 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;
/**
* restful风格的控制器
*/
@Controller
public class RestfulController {
private static List<Team> 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);
}
}
/**
* 根据id 删除一个的球队
* @return
*/
@RequestMapping(value = "team/{id}",method = RequestMethod.DELETE)
@ResponseBody
public AjaxResultVO<Team> del(@PathVariable("id")int id){
System.out.println("更新PUT--发起的请求----");
for(Team team1 : teamList){
if(team1.getTeamId() == id){
teamList.remove(team1);
return new AjaxResultVO<Team>();
}
}
return new AjaxResultVO<Team>(500,"要删除的ID不存在!");
}
/**
* 根据id 更新一个的球队
* @return
*/
@RequestMapping(value = "team/{id}",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<Team>();
}
}
return new AjaxResultVO<Team>(500,"要更新的ID不存在!");
}
/**
* 添加一个的球队
* @return
*/
@RequestMapping(value = "team",method = RequestMethod.POST)
@ResponseBody
public AjaxResultVO<Team> add(Team team){
System.out.println("更新POST--发起的请求----");
teamList.add(team);
return new AjaxResultVO<Team>(200,"OK");
}
/**
* 查询所有的球队
* @return
*//*
@RequestMapping(value = "teams",method = RequestMethod.GET)
@ResponseBody
public List<Team> getAll(){
System.out.println("查询所有GET--发起的请求----");
return teamList;
}*/
/**
* 查询所有的球队
* @return
*/
@RequestMapping(value = "teams",method = RequestMethod.GET)
@ResponseBody
public AjaxResultVO<Team> getAll(){
System.out.println("查询所有GET--发起的请求----");
return new AjaxResultVO<Team>(200,"OK",teamList);
}
/**
* 根据id 查询单个的球队
* @return
*//*
@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;
}*/
/**
* 根据id 查询单个的球队
* @return
*/
@RequestMapping(value = "team/{id}",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<Team>(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<Team> test034() {
List<Team> 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<String,Team> test035() {
Map<String,Team> 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());
/*if(ex instanceof TeamIdException){
mv.setViewName("idError");
}else if(ex instanceof TeamNameException){
mv.setViewName("nameError");
}else {
mv.setViewName("error");
}*/
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<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("/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<T> {
private Integer code;//返回的状态码
private String msg;//返回的信息(一般错误的信息或者异常的信息)
private List<T> 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<T> 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<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;
}
}
QueryVO
package com.kkb.vo;
import com.kkb.pojo.Team;
import java.util.List;
public class QueryVO {
private List<Team> teamList;
public List<Team> getTeamList() {
return teamList;
}
public void setTeamList(List<Team> teamList) {
this.teamList = teamList;
}
}
applicationContext.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"
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.kkb.service,com.kkb.dao"/>
</beans>
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
">
<!--spring的配置文件:控制器的bean对象都在这里扫描-->
<context:component-scan base-package="com.kkb.controller"/>
<context:component-scan base-package="com.kkb.exceptions"/>
<!--<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping" />
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<property name="messageConverters">
<list>
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/html; charset=UTF-8</value>
<value>application/json;charset=UTF-8</value>
</list>
</property>
</bean>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/html; charset=UTF-8</value>
<value>application/json;charset=UTF-8</value>
</list>
</property>
</bean>
</list>
</property>
</bean>-->
<mvc:annotation-driven/>
<!--视图解析器-->
<bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/jsp/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<!--放过静态资源,比如图片这种-->
<!--<mvc:default-servlet-handler/>-->
<!--映射路径下的资源,不使用Dispatcher-->
<mvc:resources mapping="/images/**" location="/images/"/>
<mvc:resources mapping="/js/**" location="/js/"/>
<mvc:resources mapping="/css/**" location="/css/"/>
<!--配置拦截器-->
<mvc:interceptors>
<!--按顺序配置多个拦截器-->
<mvc:interceptor>
<mvc:mapping path="/**"/>
<bean class="com.kkb.interceptor.MyInterceptor" id="myInterceptor"></bean>
</mvc:interceptor>
<mvc:interceptor>
<mvc:mapping path="/**"/>
<bean class="com.kkb.interceptor.MyInterceptor2" id="myInterceptor2"></bean>
</mvc:interceptor>
<mvc:interceptor>
<mvc:mapping path="/**"/>
<bean class="com.kkb.interceptor.FileInterceptor" id="fileInterceptor"></bean>
</mvc:interceptor>
</mvc:interceptors>
<!--文件上传-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!--文件上传的大小限制 以字节B为单位 5m:1024*1024*5 1M=1024KB 1KB=1024B-->
<property name="maxUploadSize" value="5242880"/>
<property name="defaultEncoding" value="utf-8"/>
</bean>
</beans>
add.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>ADD</title>
</head>
<body>
<h1>addTeam-----------</h1>
</body>
</html>
update.xml
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>update</title>
</head>
<body>
<h1>updateTeam-----------</h1>
</body>
</html>
error.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1>默认的错误页面 error---${msg}</h1>
</body>
</html>
fileHandler.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>文件操作</title>
</head>
<body>
<form action="/file/upload" method="post" enctype="multipart/form-data">
请选择文件:<input type="file" name="myFile" /><br/>
<button type="submit">上传文件</button>
</form>
<form action="/file/download" method="post" enctype="multipart/form-data">
<button type="submit">下载图片--ea6dda0cdbdb414382a1531f40449394.jpg</button>
</form>
</body>
</html>
fileTypeError.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>fileError</title>
</head>
<body>
<h1>文件上传的类型有误!后缀必须是 = png或者是.jpg</h1>
</body>
</html>
hello.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h3>9、获取集合型的参数</h3>
<form action="/param/test09" method="post">
球队id:<input type="text" name="teamList[0].teamId"/><br>
球队id:<input type="text" name="teamList[1].teamId"/><br>
球队id:<input type="text" name="teamList[2].teamId"/><br>
球队名称1:<input type="text" name="teamList[0].teamName"/><br>
球队名称2:<input type="text" name="teamList[1].teamName"/><br>
球队名称3:<input type="text" name="teamList[2].teamName"/><br>
<button type="submit">提交</button>
</form>
idError.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>id error</title>
</head>
<body>
<h1>teamId Error---${msg}</h1>
</body>
</html>
index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<img src="/images/txcat.jpg" title="服不服?!"/><br>
<form action="/team/update.do" method="post">
<button type="submit">post提交到/team/update.do</button>
</form>
<form action="/team/add.do" method="post">
<button type="submit">post提交到/team/add.do</button>
</form>
<h1>index------${teamName}</h1>
</body>
</html>
nameError.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>name error</title>
</head>
<body>
<h1>teamName Error---${msg}</h1>
</body>
</html>
ok.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1>ok--------${requestScope.teamName}</h1>
<h2>从地址栏中获取的参数值:teamName=${param.teamName},teamId=${param.teamId}</h2>
</body>
</html>
restful.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>restful</title>
<script src="/js/jquery-1.11.1.js"></script>
</head>
<body>
<form id="myForm" action="" method="post">
球队ID:<input name="teamId" id="teamId" /><br/>
球队名称:<input name="teamName" /><br/>
球队位置:<input 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:"DELETE",
url:"/team/"+$("#teamId").val(),//RESTful风格的API定义
data:"_method=DELETE",//字符串连接时需要加&,表单的所有数据以?&形式追加在URL后面 /team?teamId=1006&teamName=kuaicha&location=las
dataType:"json",
success: function (vo){
if(vo.code==200){
$("#showResult").html("删除成功!");
}else
$("#showResult").html(vo.msg);
}
/*success: function (obj){
alert("Data Saved: " + obj);
if(obj==""){
$("#showResult").html("没有符合条件的数据!");
}else
$("#showResult").html(obj.teamId+"---"+obj.teamName+"---"+obj.location);
}*/
});
});
//给 添加PUT 按钮绑定单击事件
$("#btnPost").click(function (){
//发起异步请求
$.ajax({
type:"POST",
url:"/team",//RESTful风格的API定义
data:$("#myForm").serialize()+"&_method=POST",//表单的所有数据以?&形式追加在URL后面 /team?teamId=1006&teamName=kuaicha&location=las
dataType:"json",
success: function (vo){
if(vo.code==200){
$("#showResult").html("添加成功!");
}else
$("#showResult").html(vo.msg);
}
/*success: function (obj){
alert("Data Saved: " + obj);
if(obj==""){
$("#showResult").html("没有符合条件的数据!");
}else
$("#showResult").html(obj.teamId+"---"+obj.teamName+"---"+obj.location);
}*/
});
});
//给 更新PUT 按钮绑定单击事件
$("#btnPut").click(function (){
//发起异步请求
$.ajax({
type:"POST"/*"PUT"*/,
url:"/team/"+$("#teamId").val(),//RESTful风格的API定义
data:$("#myForm").serialize()+"&_method=PUT",//表单的所有数据以?&形式追加在URL后面 /team?teamId=1006&teamName=kuaicha&location=las
dataType:"json",
success: function (vo){
if(vo.code==200){
$("#showResult").html("更新成功!");
}else
$("#showResult").html(vo.msg);
}
/*success: function (obj){
alert("Data Saved: " + obj);
if(obj==""){
$("#showResult").html("没有符合条件的数据!");
}else
$("#showResult").html(obj.teamId+"---"+obj.teamName+"---"+obj.location);
}*/
});
});
//给 查询所有GET 按钮绑定单击事件
$("#btnGetAll").click(function (){
//发起异步请求
$.ajax({
type:"GET",
url:"/teams",//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);
}
/*success: function (list){
alert("Data Saved: " + 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);
}*/
});
});
//给 查询单个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+"<br/>");
}
}else
$("#showResult").html(vo.msg);
}
/*success: function (obj){
alert("Data Saved: " + obj);
if(obj==""){
$("#showResult").html("没有符合条件的数据!");
}else
$("#showResult").html(obj.teamId+"---"+obj.teamName+"---"+obj.location);
}*/
});
});
});
</script>
result.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>result</title>
<script src="/js/jquery-1.11.1.js"></script>
</head>
</head>
<body>
<h1>result-----------</h1>
<h3>test01-----${teamName}-----</h3>
<h3>test02-----request作用域获取${requestScope.team.teamName}----${requestScope.team.teamId}---${requestScope.team.location}</h3>
<h3>test03-----session作用域获取${sessionScope.team.teamName}----${sessionScope.team.teamId}---${sessionScope.team.location}</h3>
<div>
<button type="button" id="btn1">ajax请求自定义对象</button>
<h3>ajax请求自定义对象的结果展示</h3>
<p id="res"></p>
<button type="button" id="btn2">ajax请求List</button>
<h3>ajax请求List的结果展示</h3>
<p id="res2"></p>
<button type="button" id="btn3">ajax请求Map</button>
<h3>ajax请求Map的结果展示</h3>
<p id="res3"></p>
</div>
<script>
$(function (){
$("#btn1").click(function (){
$.ajax({
type: "POST",
url: "/result/test03-3",
data: "",
success: function(msg){
alert( "Data Saved: " + msg);
var name = msg.teamName;
var id = msg.teamId;
var loc = msg.location;
$("#res").html(name+","+id+","+loc);
}
});
});
$("#btn2").click(function (){
$.ajax({
type: "POST",
url: "/result/test03-4",
data: "",
dataType:"json",
success: function(list){
alert( "Data Saved: " + list);
var str="";
for(var i=0;i<list.length;i++){
var obj = list[i];
str+="name:"+obj.teamName+",id:"+obj.teamId+",location:"+obj.location+"<br/>";
}
$("#res2").html(str);
}
});
});
$("#btn3").click(function (){
$.ajax({
type: "POST",
url: "/result/test03-5",
data: "",
dataType:"json",
success: function(map){
alert( "Data Saved: " + map);
var str="";
$.each(map,function (i,obj){
str+="name:"+obj.teamName+",id:"+obj.teamId+",location:"+obj.location+"<br/>";
});
/*for(var i=0;i<list.length;i++){
var obj = list[i];
str+="name:"+obj.teamName+",id:"+obj.teamId+",location:"+obj.location+"<br/>";
}*/
$("#res3").html(str);
}
});
});
});
</script>
</body>
</html>
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">
<!--spring配置-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!--springMVC的前端/中央/核心控制器-->
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name> <!-- dispatcherServlet-servlet.xml-->
<param-value>classpath:springmvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>/</url-pattern><!-- *.action .mvc /-->
</servlet-mapping>
<filter>
<filter-name>httpMethodFilter</filter-name>
<filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>httpMethodFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!--配置中文乱码过滤器-->
<filter>
<filter-name>characterEncodingFilter</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>
<init-param>
<param-name>forceRequestEncoding</param-name>
<param-value>true</param-value>
</init-param>
<init-param>
<param-name>forceResponseEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>characterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern><!--过滤所有请求-->
</filter-mapping>
</web-app>
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.kkb</groupId>
<artifactId>springmvc01</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.13.RELEASE</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
<scope>provided</scope>
</dependency>
<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>
<target>1.8</target>
<source>1.8</source>
</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>