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";
      
     }

    }

  • 相关阅读:
    chrome输入框记住密码导致背景黄色的解决方案
    死活要居中(转载)
    Google HTML/CSS/JS代码风格指南
    CSS的inherit与auto使用分析
    photoshop中rgb与索引模式的区别
    placeholder调整颜色
    你应该了解的5个JavaScript调试技巧
    HTML TAG FROM MDN
    apple iphone 3gs 有锁机 刷机 越狱 解锁 全教程(报错3194,3014,1600,短信发不出去等问题可参考)
    史上最全的CSS hack方式一览
  • 原文地址:https://www.cnblogs.com/snake-hand/p/3170475.html
Copyright © 2011-2022 走看看