9月20日Spring笔记

标签

java

后端

spring

springMVC

RequestMapping

发布时间:

本文字数:933 字 阅读完需:约 4 分钟

SpringMVC处理器

Controller控制器,是MVC中的部分C,是部分的原因是因为此处的控制器主要负责功能处理部分:
收集、验证请求参数并绑定到命令对象;
将命令对象交给业务对象,由业务对象处理并返回模型数据;
返回ModelAndView(Model部分是业务对象返回的模型数据,视图部分为逻辑视图名) ;
而DispatcherServlet主要负责整体的控制流程的调度部分:
负责将请求委托给控制器进行处理;
根据控制器返回的逻辑视图名选择具体的视图进行渲染(并把模型数据传入) ;
因此MVC中完整的C(包含控制逻辑+功能处理)由(DispatcherServlet + Controller)组成,此处的控制器也可以称为页面控制器、动作、处理器;

ModelAndView

ModelAndView 配合 jsp 使用,如果前台是html, 则没有必要用 ModelAndView
jsp的本质是servlet, 执行时会编译成 java 文件

ModelAndView 和 jsp 传值示例

UserController.java

package com.zr.controller;

import com.zr.service.UserService;
import com.zr.utils.Md5Util;
import com.zr.utils.ResultObj;
import com.zr.vo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller

public class UserController {
    @Autowired
    private UserService userService;
    @RequestMapping("user/login.action")
    public ModelAndView login(String userId, String password){
        System.out.println("userId:"+userId+", password"+password);
        User u = new User();
        u.setUserId(userId);
        u.setPassword(Md5Util.md5(password));
        ResultObj robj = userService.login(u);
        ModelAndView mav = new ModelAndView();
        if(robj.isSuccess()){
            mav.addObject("userName", ((User)robj.getObject()).getUserName());
            mav.setViewName("main");
        }
        else{
            mav.setViewName("failed");
        }
        return mav;
    }

}

main.jsp

<%--
  Created by IntelliJ IDEA.
  User: smile
  Date: 2022/9/19
  Time: 19:24
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>恭喜您登录成功</title>
</head>
<body>
    <h1>${userName}, 恭喜您登录成功</h1>
</body>
</html>

上例将userName传入main.jsp

model和view

UserController.java

@RequestMapping("user/login.action")
    public String login(String userId, String password, Model model){
        User u = new User();
        u.setUserId(userId);
        u.setPassword(Md5Util.md5(password));
        ResultObj robj = userService.login(u);
        if(robj.isSuccess()){
            model.addAttribute("user", ((User)robj.getObject()));
            return "main";
        }
        return "user";
    }

上例中,单独将Model拆出,返回值String就是View

其中,Model对象可以改为ModelMap对象或Map对象,底层都是Map
引入javaee包后,可以用httpservletrequest传参,如下示例

@RequestMapping("user/login.action")
    public String login(String userId, String password, HttpServletRequest req, HttpServletResponse resp){
        User u = new User();
        u.setUserId(userId);
        u.setPassword(Md5Util.md5(password));
        ResultObj robj = userService.login(u);
        if(robj.isSuccess()){
            req.setAttribute("user",((User)robj.getObject()));
            return "main";
        }
        return "user";
    }
package com.zr.controller;

import com.zr.service.UserService;
import com.zr.utils.Md5Util;
import com.zr.utils.ResultObj;
import com.zr.vo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

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

@Controller
@RequestMapping("/user")
// 注解可以加在此处

public class UserController {
    @Autowired
    private UserService userService;
@RequestMapping("login.action")
// 与类注解合并,最终为/user/login.action
    public String login(String userId, String password, HttpServletRequest req, HttpServletResponse resp){
        User u = new User();
        u.setUserId(userId);
        u.setPassword(Md5Util.md5(password));
        ResultObj robj = userService.login(u);
        if(robj.isSuccess()){
            req.setAttribute("user",((User)robj.getObject()));
            return "main";
        }
        return "user";
    }
}

@PostMapping, @GetMapping 分别是@RequestMapping的子注解,可以区分请求是Post或Get,从而使同一url映射不同的方法

    @RequestMapping(value = "/login.action", method = RequestMethod.GET)
    public String login(){
        return "login";
    }

上例使用method参数,效果等于@GetMapping注解

常见的get请求

window.location.href=""
<a href="...">百度</a> 输入网址
所有的src属性
<form>不写method属性默认为get

http状态码 405-方法不允许
400-错误的请求(参数绑定错误)

PostMapping注解的参数

示例

    @PostMapping(value = "/add.action", "/insert.action", params = {"userId!=admin","userName","!info"})
    public String add(User u){
        System.out.println(u);
        return "main";
    }

限制userId不能等于admin, 必须有userName参数,不能有info参数

获取url传参

    @RequestMapping("/{year}/print.action")
    public String print(@PathVariable("year") String year){
        System.out.println(year);
        return "main";
    }

上例,用注解@PathVariable("传入的参数名")接收url中传入的参数,url使用{传入的参数名}给后端传参

Ant风格的URL路径映射

@RequestMapping(value="/users/**")
可以匹配“/users/abc/abc”,但“/users/123”将会被[URI模板模式映射中的“/users/{userId}”模式优先映射到]
@RequestMapping(value="/product?")
可匹配“/product1”或“/producta”,但不匹配“/product”或“/productaa”;
@RequestMapping(value="/product*")
可匹配“/productabc”或“/product”,但不匹配“/productabc/abc”;
@RequestMapping(value="/product/*")
可匹配“/product/abc”,但不匹配“/productabc”;
@RequestMapping(value="/products/**/{productId}")
可匹配“/products/abc/abc/123”或“/products/123”,也就是Ant风格和URI模板变量风格可混用;

自定义请求头

@PostMapping(value = "login.action", headers = {"info"})
    public String login(String userId, String password, HttpServletRequest req, HttpServletResponse resp){
        User u = new User();
        u.setUserId(userId);
        u.setPassword(Md5Util.md5(password));
        ResultObj robj = userService.login(u);
        if(robj.isSuccess()){
            req.setAttribute("user",((User)robj.getObject()));
            return "main";
        }
        return "user";
    }

定义后,headers里面必须包含info后端才能执行login()方法, 否则返回404

对请求的content-type进行限制

@PostMapping(value = "login.action", consumes = {"application/x-www-form-urlencoded"})
    public String login(String userId, String password, HttpServletRequest req, HttpServletResponse resp){
        User u = new User();
        u.setUserId(userId);
        u.setPassword(Md5Util.md5(password));
        ResultObj robj = userService.login(u);
        if(robj.isSuccess()){
            req.setAttribute("user",((User)robj.getObject()));
            return "main";
        }
        return "user";
    }

consumes参数进行设置,上例表示必须为表单类型