SpringMVC第三篇【收集参数、字符串转日期、结果重定向、返回JSON】

来源:互联网 发布:宝宝照片创意软件 编辑:程序博客网 时间:2024/06/07 01:28

业务方法收集参数

我们在Struts2中收集web端带过来的参数是在控制器中定义成员变量,该成员变量的名字与web端带过来的名称是要一致的…并且,给出该成员变量的set方法,那么Struts2的拦截器就会帮我们自动把web端带过来的参数赋值给我们的成员变量….

那么在SpringMVC中是怎么收集参数的呢????我们SpringMVC是不可能跟Struts2一样定义成员变量的,因为SpringMVC是单例的,而Struts2是多例的。因此SpringMVC是这样干的:

  • 业务方法写上参数
  • 参数的名称要和web端带过来的数据名称要一致

接收普通参数

如果是普通参数的话,我们直接在方法上写上与web端带过来名称相同的参数就行了!

<form action="${pageContext.request.contextPath}/hello.action" method="post">    <table align="center">        <tr>            <td>用户名:</td>            <td><input type="text" name="username"></td>        </tr>        <tr>            <td>编号</td>            <td><input type="text" name="id"></td>        </tr>        <tr>            <td colspan="2">                <input type="submit" value="提交">            </td>        </tr>    </table></form>
    @RequestMapping(value = "/hello.action")    public String hello(Model model, String username, int id) throws Exception {        System.out.println("用户名是:" + username);        System.out.println("编号是:" + id);        model.addAttribute("message", "你好");        return "/index.jsp";    }

效果:

这里写图片描述


接收JavaBean

我们处理表单的参数,如果表单带过来的数据较多,我们都是用JavaBean对其进行封装的。那么我们在SpringMVC也是可以这么做的。

  • 创建Javabean
  • javaBean属性与表单带过来的名称相同
  • 在业务方法上写上Javabean的名称

创建JavaBean,javaBean属性与表单带过来的名称相同

public class User {    private String id;    private String username;    public User() {    }    public User(String id, String username) {        this.id = id;        this.username = username;    }    public String getId() {        return id;    }    public void setId(String id) {        this.id = id;    }    public String getUsername() {        return username;    }    public void setUsername(String username) {        this.username = username;    }    @Override    public String toString() {        return "User{" +                "id='" + id + '\'' +                ", username='" + username + '\'' +                '}';    }}

在业务方法参数上写入Javabean

    @RequestMapping(value = "/hello.action")    public String hello(Model model,User user) throws Exception {        System.out.println(user);        model.addAttribute("message", "你好");        return "/index.jsp";    }

这里写图片描述


收集数组

收集数组和收集普通的参数是类似的,看了以下的代码就懂了。

<form action="${pageContext.request.contextPath}/hello.action" method="post">    <table align="center">        <tr>            <td>用户名:</td>            <td><input type="text" name="username"></td>        </tr>        <tr>            <td>爱好</td>            <td><input type="checkbox" name="hobby" value="1">篮球</td>            <td><input type="checkbox" name="hobby" value="2">足球</td>            <td><input type="checkbox" name="hobby" value="3">排球</td>            <td><input type="checkbox" name="hobby" value="4">羽毛球</td>        </tr>        <tr>            <td colspan="2">                <input type="submit" value="提交">            </td>        </tr>    </table></form>

业务方法获取参数

    @RequestMapping(value = "/hello.action")    public String hello(Model model,int[] hobby) throws Exception {        for (int i : hobby) {            System.out.println("喜欢运动的编号是:" + i);        }        model.addAttribute("message", "你好");        return "/index.jsp";    }

效果:

这里写图片描述

收集List<JavaBean>集合

我们在Spring的业务方法中是不可以用List这样的参数来接收的,SpringMVC给了我们另一种方案!

我们使用一个JavaBean把集合封装起来,给出对应的set和get方法。那么我们在接收参数的时候,接收的是JavaBean

/** * 封装多个Emp的对象  * @author AdminTC */public class Bean {    private List<Emp> empList = new ArrayList<Emp>();    public Bean(){}    public List<Emp> getEmpList() {        return empList;    }    public void setEmpList(List<Emp> empList) {        this.empList = empList;    }}

业务方法接收JavaBean对象

    /**     * 批量添加员工     */    @RequestMapping(value="/addAll",method=RequestMethod.POST)    public String addAll(Model model,Bean bean) throws Exception{        for(Emp emp:bean.getEmpList()){            System.out.println(emp.getUsername()+":"+emp.getSalary());        }        model.addAttribute("message","批量增加员工成功");        return "/jsp/ok.jsp";    }

在JSP页面直接写上empList[下表].

<form action="${pageContext.request.contextPath}/emp/addAll.action" method="POST">        <table border="2" align="center">            <caption><h2>批量注册员工</h2></caption>            <tr>                <td><input type="text" name="empList[0].username" value="哈哈"/></td>                <td><input type="text" name="empList[0].salary" value="7000"/></td>            </tr>            <tr>                <td><input type="text" name="empList[1].username" value="呵呵"/></td>                <td><input type="text" name="empList[1].salary" value="7500"/></td>            </tr>            <tr>                <td><input type="text" name="empList[2].username" value="班长"/></td>                <td><input type="text" name="empList[2].salary" value="8000"/></td>            </tr>            <tr>                <td><input type="text" name="empList[3].username" value="键状哥"/></td>                <td><input type="text" name="empList[3].salary" value="8000"/></td>            </tr>            <tr>                <td><input type="text" name="empList[4].username" value="绿同学"/></td>                <td><input type="text" name="empList[4].salary" value="9000"/></td>            </tr>            <tr>                <td colspan="2" align="center">                    <input type="submit" value="批量注册"/>                </td>            </tr>        </table>    </form>

其实这种方法看起来也没有那么难理解,我们就是向上封装了一层【与接收普通的JavaBean类似的】


收集多个模型

我们有可能在JSP页面上即有User模型的数据要收集,又有Emp模型的数据要收集….并且User模型的属性和Emp模型的属性一模一样….此时我们该怎么办呢???

我们也是可以在User模型和Emp模型上向上抽象出一个Bean,该Bean有Emp和User对象

/** * 封装User和Admin的对象 * @author AdminTC */public class Bean {    private User user;    private Admin admin;    public Bean(){}    public User getUser() {        return user;    }    public void setUser(User user) {        this.user = user;    }    public Admin getAdmin() {        return admin;    }    public void setAdmin(Admin admin) {        this.admin = admin;    }}

在JSP页面收集的时候,给出对应的类型就行了。

    <form action="${pageContext.request.contextPath}/person/register.action" method="POST">        <table border="2" align="center">            <tr>                <th>姓名</th>                <td><input type="text" name="user.username" value="${user.username}"/></td>            </tr>            <tr>                <th>月薪</th>                <td><input type="text" name="user.salary" value="${user.salary}"></td>            </tr>            <tr>                <th>入职时间</th>                <td><input                         type="text"                         name="user.hiredate"                         value='<fmt:formatDate value="${user.hiredate}" type="date" dateStyle="default"/>'/></td>            </tr>            <tr>                <td colspan="2" align="center">                    <input type="submit" value="普通用户注册" style="width:111px"/>                </td>            </tr>        </table>        </form> 

字符串转日期类型

我们在Struts2中,如果web端传过来的字符串类型是yyyy-mm-dd hh:MM:ss这种类型的话,那么Struts2默认是可以自动解析成日期的,如果是别的字符串类型的话,Struts2是不能自动解析的。要么使用自定义转换器来解析,要么就自己使用Java程序来解析….

而在SpringMVC中,即使是yyyy-mm-dd hh:MM:ss这种类型SpringMVC也是不能自动帮我们解析的。我们看如下的例子:

JSP传递关于日期格式的字符串给控制器…

<form action="${pageContext.request.contextPath}/hello.action" method="post">    <table align="center">        <tr>            <td>用户名:</td>            <td><input type="text" name="username"></td>        </tr>        <tr>            <td>出生日期</td>            <td><input type="text" name="date" value="1996-05-24"></td>        </tr>        <tr>            <td colspan="2">                <input type="submit" value="提交">            </td>        </tr>    </table></form>

User对象定义Date成员变量接收

 public Date getDate() {        return date;    }    public void setDate(Date date) {        this.date = date;    }

业务方法获取Date值

    @RequestMapping(value = "/hello.action")    public String hello(Model model, User user) throws Exception {        System.out.println(user.getUsername() + "的出生日期是:" + user.getDate());        model.addAttribute("message", "你好");        return "/index.jsp";    }

结果出问题了,SpringMVC不支持这种类型的参数:

这里写图片描述


现在问题就抛出来了,那我们要怎么解决呢????

SpringMVC给出类似于Struts2类型转换器这么一个方法给我们使用:如果我们使用的是继承AbstractCommandController类来进行开发的话,我们就可以重写initBinder()方法了….

具体的实现是这样子的:

    @Override    protected void initBinder(HttpServletRequest request,ServletRequestDataBinder binder) throws Exception {        binder.registerCustomEditor(Date.class,new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"),true));    }

那我们现在用的是注解的方式来进行开发,是没有重写方法的。因此我们需要用到的是一个注解,表明我要重写该方法

    @InitBinder    protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws Exception {        binder.registerCustomEditor(                Date.class,                new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), true));    }

再次访问:

这里写图片描述

值得注意的是:如果我们使用的是Oracle插入时间的话,那么我们在SQL语句就要写TimeStrap时间戳插入进去,否则就行不通


结果重定向和转发

我们一般做开发的时候,经常编辑完数据就返回到显示列表中。我们在Struts2是使用配置文件进行重定向或转发的:

这里写图片描述

而我们的SpringMVC就非常简单了,只要在跳转前写上关键字就行了!

    public String hello(Model model, User user) throws Exception {        System.out.println(user.getUsername() + "的出生日期是:" + user.getDate());        model.addAttribute("message", user.getDate());        return "redirect:/index.jsp";    }

这里写图片描述

以此类推,如果是想要再次请求的话,那么我们只要写上对应的请求路径就行了!

    @RequestMapping(value = "/hello.action")    public String hello(Model model, User user) throws Exception {        return "redirect:/bye.action";    }    @RequestMapping("/bye.action")    public String bye() throws Exception {        System.out.println("我进来了bye方法");        return "/index.jsp";    }

这里写图片描述


返回JSON文本

回顾一下Struts2返回JSON文本是怎么操作的:

  • 导入jar包
  • 要返回JSON文本的对象给出get方法
  • 在配置文件中继承json-default包
  • result标签的返回值类型是json

那么我们在SpringMVC又怎么操作呢???

导入两个JSON开发包

  • jackson-core-asl-1.9.11.jar
  • jackson-mapper-asl-1.9.11.jar

在要返回JSON的业务方法上给上注解:

    @RequestMapping(value = "/hello.action")    public    @ResponseBody    User hello() throws Exception {        User user = new User("1", "zhongfucheng");        return user;    }

配置JSON适配器

        <!--              1)导入jackson-core-asl-1.9.11.jar和jackson-mapper-asl-1.9.11.jar            2)在业务方法的返回值和权限之间使用@ResponseBody注解表示返回值对象需要转成JSON文本            3)在spring.xml配置文件中编写如下代码:            <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">                <property name="messageConverters">                        <list>                            <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"/>                        </list>                </property>            </bean>        -->

测试的JSP

    <input type="button" value="Emp转JSON"/><p>    <input type="button" value="List<Emp>转JSON"/><p>    <input type="button" value="Map<String,Object>转JSON"/><p>    <!-- Map<String,Object>转JSON -->    <script type="text/javascript">        $(":button:first").click(function(){            var url = "${pageContext.request.contextPath}/hello.action";            var sendData = null;            $.post(url,sendData,function(backData,textStaut,ajax){                alert(ajax.responseText);            });        });    </script>

测试:

这里写图片描述

Map测试:

    @RequestMapping(value = "/hello.action")    public    @ResponseBody    Map hello() throws Exception {        Map map = new HashMap();        User user = new User("1", "zhongfucheng");        User user2 = new User("12", "zhongfucheng2");        map.put("total", user);        map.put("rows", user2);        return map;    }

这里写图片描述

更新——————————————————————

如果传递进来的数据就是JSON格式的话,我们我们需要使用到另外一个注解@RequestBody,将请求的json数据转成java对象

这里写图片描述

这里写图片描述


原创粉丝点击