zoukankan      html  css  js  c++  java
  • springMVC之annotation优化

    1.在之前配置的spring配置文件中会有这样的代码:

    <!-- 方法映射 -->
     <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"></bean>
     <!-- 找类 -->
     <bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"></bean>

    这两句是注入开启映射的类。

    在spring3.0后有了mvc标签,可以将上两句改为:

    <mvc:annotation-driven/>

    同样可以达到以上的结果。

    2.在controller中我们是这样配置的:

    package com.yx.controller.annotation;

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

    @Controller
    public class HelloAnnotationController {

     @RequestMapping(value="/user/adduser",method=RequestMethod.GET)
     public ModelAndView addUser(){
      
      return new ModelAndView("/annotationTest","result","add user");
      
     }
     @RequestMapping(value="/user/deluser")
     public ModelAndView delUser(){
      
      return new ModelAndView("/annotationTest","result","delete user");
      
     }

    }
    这里面也有很多可以优化的:

    (1).对于传输方法,在平时开发时没有必要必须规定是什么方法传输,也就是无论get还是post均可以运行。这样只要将“method=RequestMethod.GET”删掉即可。

    (2).在没给个方法前面都会出现“/user”即为命名空间,这样代码会太重复。可以在类的前面加上“@RequestMapping("/user2")”

    (3).在struts2中方法的返回值一般为String,在springMVC中也可以这样做。

    最后controller的代码可以修改为:

    package com.yx.controller.annotation;

    import javax.servlet.http.HttpServletRequest;

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

    @Controller
    @RequestMapping("/user2")
    public class HelloAnnotationController2 {

     @RequestMapping("/adduser")
     public String addUser(HttpServletRequest request){
      request.setAttribute("result","add user 方法");
      return "/annotationTest";
      
     }
     @RequestMapping("/deluser")
     public String delUser(HttpServletRequest request){
      request.setAttribute("result","delete user上述");
      return "/annotationTest";
      
     }

    }

  • 相关阅读:
    socketpair和pipe的区别
    C++异常与析构函数及构造函数
    System v shm的key
    不可靠信号SIGCHLD丢失的问题
    非阻塞IO函数
    Android 编译时出现r cannot be resolved to a variable
    找工作笔试面试那些事儿(5)---构造函数、析构函数和赋值函数
    unable to load default svn client 和 Eclipse SVN 插件与TortoiseSVN对应关系
    演示百度地图操作功能
    求第i个小的元素 时间复杂度O(n)
  • 原文地址:https://www.cnblogs.com/snake-hand/p/3170475.html
Copyright © 2011-2022 走看看