SpringMVC-06-使用@Controller、@RequestMapping注解开发

2.6 使用注解开发
  • Spring 2.5 版本新增了 Spring MVC 注解功能,用于替换传统的基于 XML 的 Spring MVC 配置

使用基于注解的控制器具有以下 2 个优点:

  • 在基于注解的控制器类中可以编写多个处理方法,所以可以处理多个请求(动作),实现Controller接口这种方式一个请求就需要对应一个Controller,比较麻烦且不易维护

  • 基于注解的控制器不需要在配置文件中部署映射,仅需要使用 @RequestMapping 注解一个方法进行请求处理即可。

2.6.1 Controller注解
  • Controller注解:用于声明某类的实例是一个控制器,解析用户请求将其转换为一个模型
  • Controller注解:底层实现了Controller接口,获得控制器功能,Controller接口是一个函数式接口
ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception;
  • 该方法表示处理请求返回一个模型视图对象

  • 一个控制器可以有多个方法,此注解会被视图解析器解析

  • Spring MVC 使用扫描机制找到应用中所有基于注解的控制器类,所以,为了让控制器类被 Spring MVC 框架扫描到,需要在配置文件中声明 spring-context,并使用 <context:component-scan/> 元素指定控制器类的基本包

<?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">

    <context:component-scan base-package="com.zk.controller"/>

    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
</beans>
  • @RestController:这个控制器下所有方法返回json格式的字符串,不走视图解析器,前后端分离时不走视图解析器
2.6.2 RequestMapping注解
  • 一个控制器内有多个处理请求的方法,每个方法负责不同的请求操作,而 @RequestMapping 就负责将请求映射到对应的控制器方法上。

  • 在基于注解的控制器类中可以为每个请求编写对应的处理方法。使用 @RequestMapping 注解将请求与处理方法一 一对应即可。

  • @RequestMapping 注解可用于类或方法上。用于类上,表示类中的所有响应请求的方法都以该地址作为父路径。

  • 常用属性

  • value 属性是 @RequestMapping 注解的默认属性,因此如果只有 value 属性时,可以省略该属性名,如果有其它属性,则必须写上 value 属性名称。value 属性支持通配符匹配,如 @RequestMapping(value=“sys/*”)

  • path属性 和value 属性都用来作为映射使用,用法一样。

  • name属性相当于方法的注释。如 @RequestMapping(value = “login”,name = “登录”)。

  • method 属性用于表示该方法支持哪些 HTTP 请求。如果省略,则说明该方法支持全部的 HTTP 请求。可以支持多个类型请求

@RequestMapping(value = "login",method = {RequestMethod.GET,RequestMethod.POST}),说明该方法同时支持 GET 和 POST 请求。
  • params 设置参数:params 属性用于指定请求中规定的参数.下面代码表示请求中必须包含 username 参数时才能执行该请求。即 http://localhost:8080/toUser?type=xxx 能够正常访问 toUser() 方法, http://localhost:8080/toUser无法访问
@RequestMapping(value = "login",params = "username")
  • params 设置参数值:下面代码表示请求中 username 参数必须为admin时才能执行该请求。
@RequestMapping(value = "login",params = "username=admin")
  • header 属性表示请求中必须包含某些指定的 header 值。
@RequestMapping(value = "login",headers = "Referer=xxx") 
表示请求的 header 中必须包含了指定的“Referer”请求头,以及值为“xxx”时,才能执行该请求。
  • consumers 属性用于指定处理请求的提交内容类型(Content-Type),例如:application/json、text/html。
@RequestMapping(value = "login",consumes = "application/json")。
  • produces 属性用于指定返回的内容类型,返回的内容类型必须是 request 请求头(Accept)中所包含的类型。还可以指定返回值的编码
@RequestMapping(value = "toUser",produces = "application/json,charset=utf-8")。
  • @RequestMapping 来完成映射,包括 4 个方面的信息项:请求 URL、请求参数、请求方法和请求头

  • 请求 URL映射方法时有两种方式

方法级别注解: @RequestMapping(value = “/sys/login”),类上不用加@RequestMapping,这就要求:在整个 Web 项目中,@RequestMapping 映射的请求信息必须保证全局唯一。

类级别注解下:控制器类中的所有方法都将映射为类级别的请求。建议采用类级别注解,将相关处理放在同一个控制器类中,方便维护

@Controller
@RequestMapping("/sys")
public class SysController {

    @RequestMapping("/login")
    public ModelAndView login(){}
}

@RequestMapping 除了可以使用请求 URL 映射请求之外,还可以使用请求参数、请求方法来映射请求,通过多个条件可以让请求映射更加精确。

@RequestMapping("/sys")
public class SysController {

    @RequestMapping(value = "/login",params = "username",method = RequestMethod.POST)
    public ModelAndView login(@RequestParam String username){}
}
  • 可以在请求处理方法中使用 Servlet API 参数类型。
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RequestMapping("/register")
public ModelAndView regist(HttpServletRequest req, HttpServletResponse resp){

}
  • 还可以传org.springframework.ui.Model 类型。是一个包含 Map 的 Spring MVC类型。在每次调用请求处理方法时 Spring MVC 都将创建 org.springframework.ui.Model 对象,这个model对象针对本次请求有效,即作用域是request域。
import org.springframework.ui.Model;
@RequestMapping("/register")
    public ModelAndView regist(Model model){
    
    }
  • 请求处理方法常见的返回类型
  • ModelAndView
  • Model
  • 包含模型属性的 Map
  • View
  • 代表逻辑视图名的 String
  • void
  • 其它任意Java类型
  • 最常见的返回类型就是代表逻辑视图名称的 String 类型,如果有具体的String 类型代表的页面可以跳转,在和@Controller配合才能被视图解析器解析
  • 两个请求返回字符可以是一样的,但页面的结果是不一样的(用一下标记语言来显示数据),可以看出前端页面就是一个模板,被不同请求复用,反应了控制器和视图间的弱耦合关系
2.6.3 举例
  • 改造上面的例子

  • 项目的web.xml文件不变

  • 修改springmvc的配置文件springmvc-servlet.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">
	<!--开启注解-->
    <context:component-scan base-package="com.zk.controller"/>
	<!--让spring-mvc不处理静态资源.css .js-->
    <mvc:default-servlet-handler/>
    <!--
    支持mvc注解驱动
    在spring-mvc使用@RequestMapping来完成映射,要让@RequestMapping生效
    需要向上下文中注册DefalutAnnotationHandlerMapping和AnnotationMethodHandlerAdapter实例
    分别用来在类级别和方法级别处理
    annotation-driven设置可以自动将上诉实例注入
    -->
    <mvc:annotation-driven/>
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
</beans>
  1. <!- annotation-driven用于简化开发的配置,注解DefaultAnnotationHandlerMapping和AnnotationMethodHandlerAdapter -->
  2. <!- 使用resources过滤掉不需要dispatcherservlet的资源(即静态资源,例如css、js、html、images)。
  3. ​ 在使用resources时必须使用annotation-driven,否则resources元素会阻止任意控制器被调用 -->
  4. <!- 允许js目录下的所有文件可见 -->
  5. <mvc:resources location=“/” mapping=“/ ** **” **/>
  • 编写控制类
package com.zk.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

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

/**
 * @author CNCLUKZK
 * @create 2022/7/1-19:35
 */
@Controller
@RequestMapping("/sys")
public class SysController {

    @RequestMapping(value = "/login",params = "username",method = RequestMethod.POST)
    public ModelAndView login(@RequestParam String username){
        ModelAndView mv =  new ModelAndView();
        mv.addObject("username",username);
        mv.addObject("msg","登录过程!");
        mv.setViewName("login");
        return mv;
    }
    @RequestMapping(value = "/login2",params = "username",method = RequestMethod.POST)
    public String login2(HttpServletRequest req,HttpServletResponse resp,
                               @RequestParam String username){
        req.getSession().setAttribute("username",username);
        req.getSession().setAttribute("msg","登录过程!");
        return "login";
    }
    @RequestMapping("/register")
    public ModelAndView regist(){
        ModelAndView mv =  new ModelAndView();
        mv.addObject("msg","注册过程!");
        mv.setViewName("register");

        return mv;
    }

    @RequestMapping("/register2")
    public String regist2(Model model){
    	//向模型中添加属性msg和值
        /*在视图中可以使用EL表达式${msg}取出model中的值*/
        model.addAttribute("msg","注册过程!");
        return "register";
    }
}
  • 编写页面,使用项目生成的index.jsp页面
<%--
  Created by IntelliJ IDEA.
  User: CNCLUKZK
  Date: 2022/6/30
  Time: 17:14
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
  <title>$Title$</title>
</head>
<body>
<%--${pageContext.request.contextPath}尽量加上--%>
<form action="/sys/login" method="post">
  <input type="text" name="username" placeholder="login">
  <input type="submit" value="提交">
</form>
<hiv>
  <a href="${pageContext.request.contextPath}/sys/login" name="登录"/>登录
  <a href="${pageContext.request.contextPath}/sys/register" name="注册"/>注册
  <a href="${pageContext.request.contextPath}/sys/register2" name="注册2"/>注册2
</hiv>
<br/>
<form action="/sys/login2" method="post">
  <input type="text" name="username" placeholder="login2">
  <input type="submit" value="提交">
</form>
</body>
</html>
  • 在/WEB-INF/jsp/下面建两个页面用来显示结果login.jsp、register.jsp保证视图安全
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
用户:${username}
登录结果:${msg}
</body>
</html>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
注册结果:${msg}
</body>
</html>
  • 启动服务器开始测试
  • 注意:springmvc必须配置的三元素

处理器映射器

处理器适配器

视图解析器

只需要手动设置视图解析器,其他两个只需要开启mvc的注解驱动即可自动注入

SpringMVC-07-@ModelAttribute注解功能
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值