springMVC做一个简单的MVC应用

MVC大家都比较熟悉,M(model层,控制业务逻辑和数据逻辑),V(View层,为视图层,负责页面的显示,例如html,jsp等),C(控制层,在这里可以接收前端传过来的数据,调用后台逻辑,将数据共享到作用域中,页面跳转等,这种分层开发很容易使各个模块解耦合,容易管理和维护,各层使用什么技术都不会影响到模型中的其它层次,本文主要阐述一下用springMVC来体现这种开发模式的特点,下面是一个简单的CRUD(增删改查)的例子。
在这里我的Model层包括一个用户的DAO,以及它的实现类,当然还有一个用户实体类。
DAO:

package com.ev.userdao;

import java.util.List;

import com.ev.entities.User;

public interface Dao {
    //获取所有用户信息
    public List getAll();
    //通过id获取一个用户信息
    public User getUserById(int id);
    //新增一个用户
    public void save(User user);
    //删除一个用户
    public void delete(int id);
    //修改一个用户信息
    public void update(User user);
}

它的实现类为:

package com.ev.userdaoimp;

import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Component;

import com.ev.entities.User;
import com.ev.userdao.Dao;
@Component
public class UserDaoImp implements Dao{

    static List<User> list = new ArrayList<User>();
    static{
        list.add(new User(1,"YKG","[email protected]","man"));
        list.add(new User(2,"XLW","[email protected]","man"));     
        list.add(new User(3,"PH","[email protected]","man"));
        list.add(new User(4,"LDM","[email protected]","female"));
        list.add(new User(5,"ZXB","[email protected]","man"));

    }
    @Override
    public List<User> getAll() {        
        return list;
    }

    @Override
    public User getUserById(int id) {
        for(int i=0;i<list.size();i++){
            if(list.get(i).getId() == id){
                return list.get(i);
            }
        }
        return null;
    }

    @Override
    public void save(User user) {
        int newId = 1;
        for(int i=0;i<list.size();i++){
            int curId = list.get(i).getId();
            if(curId>=newId){
                newId = curId;
            }
        }
        newId++;
        user.setId(newId);
        list.add(user);     
    }

    @Override
    public void delete(int id) {
        for(int i=0;i<list.size();i++){
            if(list.get(i).getId() == id){
                list.remove(i);
                break;
            }
        }               
    }

    @Override
    public void update(User user) {
        User oldUserData = getUserById(user.getId());
        oldUserData.setEmail(user.getEmail());
        oldUserData.setSex(user.getSex());
        oldUserData.setUsername(user.getUsername());
    }
    public static void main(String[] args){
        UserDaoImp test = new UserDaoImp();
        test.update(new User(1,"YKG","[email protected]","man"));
        System.out.println(test.getAll());

    }
}


以上就是这个应用的model层,在这里我就不去连接数据库了,用下面的方式来模拟数据库

//模拟一个数据库
static List<User> list = new ArrayList<User>();
static{
    list.add(new User(1,"YKG","[email protected]","man"));
    list.add(new User(2,"XLW","[email protected]","man"));     
    list.add(new User(3,"PH","[email protected]","man"));
    list.add(new User(4,"LDM","[email protected]","female"));
    list.add(new User(5,"ZXB","[email protected]","man"));

}

然后在配置View层时,我们一开始就要进入到一个index.jsp主页,如图:
这里写图片描述
点击“查看用户信息”链接,跳转到success.jsp页面显示所有用户信息如图 :
这里写图片描述
index.jsp页面内容如下

    <h1>欢迎!</h1>
    <div style="text-align:center;">
        <a href="/springcrud/spring/getall">查看用户信息</a>
    </div>

其中/springcrud/spring/getall是请求url,后面会讲到如何在Controller层映射这个请求url
success.jsp内容如下 :

<table cellpadding="3" cellspacing="0" border bordercolor="#000">
        <thead><th>用户名</th><th>邮箱</th><th>性别</th><th>编辑</th><th>操作</th></thead>
        <tbody>
            <c:if test="${empty requestScope.userlist}">
                <tr><td colspan="5" style="text-align:center;">无数据!</td></tr>
            </c:if>
            <c:if test="${!empty requestScope.userlist}">
                <c:forEach items="${requestScope.userlist }" var="item">
                    <tr>
                        <td>${item.username}</td>
                        <td>${item.email}</td>
                        <td>${item.sex}</td>
                        <td><a style="font-size:16px;color:#f60;" href="/springcrud/spring/update/${item.id}">修改</a></td>
                        <td><a style="font-size:16px;color:#f60;" href="/springcrud/spring/deletebyid/${item.id}">删除</a></td>
                    </tr>
                </c:forEach>
            </c:if>
        </tbody>
    </table>
    <div>
        <a href="/springcrud/spring/input">添加用户信息</a>
    </div>

在这里我使用了JSTL以及EL表达式。
其中/springcrud/spring/input是用于跳转到输入页面的请求url input.jsp
这里写图片描述
内容为:

<div style="width:300px;margin:30px auto;">
        <f:form action="/springcrud/spring/save" method="post" modelAttribute="myForm">
            用户名:<f:input path="username"/><br>
            邮箱:<f:input path="email"/><br>
            性别:<f:input path="sex"/><br>            
            <input style="margin:10px auto;width:50px;display:block;" type="submit" value="保存"/>
        </f:form>
    </div>

在这个页面我使用了springMVC中的表单标签,目的是在修改用户信息时方便信息的回显。input标签的path属性相当于普通html表单标签的name属性。
form标签 的 modelAttribute属性用于将作用域中的bean各个属性值填到表单中相对应的字段,这就是回显操作,这一步是必须的,否则就会报错。
最后再用springMVC配置一下Controller层。
控制器类的JAVA代码如下:

package com.ev.controller;

import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import com.ev.entities.User;
import com.ev.userdaoimp.UserDaoImp;

@Controller
@RequestMapping(path="/spring")
public class ReqestHandler {
    private static String SUCCESS = "success";
    private static String INPUT = "input";
    @Autowired
    private UserDaoImp daoImp;
    @RequestMapping(path="/getall")
    public String getAllUser(Map<String,Object> map){
        map.put("userlist",daoImp.getAll());
        return  SUCCESS;
    }
    @RequestMapping(path="/deletebyid/{id}")
    public String deleteEleById(@PathVariable("id") int id){
        System.out.println(id);
        daoImp.delete(id);
        return "redirect:/spring/getall";
    }
    @RequestMapping(path="/update/{id}")
    public String update(@PathVariable("id") int id,Map<String,Object> map){
        map.put("myForm",daoImp.getUserById(id));
        return INPUT;
    }

    @RequestMapping(path="/save")
    public String save(User user){
        System.out.println(user);
        daoImp.save(user);
        return "redirect:/spring/getall";       
    }

    @RequestMapping(path="/input")
    public String savePage(Map<String,Object> map){
        map.put("myForm", new User());
        return INPUT;
    }

}

控制器类ReqestHandler对应有增删改查操作使用@RequestMapping注解来映射url请求,@PathVariable注解是以REST风格来获取表单中的参数,每个处理方法可传入一个Map类型对象,用于将数据共享到作用域中,处理方法中的返回值,可用视图解析器把它解析成物理视图,当返回值中有redirect:开头时,就表示页面的跳转,例如以save处理方法为例,当保存完一个用户信息后,就要跳转到显示用户列表页面,返回值就为redirect:/spring/getall
这个例子虽然很简单,但它体现了MVC设计思想,这就是MVC!

猜你喜欢

转载自blog.csdn.net/yangkaige111/article/details/80711485
今日推荐