springMVC controller跳转和参数

2018年03月03日 11:09 | 3097次浏览

一、前言

我们上一章节介绍了springMVC+mybatis的整合,本章节重点介绍springMVC的参数,url跳转

二、Controller的返回结果

我们之前都是用modelAndView 

1、现在我们看看所有Controller返回方式:void、String、modelAndView 

2、

重定向redirect:request无法共享,url变化  用例:"redirect:url"

页面转发forword:request共享,url不变化   用例:"forward:url"

package com.ycy.controller;


import com.ycy.dto.ItemsCustom;
import com.ycy.service.ItemsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

/**
 * Created by Administrator on 
 */
@Controller
@RequestMapping("/items")
public class ItemController {

    //注入service
    @Autowired
    private ItemsService itemsService;

    /**
     * 商品展示
     *
     * @param httpServletRequest
     * @param httpServletResponse
     * @return
     * @throws Exception
     */
    @RequestMapping("/queryItems")
    public ModelAndView queryItems(javax.servlet.http.HttpServletRequest httpServletRequest,
                                   javax.servlet.http.HttpServletResponse httpServletResponse) throws Exception {
        //如果是转发:httpServletRequest的数据是可以共享的

        ItemsCustom itemsCustom = new ItemsCustom();
        itemsCustom.setId(1);
        //商品列表
        List<ItemsCustom> itemsList = itemsService.findtemsList(null);
        //创建modelAndView准备填充数据、设置视图
        ModelAndView modelAndView = new ModelAndView();
        //填充数据
        modelAndView.addObject("itemsList", itemsList);
        //视图
        modelAndView.setViewName("order/itemsList");

        return modelAndView;
    }

    /**
     * 修改商品信息1.1
     * @return
     * @throws Exception
     */
    @RequestMapping("/editItems1")
    public ModelAndView editItems() throws Exception {
        ModelAndView modelAndView = new ModelAndView();
        ItemsCustom itemsCustom = itemsService.getItemsById(1, null);
        modelAndView.addObject("item",itemsCustom);
        modelAndView.setViewName("order/editItem");
        return modelAndView;
    }

    /**
     * 修改商品信息1.2
     * @return
     * @throws Exception
     */
    @RequestMapping("/editItems2")
    public String editItems(Model model) throws Exception {
        ModelAndView modelAndView = new ModelAndView();
        ItemsCustom itemsCustom = itemsService.getItemsById(1, null);
        model.addAttribute("item", itemsCustom);
        return "order/editItem";
    }

    /**
     * 修改商品信息1.3
     * @return
     * @throws Exception
     */
    @RequestMapping("/editItems")
    public void editItems(javax.servlet.http.HttpServletRequest httpServletRequest,
                          javax.servlet.http.HttpServletResponse httpServletResponse) throws Exception {
        ModelAndView modelAndView = new ModelAndView();
        ItemsCustom itemsCustom = itemsService.getItemsById(1, null);
        httpServletRequest.setAttribute("item", itemsCustom);
        httpServletRequest.getRequestDispatcher("/pages/jsp/order/editItem.jsp").forward(httpServletRequest,httpServletResponse);
        /**
         * 使用此方法,容易输出json、xml格式的数据:
         通过response指定响应结果,例如响应json数据如下:
         response.setCharacterEncoding("utf-8");
         response.setContentType("application/json;charset=utf-8");
         response.getWriter().write("json串");
         */
    }

    /**
     * 修改商品属性
     * @return
     */
    @RequestMapping("/editItemSubmit")
    public String editItemSubmit(){
        //重定向  request数据无法共享,url地址栏会发生变化的 页面地址:editItemSubmit
        return  "redirect:queryItems";
        //转发   request数据可以共享,url地址栏不会变化 页面地址:queryItems
        //return  "forward:queryItems";
    }
}

三、Controller的参数


早期springmvc是使用PropertyEditor属性编辑器进行参数绑定(仅支持由字符串传为其它类型)

后期springmvc是使用converter转换器进行参数绑定(支持任意类型转换)

参数类型:

1、HttpServletRequest:请求信息

2、HttpServletResponse:处理响应

3、HttpSession:得到session中值

4、Model:通过Model向页面传递数据

5、@RequestParam:对应形参一样自动匹配,否则指定匹配。可以设置默认值,可以设定是否必须传递。

6、简单类型与po类型:int 、double、string、 boolean、 实体UserInfo

示例如下:

  @RequestMapping("/testRequestParam")
    public  void testRequestParam(@RequestParam(value="queryName", required=true,defaultValue = "") String name ){
    // 上面的对传入参数指定为queryName,如果前端不传queryName参数名,会报错
    // required=false表示不传的话,会给参数赋值为null,required=true就是必须要有
    }
    @RequestMapping("/testModel")
    public  String testModel(Model model )throws Exception {
        ModelAndView modelAndView = new ModelAndView();
        ItemsCustom itemsCustom = itemsService.getItemsById(1, null);
        model.addAttribute("item", itemsCustom);
        return "order/editItem";
    }
    @RequestMapping("/testHttpSession")
    public  void testHttpSession(HttpSession  httpSession )throws Exception {
        httpSession.getAttribute("username");
    }
    @RequestMapping("/testHttpSession")
    public  void testHttprequest(javax.servlet.http.HttpServletRequest httpServletRequest,
                                 javax.servlet.http.HttpServletResponse httpServletResponse)throws Exception {
        httpServletRequest.setAttribute("obj", null);
        httpServletRequest.getRequestDispatcher("/pages/jsp/XXX/XXXX.jsp").forward(httpServletRequest,httpServletResponse);
    }

2.1自定义参数(了解)

例如:springMvc没定义日期类型绑定。需要自定义!!!

2.1.1 Controller内自定义属性编辑器

在每一个Controller类里面加一个这样的方法就可以转换日期格式了哦,或者用在父类写入这个方法,继承一个父类就OK。

 //自定义编辑器
    /**
     * 注册属性编辑器(字符串转换为日期)
     */
    @InitBinder
    public void initBinder(WebDataBinder binder) throws Exception {
        binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd HH-mm-ss"),true));
        //System.out.println("init binder =======================");
        binder.registerCustomEditor(BigDecimal.class, new CustomNumberEditor(BigDecimal.class, false));
        binder.registerCustomEditor(Integer.class, null,new CustomNumberEditor(Integer.class, null, true));
        binder.registerCustomEditor(Long.class, null, new CustomNumberEditor(Long.class, null, true));
        binder.registerCustomEditor(Float.class, new CustomNumberEditor(Float.class, true));
        binder.registerCustomEditor(Double.class, new CustomNumberEditor(Double.class, true));
        binder.registerCustomEditor(BigInteger.class, new CustomNumberEditor(BigInteger.class, true));
    }

2.1.2属性 配置编译器xml

1、编写属性编译器java类:propertyeditor

package com.ycy.propertyeditor;

import org.springframework.beans.PropertyEditorRegistrar;
import org.springframework.beans.PropertyEditorRegistry;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.beans.propertyeditors.CustomNumberEditor;

import java.beans.PropertyEditor;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.SimpleDateFormat;
import java.util.Date;

/**自定义属性编辑器
 * Created by Administrator on 2015/9/24 0024.
 */
public class CustomPropertyEditor implements PropertyEditorRegistrar {
    @Override
    public void registerCustomEditors(PropertyEditorRegistry binder) {
        binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd HH-mm-ss"),true));
        //System.out.println("init binder =======================");
        binder.registerCustomEditor(BigDecimal.class, new CustomNumberEditor(BigDecimal.class, false));
        binder.registerCustomEditor(Integer.class, null,new CustomNumberEditor(Integer.class, null, true));
        binder.registerCustomEditor(Long.class, null, new CustomNumberEditor(Long.class, null, true));
        binder.registerCustomEditor(Float.class, new CustomNumberEditor(Float.class, true));
        binder.registerCustomEditor(Double.class, new CustomNumberEditor(Double.class, true));
        binder.registerCustomEditor(BigInteger.class, new CustomNumberEditor(BigInteger.class, true));

    }
}

2、在handlerAdapter适配器中加入我们的属性适配器

<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-4.0.xsd
		http://www.springframework.org/schema/mvc
		http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
		http://www.springframework.org/schema/context
		http://www.springframework.org/schema/context/spring-context-4.0.xsd
		http://www.springframework.org/schema/aop
		http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
		http://www.springframework.org/schema/tx
		http://www.springframework.org/schema/tx/spring-tx-4.0.xsd ">
    <!--1、=========================dispatcher已经在web.xml里面配置==================================-->
    <!-- 使用spring组件扫描 -->
    <context:component-scan base-package="com.ycy.controller"/>

    <!-- 2、3 通过annotation-driven可以替代下边的处理器映射器和适配器 -->
    <!-- 	<mvc:annotation-driven conversion-service="conversionService"></mvc:annotation-driven>-->


    <!--2、=======================使用注解RequestMappingInfoHandlerMapping映射器======================-->
    <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/>

    <!--3、=============================处理器适配器HandlerAdapter====================================-->
    <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
        <!--注解适配器:加入我们的属性解析器 -->
           <property name="webBindingInitializer" ref="customBinder"></property>
       </bean>

       <!--4、============================视图解析器ViewResolver======================================-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
        <property name="prefix" value="/pages/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
    <!--5、视图view与hanlder需要自己实现-->


    <!-- ================================自定义webBinder:属性编辑器===================================-->
    <bean id="customBinder"
          class="org.springframework.web.bind.support.ConfigurableWebBindingInitializer">
        <property name="propertyEditorRegistrars">
            <list>
                <!-- 注册属性编辑器 -->
                <bean id="customPropertyEditor" class="com.ycy.propertyeditor.CustomPropertyEditor" />
            </list>
        </property>
    </bean>

</beans>

2.2参数转换器(必须掌握)

2.2.1 配置方式1针对不使用<mvc:annotation-driven>

1首先编写java转换器

package com.ycy.controller.converter;

import org.springframework.core.convert.converter.Converter;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by Administrator on 
 */
public class CustomDateConverter implements Converter<String, Date> {

    @Override
    public Date convert(String source) {
        try {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            return simpleDateFormat.parse(source);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}

 2 其次根据写的Jva类配置springMVC.xml

 <bean id="customBinder"
          class="org.springframework.web.bind.support.ConfigurableWebBindingInitializer">
        <property name="conversionService" ref="conversionService" />
    </bean>
    <!-- conversionService -->
    <bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
        <!-- 转换器 -->
        <property name="converters">
            <list>
                <bean class="com.ycy.controller.converter.CustomDateConverter"/>
            </list>
        </property>
    </bean>

3  加入适配器

 <!--3、=============================处理器适配器HandlerAdapter====================================-->
    <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
        <!--注解适配器:加入我们的属性解析器 -->
           <property name="webBindingInitializer" ref="customBinder"></property>
       </bean>

2.2.2 配置方式2针对使用<mvc:annotation-driven>的配置

1首先编写java转换器同上

2配置xml

<!-- conversionService -->
    <bean id="conversionService"
          class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
        <!-- 转换器 -->
        <property name="converters">
            <list>
                <bean class="com.ycy.controller.converter.CustomDateConverter"/>
            </list>
        </property>
    </bean>

3 加入适配器

<mvc:annotation-driven conversion-service="conversionService">
</mvc:annotation-driven>

四、总结

这一讲主要讲解Controlleer的返回结果,传入参数。加上mybatis的缓存等等(看mybatis篇先),基本上能够应对你的项目开发的全部。

---摘录自ycy博文



小说《我是全球混乱的源头》

感觉本站内容不错,读后有收获?小额赞助,鼓励网站分享出更好的教程