Spring-MVC 基于注解控制器

  SpringMVC是一个基于DispatcherServlet的MVC框架,每个请求最先访问的是DispatcherServlet,DispatcherServlet负责将每一个Request转发到相应的Handler,Handler处理后再返回相应的模型(Model)和视图(View)。在使用注解的Spring MVC中,处理器Handler是基于@Controller和@RequestMapping两个注解的,这两个注解可以提供非常灵活的匹配和处理方式

   web.xml配置如下

1 <servlet>
2         <servlet-name>springDispatcherServlet</servlet-name>
3         <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
4         <init-param>
5             <param-name>contextConfigLocation</param-name>
6             <param-value>classpath:spring-mvc.xml</param-value>
7         </init-param>
8         <load-on-startup>1</load-on-startup>
9     </servlet>

 

 

 一.@Controller和@RequestMapping

  •  @Controller注解类型

   声明一个控制器类,Spring使用扫描机制来找到应用程序中所有基于注解的控制器类,控制器类的内部包含每个动作相应的处理方法,如下是一个@Controller的例子

      

 1 @Controller
 2 public class SignController {
 3     @Autowired
 4     private ISignService signService;
 5 
 6     /**
 7      * 打卡签到
 8      * 
 9      * @param uid
10      * @return
11      */
12     @GetMapping("/jsp/addSign")
13     public String addSgin(int uid) {
14 
15         int addSign = signService.addSign(uid);
16 
17         return "right";
18     }
19 
20     /**
21      * 查询打卡记录
22      * 
23      * @param model
24      * @return
25      */
26     @RequestMapping("/selectSign")
27     public String selecetSign(Model model, @RequestParam(value = "page", defaultValue = "1") Integer page,
28             HttpSession session) {

 

 为了保证Spring能扫描到控制器类,需要完成两个配置,首先要在Spring MVC的spring-mybatils.xml配置文件中声明Spring-context,其次需要应用<component-scan/>元素,在该元素中指定控制器类的基本包。例如所有的控制器类都在com.example.controller及其子包下,则该元素如下所示:

<?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:aop="http://www.springframework.org/schema/aop"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:p="http://www.springframework.org/schema/p"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">

    <context:property-placeholder location="classpath:jdbc.properties" />

    <context:component-scan base-package="com.qf.controller"></context:component-scan>
    
   <!--*********************链接数据源**************************  -->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="${driver}" />
        <property name="url" value="${url}" />
        <property name="username" value="${user}" />
        <property name="password" value="${pass}" />
        <property name="minIdle" value="1" />
    </bean>
    <!--********************SqlSession的获取,指定数据源******************** -->
    <bean id="sf" class="org.mybatis.spring.SqlSessionFactoryBean">
    
        <!-- 指定sqlMapConfig总配置文件,订制的environment在spring容器中不在生效-->
        <property name="configLocation" value="classpath:mybatis-config.xml" />
        <property name="typeAliasesPackage" value="com.qf.pojo" />
        <property name="mapperLocations" value="classpath:com/qf/dao/mapper/*Mapper.xml" />
        <property name="dataSource" ref="dataSource"></property>
    </bean>
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.qf.dao" />
        <property name="sqlSessionFactoryBeanName" value="sf"></property>
    </bean>
    
    <!--通过<tx:advice>标签定义事务增强,并制定事务管理器 -->
    <tx:advice id="txAdvice" transaction-manager="txManager">
        <!--定义属性,声明事务规则 -->
        <tx:attributes>
            <tx:method name="create*" propagation="REQUIRED" isolation="DEFAULT"
                rollback-for="Exception" />
            <tx:method name="insert*" propagation="REQUIRED" isolation="DEFAULT"
                rollback-for="Exception" />
            <tx:method name="add*" propagation="REQUIRED" isolation="DEFAULT"
                rollback-for="Exception" />
            <tx:method name="upd*" propagation="REQUIRED" isolation="DEFAULT"
                rollback-for="Exception" />
            <tx:method name="del*" propagation="REQUIRED" isolation="DEFAULT"
                rollback-for="Exception" />
            <tx:method name="execute*" propagation="REQUIRED"
                isolation="DEFAULT" rollback-for="Exception" />
            <tx:method name="do*" propagation="REQUIRED" isolation="DEFAULT"
                rollback-for="Exception" />
            <tx:method name="save*" propagation="REQUIRED" isolation="DEFAULT"
                rollback-for="Exception" />
            <tx:method name="set*" propagation="REQUIRED" isolation="DEFAULT"
                rollback-for="Exception" />
            <tx:method name="get*" propagation="SUPPORTS" isolation="DEFAULT"
                read-only="true" />
            <tx:method name="show*" propagation="SUPPORTS" isolation="DEFAULT"
                read-only="true" />
            <tx:method name="list*" propagation="SUPPORTS" isolation="DEFAULT"
                read-only="true" />
            <tx:method name="select*" propagation="SUPPORTS" isolation="DEFAULT"
                read-only="true" />
            <tx:method name="query*" propagation="SUPPORTS" isolation="DEFAULT"
                read-only="true" />
            <tx:method name="has*" propagation="SUPPORTS" isolation="DEFAULT"
                read-only="true" />
            <tx:method name="ntx*" propagation="NOT_SUPPORTED" />
            <tx:method name="*" propagation="SUPPORTS" isolation="DEFAULT"
                read-only="true" />
        </tx:attributes>
    </tx:advice>

    <!-- 定义切面 -->
    <aop:config>
        <aop:pointcut id="serviceMethod"
            expression="execution(* com.qf.service..*.*(..))" />
        <!-- 将事务增强与切入点组合(织入事务切面) -->
        <aop:advisor pointcut-ref="serviceMethod" advice-ref="txAdvice" />
    </aop:config>
    
    <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">  
     <property name="dataSource" ref="dataSource" />  
    </bean>

</beans>

  确保所有控制器都在基本包下,并且不要指定太广泛的基本包,否则会导致Spring MVC扫描无关的包。

 

  • @RequestMapping注解类型

  该注解类型在控制器类的内部定义每一个动作相应的处理方法,一个采用@RequestMapping注释的方法将成为一个请求处理方法,并由调度程序在接收到对应的URL请求时调用,下面是一个RequestMapping注解方法的控制器类。

package com.example.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
...

@Controller
public class ProductController {
    
    @RequestMapping(value="/productInput")
    public String inputProduct(){
        //do something here
        return "ProductForm";
    }
}

使用RequestMapping注解的value属性将URL映射到方法,在如上的例子中,我们将productInput映射到inputProduct()方法,通过http://localhost:8081/SpringMVC/productInput访问inputProduct方法。RequestMapping方法除了有value属性外,还有method属性,该属性用来指示该方法仅处理哪些http方法,例如,仅当HTTP POST或PUT方法时,调用下面的processOrder方法。

@RequestMapping(value="/order_process", method={RequestMethod.POST, RequestMethod.PUT})
public String processOrder(){
    //do something here
    return "OrderForm";
}

如果method属性只有一个HTTP方法值,则无需{},直接为method=RequestMethod.POST,如果未指定method属性,则请求处理方法可以处理任意HTTP方法。此外RequestMapping注释类型也可以用来注释一个控制器类,如下所示:

import org.springframework.stereotype.Controller;
...

@Controller
@RequestMapping(value="/customer")
public class CustomerController{
    @RequestMapping(value="/delete", method={RequestMethod.POST, RequestMethod.PUT})
    public String deleteCustomer(){
        //do something here
        return ...;
    }
}

在这种情况下,所有的方法都将映射为相对于类级别的请求,如例子中的deleteCustomer方法,由于控制器类映射使用"/customer",而deleteCustomer方法映射为"/delete",则需要通过http://localhost:8081/SpringMVC/customer/delete。

2017-12-09

 

posted @ 2017-12-09 19:29  你的安静  阅读(189)  评论(0编辑  收藏  举报