SpringMVC中的Controller方法的(返回值/参数类型)

一. Controller方法的返回值:

1、 返回的ModelAndView

   ModelAndView 存放数据, addObject(),往model(request域)添加数据

   ModelAndView 添加逻辑视图名, setViewName(), 经过视图解析器,得到物理视图, 转发到物理视图

@RequestMapping("/getUser.action")
    public ModelAndView  getUser(@RequestParam(name="userId",required = true)Integer id) throws Exception{
        System.out.println("id="+id);
        ModelAndView modelAndView = new ModelAndView();
        User user = userService.queryOne(id);
        modelAndView.addObject("user", user);
        modelAndView.setViewName("userinfo");
        return modelAndView;
    }

2、 String类型,  返回的视图

  a. 逻辑视图名,  经过视图解析器,得到物理视图, 转发

@RequestMapping("/index.action")
    public String  toIndex() {
    return "index";    

  b. redirect:资源路径,  不经过视图解析器,要求这个资源路径写完整的路径: /开头,  表示/项目名    重定向到资源

@RequestMapping("/index.action")
public String  toIndex() {
    //重定向到index.jsp,  完整的路径
    return "redirect:/jsp/index.jsp";

  c. forward:资源路径, 不经过视图解析器,要求这个资源路径写完整的路径: /开头,表示/项目名    转发向到资源

@RequestMapping("/index.action")
public String  toIndex() {
    return "forward:/jsp/index.jsp";

  d.响应给前端的字符串,(数据),需要结合@ResponseBody

//将user对象以json的格式响应给前端页面
@RequestMapping("/queryUserByCondition.action")
@ResponseBody
public User   queryUserByCondition(User user) throws Exception{
    return user;
}

3、Java对象

  需要结合@ResponseBody, 发生的数据,(json)

主要用来接收前端传递给后端的json字符串中的数据的(请求体中的数据的),只能是post提交,get没有请求体

@RequestMapping("/queryUserByCondition.action")
@ResponseBody
public User   queryUserByCondition( @RequestBody User user) throws Exception{
    return user;
}

4、 void, 默认逻辑视图名

   controller的@RequestMapping() 前缀+ 方法名,    很少使用

二. Controller方法的参数类型

1、直接注入Servlet API相关的类

  • 1) HttpServletRequest 通过request对象获取请求信息
  • 2) HttpServletResponse 通过response处理响应信息
  • 3) HttpSession 通过session对象得到session中存放的对象
//使用Servlet API 对象
    @RequestMapping("/fun2.action")
    public  String  fun2(HttpServletRequest request, HttpServletResponse response, HttpSession session) {
        System.out.println("fun2().....");
        request.setAttribute("hello", "request_hello");
        session.setAttribute("hello", "session_hello");
        Cookie cookie = new  Cookie("haha","xixi");
        //把cookie保存客户端
        response.addCookie(cookie);
        return "hello";
    }

2、 Model/ModelMap    往model存放/取数据,  request域

  如果我们只是往request域存放数据, 推荐使用Model, Controller类与ServletAPI 解耦

//推荐写法
    @RequestMapping("/fun3.action")
    public  String  fun3(Model model) {
        System.out.println("fun3().....");
        // SpringMVC 框架帮我们把model中的数据, 一个一个添加到request域
        // Model 不能替换Request对象, 
        model.addAttribute("hello","model_hello");
        model.addAttribute("xx", 123);
        return "hello";
    }

3、 接收请求参数

  a、基本数据类型

参数名与请求参数名一样,自动进行映射

如果参数名与请求参数名不一样, 使用@RequestParam 来进行映射

  b、参数是java对象,是一个pojo对象

案例添加用户:Pojo对象的属性名与请求参数的name一样, 自动映射

@RequestMapping(value="/addUser.action",method=RequestMethod.POST)
    public  String  addUser(User user,Model model) {
        userService.saveUser(user);
        model.addAttribute("msg", "添加成功");
        return "msg";
    }

前端页面:

<body>
    <h1>添加用户:</h1>
    <form action="${pageContext.request.contextPath }/user/addUser.action" method="post">
        用户名:<input type="text" name="username" />
        <hr />&nbsp;&nbsp;&nbsp;码:<input type="text" name="password" />
        <hr />&nbsp;&nbsp;&nbsp;别:<input type="radio" name="sex" value="男" id="man"
            checked /><label for="man"></label> <input type="radio" name="sex"
            value="女" id="woman" /><label for="woman"></label>
        <hr />&nbsp;&nbsp;&nbsp;日:<input type="text" name="brithday"  readonly id="brithday"/>
        <hr />&nbsp;&nbsp;&nbsp;址:<input type="text" name="address" />
        <hr />
        <button>添加</button>
    </form>
</body>
View Code

String类型,SpringMVC 不能自动转换为Date类型 ,  需要手动配置

1、局部的转换器, @DateTimeFormat(日期格式)

  只对某一个属性进行转换 ,只需要在日期类型的属性上添加

@DateTimeFormat(pattern = "yyyy-MM-dd")
private Date brithday;

2、 全局的转换器,   对整个项目的所有的date类型进行转换

第一步: 编写一个转换器类, 实现Converter接口

public class MyDateConverter  implements Converter<String, Date>{
    private SimpleDateFormat  sdf = new SimpleDateFormat("yyyy-MM-dd");
    //转换的方法
    @Override
    public Date convert(String source) {
        try {
            return sdf.parse(source);
        } catch (ParseException e) {
            e.printStackTrace();
            throw new RuntimeException("日期格式不对,日期格式:yyyy-MM-dd");
        }
    }
}

第二步: 在springmvc的配置文件进行配置

<!-- 基于注解的处理器映射器,处理器适配器 -->
    <mvc:annotation-driven   conversion-service="conversionService"/>
    
    <!-- 配置全局转换器 -->
    <bean id="conversionService"  class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
        <property name="converters">
            <set>
                <!--内部bean: 这个bean 只能在包括他的bean内部使用 -->
                <bean class="spring09.converter.MyDateConverter"/>
                <!-- 配置多个转换器类的bean -->
            </set>
        </property>
    </bean>

对整个项目的Date类型进行转换

  c、参数是集合属性

Controller参数写法:  需要封装成一个类, 作为这个类的属性(list集合

//批量添加    @RequestMapping(value="/bathAddUser.action",method=RequestMethod.POST)
    public  String  bathAddUser(UserVo userVo,Model model) {
        model.addAttribute("msg", "添加成功");
        return "msg";
    }

UserVo类:

public class UserVo {
    private List<User> users = new ArrayList<>();
    public List<User> getUsers() {
        return users;
    }
    public void setUsers(List<User> users) {
        this.users = users;
    }

前端页面:name="users[0].password"

UserVo中的users属性,list数组,里面的对象下标从0开始,可以使用js赋值,以下页面作为显示效果

<h1>批量添加用户:</h1>
    <form action="${pageContext.request.contextPath }/user/bathAddUser.action" method="post">
        <h1>第一个用户:</h1>
        用户名:<input type="text" name="users[0].username" />
        <hr />&nbsp;&nbsp;&nbsp;码:<input type="text" name="users[0].password" />
        <hr />&nbsp;&nbsp;&nbsp;别:<input type="radio" name="users[0].sex" value="男" id="man"
            checked /><label for="man"></label> <input type="radio" name="users[0].sex"
            value="女" id="woman" /><label for="woman"></label>
        <hr />&nbsp;&nbsp;&nbsp;日:<input type="text" name="users[0].brithday"  readonly class="brithday"/>
        <hr />&nbsp;&nbsp;&nbsp;址:<input type="text" name="users[0].address" />
        <hr />
        
        <h1>第二个用户:</h1>
        用户名:<input type="text" name="users[1].username" />
        <hr />&nbsp;&nbsp;&nbsp;码:<input type="text" name="users[1].password" />
        <hr />&nbsp;&nbsp;&nbsp;别:<input type="radio" name="users[1].sex" value="男" id="man"
            checked /><label for="man"></label> <input type="radio" name="users[1].sex"
            value="女" id="woman" /><label for="woman"></label>
        <hr />&nbsp;&nbsp;&nbsp;日:<input type="text" name="users[1].brithday"  readonly class="brithday"/>
        <hr />&nbsp;&nbsp;&nbsp;址:<input type="text" name="users[1].address" />
        <hr />
        
        <button>添加</button>
View Code

 数组类型:

JSP页面端:

Controller:

 Map集合

JSP页面端:

包装类:

Controller:

 

posted @ 2020-06-16 19:27  64Byte  阅读(2235)  评论(0编辑  收藏  举报