目录

  • 一级目录
  • void
  • 时间转换器
  • 默认参数绑定
  • 重定向
  • 重定向的传值问题
  • 注解
  • @RequestMapping
  • @RequestParam
  • @SessionAttributes
  • @ModelAttribute
  • @RequestHeader
  • @RequestBody
  • @CookieValue
  • @PathVariable
  • Springmvc ant风格


一级目录

void

/*
  返回值类型为void : 无返回值的时候
  void
  情况一:
   404异常 找不到: /WEB-INF/views/void11.jsp
   他会将 @RequestMapping 当成返回值
   等同写成了返回值为String类型的简写
    public  String  show(){
      return "void11";
    }
    
  情况二:
   等同于返回值为任何类型
   可以将任何数据打包成json
 */
@Controller
public class LoginController  extends JsonController {
//    情况一
    @RequestMapping("void001")
    public void show(){
        System.out.println("---这是返回值为void。。。");
    }

//情况二
    /*
    JsonUtilObjecToJson(HttpServletResponse response,
			String code, String msg, Object object)
     */
     @RequestMapping("void002")
     public void void002(HttpServletResponse response){
//         String name = "xiaowang";
//         JsonUtilObjecToJson(response,"","",name);

         Person person = new Person();
         person.setPid(1001);
         person.setPname("laowang");
         person.setAddress("shandong");
         JsonUtilObjecToJson(response,"200","success",person);

     }
}

Json工具类
将任意object类型数据转换成json类型,并放进json域中

@Controller
public class JsonController {
    private String codeKey = "code";
    private String msgKey = "msg";
    private String dateKey = "date";
    private static final Logger LOGGER = LoggerFactory
            .getLogger(JsonController.class);


    protected void JsonUtilObjecToJson(HttpServletResponse response,
                                       String code, String msg, Object object) {
        response.setContentType("application/json;charset=UTF-8");
        ObjectMapper mapper = new ObjectMapper();
        final String resultCode = code;
        final String resultMsg = msg;
        final Object resultObject = object;
        try {
            mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
            mapper.writeValue(response.getWriter(),
                    new HashMap<String, Object>() {
                        {
                            put(codeKey, resultCode);
                            put(msgKey, resultMsg);
                            put(dateKey, resultObject);
                        }
                    });
        } catch (JsonGenerationException | JsonMappingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

时间转换器

前端传到后台的数据类型为string,而对应的属性类型为Date,解决无法赋值的问题
方法一:注解
在自定义封装类中对应属性上添加注解
@DateTimeFormat(pattern = "yyyy-MM-dd") 即可解决问题
方式二:时间转换器 (常用方式)
在Java代码层次基本上,会用到的转换器之一

public class MyConvertor  implements Converter<String, Date> {

    @Override
    public Date convert(String source) {
        Date parse = null ;
        try {
            parse = new SimpleDateFormat("yyyy-MM-dd").parse(source);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return parse;
    }
}

springmvc.xml

<!-- 注解驱动 中间人-->
    <mvc:annotation-driven conversion-service="conversionServiceFactoryBean"></mvc:annotation-driven>

<!--转换器声明-->
    <bean id="conversionServiceFactoryBean" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
        <property name="converters">
            <list>
                <bean class="com.offcn.convertor.MyConvertor"></bean>
            </list>
        </property>
    </bean>

默认参数绑定

HttpServletRequest re ,
Model model
HttpServletResponse response
HttpSession session

// 默认参数绑定
    @RequestMapping("demo")
    public ModelAndView demo(HttpServletRequest request, Model model, Map<String,Object> map, ModelMap modelMap, ModelAndView modelAndView){

        ModelAndView modelAndView1 = new ModelAndView();
//        request.setAttribute("msg","123");
//        model.addAttribute("msg","123");
//        map.put("msg","123");
//        modelMap.addAttribute("msg","123");
         modelAndView1.setViewName("index");
         modelAndView1.addObject("msg","132");
     return modelAndView1;
    }

重定向

特点及注意:

  1. 重定向可以调用
@RequestMapping("r1")
    public String r1(){
        System.out.println("r1");
        return "redirect:r2";
    }
    @RequestMapping("r2")
    public String r2(){
        System.out.println("r2");
        return "redirect:r3";
    }
  1. 重定向可以跨类调用
  2. 当多层路径的时候: 重定向 要加上那个 /
//    http://localhost:8080/mm/r5
    @RequestMapping("mm/r5")
    public String r5(){
        System.out.println("r5");
        return "redirect:/kk/r6";
    //当redirect路径是 kk/r6 时 前端访问路径是  http://localhost:8080/mm/kk/r6
    }

//    http://localhost:8080/kk/r6
@RequestMapping("kk/r6")
public String r6(){
    System.out.println("r6");
    return "index";
}
  1. 浏览器特点 多个 / 可以识别为一个 /
    即:
    http://localhost:8080/r7 http://localhost:8080//r7
    http://localhost:8080///r7
    效果相同
    因此 Java层方法上定义路径时,加上 / 和不加 / 都可以
    但最好不要少了 /

重定向的传值问题

一:redirectAttributes.addAttribute()
访问时,前端路径会带出参数,相当于 get

@RequestMapping("m1")
    public String m1(RedirectAttributes redirectAttributes){
        String name = "xiaofang";
        redirectAttributes.addAttribute("msg",name);
        return "redirect:/m2";
    }
//    http://localhost:8080/m2?msg=xiaofang
    @RequestMapping("m2")
    public String m2(String msg){
        System.out.println("--msg--"+msg);
        return "";
    }

二:redirectAttributes.addFlashAttribute();
访问时,前端路径不会带出参数,相当于 post

@RequestMapping("m3")
    public String m3(RedirectAttributes redirectAttributes){
        String name = "xiaofang";
        redirectAttributes.addFlashAttribute("msg","11");
        return "redirect:/m4";
    }
    @RequestMapping("m4")
    public String m4(String msg){
        System.out.println("msg=="+msg);
        return "redirect:/m2";
    }

注解

@RequestMapping

@RequestMapping 作用: 接收请求

  1. 分模块化
    将 @RequestMapping(“per”) 注解打到类上面去,类中的所有注解中的value值都会默认加上类上注解的value值,如:
    http://localhost:8080/per/savePerson http://localhost:8080/per/deletePersonById
    http://localhost:8080/stu/saveStudent
  2. 方法区分get post
    method = RequestMethod.GET 接收的此请求必须是get提交方式
    method = RequestMethod.POST接收的此请求必须是POST提交方式
    没有配置method的属性默认是get提交方式
  3. value值为空字符时,请求首先进入的是web.xml
    http://localhost:8080/ 此时路径请求在web.xml的默认页面配置中得到匹配,不会再去springmvc路径配置中查找
    很抱歉,此人已经跳转到index.jsp
@Controller
//@RequestMapping("per")
public class RequestMappingController {

     @RequestMapping(value = "savePerson", method = RequestMethod.POST)
     public String m1001(){
         System.out.println("----这是post提交方式--");
         return "index";
     }

//     http://localhost:8080/
     @RequestMapping("")
     public String demo(){
         System.out.println("---index---");
         return "void001";
     }
}

@RequestParam

  1. 前端传值定义的名称,与后端接收定义的名称不相同时,解决无法赋值的问题
/*
    @RequestParam
    http://localhost:8080/m2001?number=18
    1: @RequestParam("number") value值和所匹配的键值对 对应即可接收数据
    2:defaultValue = "10" 可以设置默认值
    3: required = true 必填项 (无效)
     */
    @RequestMapping("m2001")
    public String m2001( @RequestParam(value = "number",required = false , defaultValue = "10") Integer age){
        System.out.println("age=="+age);
        return "";
    }
  1. 前台向后台传递多个值
    路径带参形式为hobby=1001&hobby=1002&hobby=1003&userName=xiaofang时,后台可以利用 @RequestParam 以List集合形式接收
/*
          篮球 1001  足球2001   乒乓球  3001
          http://localhost:8080/m2002?hobby=1001&hobby=1002&hobby=1003&userName=xiaofang
      */
    @RequestMapping("m2002" )
    public String m2002(@RequestParam("hobby") List<Integer> hobby){
        System.out.println(hobby);
        return "";
    }

//    进阶
 @RequestMapping(value = "m2003" )
 public  String  m2002(
        @RequestParam(value = "number",required = false , defaultValue = "10") Integer age,
        @RequestParam("hobby") List<Integer> hobby,
        @RequestParam("hobby") List<Integer> hobby1,
        @RequestParam("hobby") List<Integer> hobby2,
        String userName, Person person){
    System.out.println(hobby);
    return "";

@SessionAttributes

@Controller
@SessionAttributes(value = {"a","b","c","d"})
public class SessionAttributesController {
    /*
       类中所有方法中的 键值对,只要是匹配到SessionAttributes的value值
       都会向 session中部署一份
       注意:request域中的不行!
     */
    @RequestMapping("s1001")
    public String s1001(HttpServletRequest request, Map<String,Object> map, Model model, ModelMap modelMap
    ){
        request.setAttribute("a","11");
        map.put("b","22");
        model.addAttribute("c","33");
        modelMap.addAttribute("d","44");
        return "void001";
    }
}

@ModelAttribute

@ModelAttribute
    public String model(){
        System.out.println("---无论请求到此类中的哪个方法,都先优先运行一下我--");
        return "void001";
    }

@RequestHeader

可以获取请求头里的东西

//   http://localhost:8080/c1001?112132131
    @RequestMapping("c1001")
    public String c1001(@RequestHeader("Cookie") String  msg){
        System.out.println("msg=="+msg);
        return "void001";
    }

@RequestBody

//   可以获取请求体中的东西
//   http://localhost:8080/demo04?name=xiaowang&address=shandong
    @RequestMapping("demo04")
    public String demo4(@RequestBody String body){
//      body = name=xiaowang&address=shandong
        return "";
    }

//checkbox多选框传值 http://localhost:8080/demo05?name=admin&id=1
//ajax传值 {"name":"admin","id":"1"}
//@RequestMapping("demo05")
public String demo5(@RequestBody String body){
        name=admin&id=1
    return "";
}

//用自定义对象接收 用不用该注解一样
//http://localhost:8080/demo06?username=admin&password=123456
@RequestMapping("demo06")
public String demo6(@RequestBody Person per){
//  name=admin&id=1
    return "";
}

@CookieValue

//    @CookieValue 用于从cookie中取值。
//    http://localhost:8080/c1002
    @RequestMapping("c1002")
    public String c1002(@CookieValue("c1") String str){
        System.out.println("展示从浏览器获取过来的c1的cookie值=="+str);
        return "void001";
    }

//    向浏览器发送cookie
    @RequestMapping("c1003")
    public String c1003(HttpServletResponse response){
        Cookie cookie = new Cookie("c1", "xiaowang");
        cookie.setMaxAge(Integer.MAX_VALUE); //无限值  永久cookie
        response.addCookie(cookie);
        return "void001";
    }
}

@PathVariable

前端向后台传值 以 / 隔开时 后台获取

//    
//    http://localhost:8080/p001/8888/9999
    @RequestMapping("p001/{id}/{id2}")
    public String p001(@PathVariable(value = "id")  String personId,@PathVariable("id2") String studentId){
        System.out.println("id=="+personId);
        System.out.println("id=="+studentId);
        return "";
    }
//   PathVariable 万能跳转页面
//http://localhost:8080/per/personUpdate
//http://localhost:8080/per/personSave
    @RequestMapping("per/{page}")
    public String p003(@PathVariable String page){
        System.out.println("per/personUpdate");
        return page;
    }
//    path属性  value也行!!!!!
    @RequestMapping(path = {"demo9001","demo9002"})
    public String p004(){
        System.out.println("per/personUpdate");
        return "";
    }

Springmvc ant风格

SpringMVC Ant风格.
前端多处访问方法名不同,但方法处理相同时

//      http://localhost:8080/p002/mbb 可以进入该方法
//      http://localhost:8080/p002/kbb 可以
//      http://localhost:8080/p002/mbb 不可以
//ant
//SpringMVC支持路径中包含ant风格的通配符,常用的几种通配符及意义如下:
//?  任意一个字符
//*  任意多个字符
//**  匹配多层路径

   @RequestMapping("p002/?bb")
    public String p002(){
       System.out.println("9999");
       return "";
   }