zoukankan      html  css  js  c++  java
  • Spring MVC注解的一些案列

        1.  spring MVC-annotation(注解)的配置文件ApplicationContext.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"
        xmlns:aop="http://www.springframework.org/schema/aop"
        xmlns:mvc="http://www.springframework.org/schema/mvc" 
        xmlns:tx="http://www.springframework.org/schema/tx" 
         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
            http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
            http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
             http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
    
         <context:component-scan base-package="cn.happy.*"></context:component-scan>
         
    </beans>

        01.spring MVC最基本的注解之零散参数自动装配

    @Controller
    @RequestMapping("/hr")
    public class MyController {
        @RequestMapping("/hello.do")
        public String show(String name,Model model){
            System.out.println("=="+name+"==");
            model.addAttribute("msg",name+"展示页面");
            return "happy";
        }
    }

            其中,方法中的参数与界面表单的name属性并且和实体类中的字段name保持一直("三者合一"),Model类型代替了ModelAndView的用法去装载数据然后直接return到jsp界面,

            如果直接像图中返回happy那样就需要在配置文件中添加一个视图解析器

         <!-- 视图解析器 -->
         <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
         <property name="prefix" value="/WEB-INF/jsp/"></property>
         <property name="suffix" value=".jsp"></property>
        </bean>

              如果界面中的属性不一致,则需用到注解@RequestParam来进行指明

    @RequestMapping(value="/list.do",method=RequestMethod.POST)
        public String list(Model model,@RequestParam(value="uname",required=false) String name){
            System.out.println("=="+name);
            return "happy";
        }

         

           02.spring MVC注解之参数以对象、作用域、map、泛型作为传输数据

    //装配对象类型
       @RequestMapping(value="/list.do",method=RequestMethod.POST)
       public String list(Model model,UserInfo info){
          
           System.out.println("===="+info.getUname()+"	地址"+info.getRadd().getAdd()+"	图书1"+info.getBooklist().get(0).getBookname());
           model.addAttribute("uname", info.getUname());
           return "index";
       }

           03.获取请求的地址栏中的属性参数值

    @Controller
    public class HandleReturn {
        /*
         * 获取地址栏中的属性值
         */
        @RequestMapping("/{rname}/{age}/first.do")
        public String handlereturn(Model model,@PathVariable("rname") String name,@PathVariable int age){
            System.out.println(name+"==="+age);
            model.addAttribute("name", name);
            model.addAttribute("age", age);
            return "handle";
        }
    }

        其中,如果地址栏中的属性名称与方法参数名不一致,就通过如代码所示的注解@PathVariable来指明地址栏中的属性名称rname与name关系

      

          04.spring MVC注解之返回值void、Object、string

    @Controller
    public class HandleAjax {
     
        @RequestMapping("/ajax.do")
        public void handleAjax(HttpServletResponse response) throws Exception{
                   //虚拟出一些数据
                    Map<String, UserInfo> map=new HashMap<String,UserInfo>();
                    UserInfo u1=new UserInfo();
                    u1.setAge(12);
                    u1.setName("恭喜就业");
                    
                    UserInfo u2=new UserInfo();
                    u2.setAge(122);
                    u2.setName("顺利就业");
                    
                    map.put("001",u1);
                    map.put("001",u2);
                    
                    //工具   map----json字符串    fastjson
                    String jsonString = JSON.toJSONString(map);
                    response.setCharacterEncoding("utf-8");
                    //响应流
                    response.getWriter().write(jsonString);
                    response.getWriter().close();
        }
    }
    /*
     * Object返回值类型代替其他类型
     */
    @Controller
    public class HandleAjaxObject {
    
        @RequestMapping("/num.do")
        @ResponseBody
        public Object number() {
            return 1;
        }
    
        @RequestMapping(value = "/nums.do", produces = "text/html;charset=utf-8")
        @ResponseBody
        public Object numberS() {
            return "汉字";
        }
    
        // 处理器方法-----UserInfo
        @RequestMapping(value = "/third.do")
        @ResponseBody
        public Object doThird() {
            UserInfo info = new UserInfo();
            info.setAge(12);
            info.setName("Happy");
            return info;
        }

         

           使用Object作为返回值需要用到注解@ResponseBody来将数据回传到jsp界面

             

    ----js
    
    <script type="text/javascript">
          $(function(){
             $("#btn").click(function(){
                   
                $.ajax({
                   url:"nums.do",
                   success:function(data){ //data指的是从server打印到浏览器的数据                  
                       alert(data)
                }
                });
             });
          });
        </script>
    
    -----body
    
    <input type="button" id="btn" value="Ajax"/>

        使用void返回值返回json数据回传到jsp界面

    <script type="text/javascript">
          $(function(){
             $("#btn").click(function(){     
                $.ajax({
                   url:"ajax.do",
                   success:function(data){ //data指的是从server打印到浏览器的数据
                       //jsonString jsonObject
                       //{"001":{"age":122,"name":"顺利就业"}}
                      var result= eval("("+data+")");
                      $.each(result,function(i,dom){
                          alert(dom.age)
                      });                
                   }
                 });
             });
          });
        </script>
    
    <input type="button" id="btn" value="Ajax"/>

      

          最后就是String类型的了,不过跟void类型的返回值很相似

         使用String作为返回值需要用到注解@ResponseBody来支持json数据回传到jsp界面

    /*
     * String返回值类型代替其他类型
     */
    @Controller
    public class HandleAjax {
        @RequestMapping("/ajax.do")
        public void handleAjax(HttpServletResponse response) throws Exception{
                    //伪造数据
                    Map<String, UserInfo> map=new HashMap<String,UserInfo>();
                    UserInfo u1=new UserInfo();
                    u1.setAge(12);
                    u1.setName("恭喜就业");
                    
                    UserInfo u2=new UserInfo();
                    u2.setAge(122);
                    u2.setName("顺利就业");
                    
                    map.put("001",u1);
                    map.put("001",u2);
                    
                    //工具   map----json字符串    fastjson
                    String jsonString = JSON.toJSONString(map);
                    response.setCharacterEncoding("utf-8");
                return jsonString ;
        }

         05.重定向到另一个方法去

    /*
     * 转发与重定向
     * 重定向到另一个方法
     */
    @Controller
    public class Dispatchreturn {
    
        /*
         * 重定向到另一个方法dsipatch.do
         */
        @RequestMapping(value="add.do")
        public String AddAllInfo(){
            return "redirect:dolist.do";
        }
        
        @RequestMapping(value="dolist.do")
        public String doList(){
            return "redirect:/list.jsp";
        }
    }

        注意:"/"可写可不写

  • 相关阅读:
    <剑指OFFER18> 18_01_DeleteNodeInList在O(1)时间删除链表结点
    哈夫曼树

    快速排序
    冒泡算法
    Java 缓存机制
    JAVA NIO
    string、stringbuilder、stringbuffer区别
    Java内存泄露的问题调查定位
    使用hibernate 框架搭建的helloworld
  • 原文地址:https://www.cnblogs.com/bdpsc/p/6087070.html
Copyright © 2011-2022 走看看