Springmvc中,web层与前端数据绑定学习(一)

         刚学完ssm,打算搞一个自己的框架,各种封装,说不定以后用的上,然而由于初学,基础不扎实,对springMVC的数据绑定不熟悉,所以吃了很多苦头啊!所以利用这篇文章来记录一下自己所用到的springmvc的数据绑定,当然是数据绑定有很多种方法,这里给出的这两种足以应对实际开发的各种情况了。


第一种:使用Model来向前端传数据。流程是这样的:当我们获取到前端的请求的时候,web层会调用Service层来处理,Service层会根据相应的信息到Dao层去查询数据,Service层将查询到数据返回给Web层,至此Web层将该数据传到前端来显示。

这里只给出Web层的写法,Service层和Dao层就不给出了,这些需要自己去体会怎么写。

Web层(即Controller层)写法:

    @RequestMapping("/content")
    public String showcontent(Model model){
        int id=1;
        UserEntity user=queryservice.getByid(id);
        System.out.println(user);
        model.addAttribute("user",user.getUsername());//这里将数据以key-value的形式传给前端
        return "content";
    }

Content.jsp页面:${user}:即是web层传过去的数据,“user”为key的名字

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>显示内容</title>
</head>
<body>

<h1>这是根据springmvc拦截请求,然后service层处理,去dao层查询数据,然后返回给web层,所显示的结果:</h1>${user}

</body>
</html>



第二种:获取表单穿来的信息。当用户提交表单请求的时候,将数据绑定到一个bean(Entity)实体中,日后直接调用这个实体类,便可获取到表单穿来的相应的信息(好处:一次性大批量获取)

Web层(即Controller层)写法:@ModelAttribute注解可以很方便的将表单穿来的数据保存到实体中(这里的实体类是UserEntity),如果获取数据不为空,则用model将数据传到成功页面来显示。

    @RequestMapping(value = "/login",method = {RequestMethod.POST})
    public String login(HttpServletRequest request, Model model,@ModelAttribute("userEntity")UserEntity userEntity){
        if(userEntity!=null){
            System.out.print(userEntity.getUsername()+"  "+userEntity.getPassword());
            model.addAttribute("userEntity",userEntity);
            return "loginsuccess";
        }
        return "login";
    }


login.jsp:这里使用springmvc的表单标签,利用它的modelAttribute属性获取数据

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<html>
<head>
    <title>登录页面</title>
</head>
<body>

<h1>这是登录</h1>

<div align="center">
    <form:form modelAttribute="userEntity" method="POST">
    用户名:<form:input path="username"/><br>
    密码:<form:password path="password"/><br>
    <input type="submit" value="提交" />     <input type="reset" value="取消" />
    </form:form>
</div>

</body>
</html>

loginsuccess.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>登录成功</title>
</head>
<body>
<h1>用户名:${userEntity.username}</h1>
<h1>密码:${userEntity.password}</h1>
</body>
</html>

这样便可以实现数据绑定与传输


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章