• SpringMVC实战(注解)


     

     1.前言

    前面几篇介绍了SpringMVC中的控制器以及视图之间的映射方式,这篇来解说一下SpringMVC中的注解,通过注解能够非常方便的訪问到控制器中的某个方法.


     2.配置文件配置

    2.1 注解驱动,配置扫描器

    首先须要在SpringMVC中的核心文件里指定注解驱动,详细例如以下:

    <?

    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:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd "> <!-- SpringMVC注解驱动 --> <mvc:annotation-driven/> <!-- SpringMVC的扫描器,假设配置了此扫描器,那么注解驱动就不用再配置了 --> <context:component-scan base-package="com.url.controller"/> <!-- 配置文件形式要配置的组建:Controller,handlermapping(有默认规则),viewResolver,interceptor --> <!-- 视图解析器 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <!-- 配置从项目根文件夹到一端路径 --> <property name="prefix" value="/WEB-INF/jsp/" /> <!-- 文件后缀名称 --> <property name="suffix" value=".jsp" /> </bean> </beans>


    2.2 详细类定义

    package com.url.controller;
    
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    
    /*控制器的标识,当扫描器扫描的时候,会扫描到这是个控制器*/
    @Controller
    public class TestController  {
    
    	/*前台訪问此方法的路径*/
    	@RequestMapping("/hello")
    	public String hello(){
    		return "index";
    	}
    
    	/*也能够为此方法加入參数,用来收集前台传过来的參数*/
    	@RequestMapping("/hello")
    	public String hello(String name,String id){
    		return "index";
    	}
    }
    

    @Controller:标识当前类是控制器层的一个详细的实现

    @requestMapping:放在方法上用来指定某个方法的路径,当放在类上的时候,相当于命名空间须要组合方法上的requestmapping来訪问

    在方法中也能够任意定义方法的參数,怎样方法參数的名称与传入參数的name匹配的话,就会自己主动的接收.而且转换为我们须要的类型.



     3.小结

    本篇博客简单的介绍了SpringMVC中控制器中经常使用的注解,通过注解能够实现高速的訪问控制器信息,方便了开发.


  • 相关阅读:
    利用Openssh后门 劫持root密码
    CentOS 6.9 升级OpenSSH版本 关闭ssh服务后门
    CentOS 7 实现zabbix agent 自动添加,并链接到指定的模版
    CentOS 7 zabbix添加监控服务器
    CentOS 7 Squid代理服务器反向代理
    CentOS 7 Squid代理服务器正向代理-透明代理
    CentOS 7 Squid代理服务器正向代理-传统代理
    CentOS 7 搭建Squid代理服务器
    CentOS 7 配置DHCP中继代理服务
    CentOS 7 配置DHCP
  • 原文地址:https://www.cnblogs.com/cxchanpin/p/7189697.html
Copyright © 2020-2023  润新知