java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > SSM中entity mapper dao service controller层

SSM框架中entity mapper dao service controller层的使用

作者:劳心

这篇文章主要介绍了SSM框架中entity mapper dao service controller层的使用方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教

1、entity:实体层

用户实现对数据库表的映射

package com.fq.entity;
 
import java.io.Serializable;
 
public class User implements Serializable {
    private static final long serialVersionUID = 1;
 
    private int uid;
    private String username;//uname
    private String upassword;
    private String usex;
    private String ustatus;
    private String code;
    private String email;
    private int urole;//角色
 
    public String getUsername() {
        return username;
    }
 
    public int getUid() {
        return uid;
    }
 
    public void setUid(int uid) {
        this.uid = uid;
    }
 
    public String getUpassword() {
        return upassword;
    }
 
    public void setUpassword(String upassword) {
        this.upassword = upassword;
    }
 
    public String getUsex() {
        return usex;
    }
 
    public void setUsex(String usex) {
        this.usex = usex;
    }
 
    public String getUstatus() {
        return ustatus;
    }
 
    public void setUstatus(String ustatus) {
        this.ustatus = ustatus;
    }
 
    public int getUrole() {
        return urole;
    }
 
    public void setUrole(int urole) {
        this.urole = urole;
    }
 
    public String getCode() {
        return code;
    }
 
    public String getEmail() {
        return email;
    }
 
    public void setUsername(String username) {
        this.username = username;
    }
 
    public void setCode(String code) {
        this.code = code;
    }
 
    public void setEmail(String email) {
        this.email = email;
    }
 
    @Override
    public String toString() {
        return "User{" +
                "uid=" + uid +
                ", username='" + username + '\'' +
                ", upassword='" + upassword + '\'' +
                ", usex='" + usex + '\'' +
                ", ustatus='" + ustatus + '\'' +
                ", code='" + code + '\'' +
                ", email='" + email + '\'' +
                ", urole=" + urole +
                '}';
    }
}

2、dao:数据访问对象层

对数据库的增删改查,因为有entity层,dao层实际上就是对entity进行各种操作,但这里的增删改查相对来说与业务模型是分离的(但也只是相对来说,因为一切Dao层的操作本职上还是为了业务),所以Dao层实际上是提供更上层(service层)基础的增删改查方法的,dao是data access object,即数据访问对象。

数据可能保存到各种数据库,或者各种文件,或者内存。dao层隐藏了这种实现细节,更换数据库或者文件或者内存,对调用dao的更高层来说不受影响。

mapper和dao不同,mapper的目的是为了把关系数据库映射成java类(对象)。

因此,如果只有mapper没有dao层,那么一旦项目需要把数据保存到文件或者内存,那么调用mapper的高层就会受到影响。

一般的项目可能只会使用数据库作为数据存储,所以mapper和dao可以说上就是一个东西了。

2.1 例如:dao

package com.fq.dao;
 
import com.fq.entity.User;
import org.apache.ibatis.jdbc.SQL;
 
import java.sql.SQLException;
 
/*用户模块数据库访问接口*/
public interface UserDao {
    User selectUserByUname(String username) throws SQLException;
 
    int insertUser(User user) throws SQLException;
 
    User selectUserByCode(String code)throws SQLException;
 
    int updateStatusByUid(int uid)throws SQLException;
 
}

impl

package com.fq.dao.impl;
 
import com.fq.dao.UserDao;
import com.fq.entity.User;
import com.fq.utils.C3P0Utils;
import com.fq.utils.Constants;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
 
import javax.jws.soap.SOAPBinding;
import java.sql.SQLException;
/*用户模块数据库访问实现类*/
public class UserDaoImpl implements UserDao {
    @Override
    public User selectUserByUname(String username) throws SQLException {
        QueryRunner queryRunner = new QueryRunner(C3P0Utils.getDataSource());
        String sql = "select u_id as uid , u_name as username , u_password as upassword , u_sex as usex , u_status as ustatus , u_code as code , u_email as email , u_role as urole from user where u_name = ?";
        User user = queryRunner.query(sql,new BeanHandler<User>(User.class),username);
        return user;
    }
 
    @Override
    public int insertUser(User user) throws SQLException {
        QueryRunner queryRunner = new QueryRunner(C3P0Utils.getDataSource());
        String sql = "insert into user (u_name,u_password,u_sex,u_status,u_code,u_email,u_role) value (?,?,?,?,?,?,?)";
        int rows = queryRunner.update(sql,user.getUsername(),user.getUpassword(),user.getUsex(),user.getUstatus(),user.getCode(),user.getEmail(),user.getUrole());
        return rows;
    }
 
    @Override
    public User selectUserByCode(String code) throws SQLException {
        QueryRunner queryRunner = new QueryRunner(C3P0Utils.getDataSource());
        String sql = "select u_id as uid , u_name as username , u_password as upassword , u_sex as usex , u_status as ustatus , u_code as code , u_email as email , u_role as urole from user where u_code = ?";
        User user = queryRunner.query(sql,new BeanHandler<User>(User.class),code);
 
        return user;
    }
 
    @Override
    public int updateStatusByUid(int uid) throws SQLException {
        QueryRunner queryRunner = new QueryRunner(C3P0Utils.getDataSource());
        String sql = "update user set u_status = ? where u_id = ?";
        int row  = queryRunner.update(sql, Constants.USER_ACTIVE,uid);
 
        return row;
    }
}

2.2 例如:

public interface QuestionDao {
 
    int save(Question question);
 
    int delete(Question question);
 
    int update(Question question);
 
    Question findById(String id);
 
    List<Question> findAll();
}

mapper

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.itheima.dao.store.QuestionDao">
    <!--配置实体类属性和数据库表中列的对应关系-->
    <resultMap id="BaseResultMap" type="com.itheima.domain.store.Question">
        <id column="id" jdbcType="VARCHAR" property="id"/>
        <result column="company_id" jdbcType="VARCHAR" property="companyId"/>
        <result column="catalog_id" jdbcType="VARCHAR" property="catalogId"/>
        <result column="remark" jdbcType="VARCHAR" property="remark"/>
        <result column="subject" jdbcType="VARCHAR" property="subject"/>
        <result column="analysis" jdbcType="VARCHAR" property="analysis"/>
        <result column="type" jdbcType="VARCHAR" property="type"/>
        <result column="difficulty" jdbcType="VARCHAR" property="difficulty"/>
        <result column="is_classic" jdbcType="VARCHAR" property="isClassic"/>
        <result column="state" jdbcType="VARCHAR" property="state"/>
        <result column="review_status" jdbcType="VARCHAR" property="reviewStatus"/>
        <result column="create_time" jdbcType="TIMESTAMP" property="createTime"/>
        <result column="picture" jdbcType="VARCHAR" property="picture"/>
 
        <association
            property="company"
            column="company_id"
            javaType="com.itheima.domain.store.Course"
            select="com.itheima.dao.store.CompanyDao.findById"/>
 
        <association
            property="catalog"
            column="catalog_id"
            javaType="com.itheima.domain.store.Course"
            select="com.itheima.dao.store.CatalogDao.findById"
            />
 
    </resultMap>
 
    <!--配置查询的列名公共SQL语句-->
    <sql id="Base_Column_List">
        id, catalog_id, company_id, remark,subject,analysis,type, difficulty, is_classic,
        state, review_status, create_time, picture
    </sql>
 
    <!--配置查询所有,带条件-->
    <select id="findAll" resultMap="BaseResultMap">
        select
        <include refid="Base_Column_List"/>
        from st_question
        order by create_time desc
    </select>
 
    <!--配置根据ID查询-->
    <select id="findById" parameterType="java.lang.String" resultMap="BaseResultMap">
        select
        <include refid="Base_Column_List"/>
        from st_question
        where id = #{id,jdbcType=VARCHAR}
    </select>
 
    <!--配置根据id删除-->
    <delete id="delete" parameterType="java.lang.String">
        delete from st_question where id = #{id,jdbcType=VARCHAR}
    </delete>
 
    <!--配置全字段插入,当某个字段没有值时,插入null-->
    <insert id="save" parameterType="com.itheima.domain.store.Question">
        insert into st_question(id, company_id, catalog_id, remark, subject, analysis, type,
                difficulty, is_classic, state, review_status, create_time ,picture )
            values (#{id,jdbcType=VARCHAR}, #{companyId,jdbcType=VARCHAR}, #{catalogId,jdbcType=VARCHAR},
                #{remark,jdbcType=VARCHAR}, #{subject,jdbcType=VARCHAR}, #{analysis,jdbcType=VARCHAR},
                #{type,jdbcType=VARCHAR}, #{difficulty,jdbcType=VARCHAR}, #{isClassic,jdbcType=VARCHAR},
                #{state,jdbcType=VARCHAR}, #{reviewStatus,jdbcType=VARCHAR}, #{createTime,jdbcType=TIMESTAMP},
                #{picture,jdbcType=VARCHAR} )
    </insert>
 
    <!--配置全字段更新,当提供的数据为null时,数据库数据会被更新为null-->
    <update id="update" parameterType="com.itheima.domain.store.Question">
        update
            st_question
        set
            company_id = #{companyId,jdbcType=VARCHAR},
            catalog_id = #{catalogId,jdbcType=VARCHAR},
            remark = #{remark,jdbcType=VARCHAR},
            subject = #{subject,jdbcType=VARCHAR},
            analysis = #{analysis,jdbcType=VARCHAR},
            difficulty = #{difficulty,jdbcType=VARCHAR},
            is_classic = #{isClassic,jdbcType=VARCHAR},
            picture = #{picture,jdbcType=VARCHAR},
            state = #{state,jdbcType=VARCHAR}
        where
            id = #{id,jdbcType=VARCHAR}
    </update>
 
</mapper>

3、service层:业务逻辑层

这层主要实现业务真正的逻辑

例如:

package com.fq.service;
 
import com.fq.entity.User;
 
import java.sql.SQLException;
/*用户模块对应的接口*/
public interface UserService {
    /*检测用户名是否存在*/
    boolean checkedUser(String username) throws SQLException;
    /*注册新用户*/
    int registerUser(User user) throws SQLException;
    /*激活用户*/
    int activeUser(String code) throws SQLException;
    /*登录*/
    User login(String username,String password) throws SQLException;
}

impl

package com.fq.service.impl;
 
import com.fq.dao.UserDao;
import com.fq.dao.impl.UserDaoImpl;
import com.fq.entity.User;
import com.fq.service.UserService;
import com.fq.utils.Constants;
import com.fq.utils.MD5Utils;
 
import java.sql.SQLException;
/*用户模块接口实现类*/
public class UserServiceImpl implements UserService {
    @Override
    public boolean checkedUser(String username) throws SQLException {
        UserDao userDao = new UserDaoImpl();
        User user = userDao.selectUserByUname(username);
        if (user != null){
            return true;
        }
 
        return false;
    }
 
    @Override
    public int registerUser(User user) throws SQLException {
        UserDao userDao = new UserDaoImpl();
        int row = userDao.insertUser(user);
        //发邮件
//        EmailUtils.sendEmail(user);
        return 0;
    }
 
    @Override
    public int activeUser(String code) throws SQLException {
        UserDao userDao = new UserDaoImpl();
        User user = userDao.selectUserByCode(code);
        if (user == null){
            return Constants.ACTIVE_FAIL;//激活失败
        }
        if (user.getUstatus().equals(Constants.USER_ACTIVE)){
            return Constants.ACTIVE_ALREADY;//判断是否激活
        }
        int i = userDao.updateStatusByUid(user.getUid());
        if (i>0){
            return Constants.ACTIVE_SUCCESS;
 
        }
        return Constants.ACTIVE_FAIL;
    }
 
    @Override
    public User login(String username, String password) throws SQLException {
        String md5password = MD5Utils.md5(password);
        UserDao userDao = new UserDaoImpl();
        User user = userDao.selectUserByUname(username);
        if (user != null && user.getUpassword().equals(md5password)){
            return user;
        }
 
        return null;
    }
}

4、controller层:控制层

实现请求和相应的控制。

package com.fq.controller;
 
import com.fq.entity.User;
import com.fq.service.UserService;
import com.fq.service.impl.UserServiceImpl;
import com.fq.utils.Base64Utils;
import com.fq.utils.Constants;
import com.fq.utils.MD5Utils;
import com.fq.utils.RandomUtils;
import org.apache.commons.beanutils.BeanUtils;
 
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.SQLException;
import java.util.Map;
 
@WebServlet("/user")
public class UserController extends BaseSevlet {
 
    public String check(HttpServletRequest request,HttpServletResponse response) throws SQLException {
        String username = request.getParameter("username");//获取参数
        if (username == null){
            return Constants.HAS_USER;//判空,不能注册
        }
        //判断用户名是否存在
        UserService userService = new UserServiceImpl();
        boolean b = userService.checkedUser(username);
        if (b){
            return Constants.HAS_USER;
        }
        return Constants.NOT_HAS_USER;
    }
    public String register(HttpServletRequest request, HttpServletResponse response){
        //1.获取用户信息
        Map<String, String[]> parameterMap = request.getParameterMap();
        User user = new User();
        try {
            BeanUtils.populate(user,parameterMap);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
 
        //2.完善用户信息
        //已经赋值: 用户名 密码 邮箱 性别
        //没有赋值: 激活状态 账号类型 激活码
        user.setUstatus(Constants.USER_NOT_ACTIVE); //未激活状态 0 激活 1
        user.setUrole(Constants.ROLE_CUSTOMER); //普通客户0  管理员1
        user.setCode(RandomUtils.createActive());
 
        //需要处理的属性:密码 md5进行加密处理
        user.setUpassword(MD5Utils.md5(user.getUpassword()));
 
        //3.调用用户的业务逻辑进行注册
        UserService userService = new UserServiceImpl();
        try {
            userService.registerUser(user);
        } catch (SQLException e) {
            e.printStackTrace();
 
            request.setAttribute("registerMsg","注册失败!");
 
            return Constants.FORWARD+"/register.jsp";
        }
 
        //4.响应
        return Constants.FORWARD + "/registerSuccess.jsp";
    }
 
    /**
     * 激活方法!
     * @param request
     * @param response
     * @return
     */
    public String active(HttpServletRequest request,HttpServletResponse response) throws SQLException {
        //1.获取激活码
        //已经转成base64
        String c = request.getParameter("c");
        //base64翻转
        String code = Base64Utils.decode(c);
        //2.调用激活的业务逻辑
        UserService userService = new UserServiceImpl();
        int i = userService.activeUser(code);
 
        //3.响应(激活失败(code没有找到) 已经激活 激活成功)
        if (i == Constants.ACTIVE_FAIL){
            request.setAttribute("msg","未激活成功!");
        }else if(i==Constants.ACTIVE_SUCCESS){
            request.setAttribute("msg","激活成功,请登录!");
        }else{
            request.setAttribute("msg","已经激活");
        }
 
        return Constants.FORWARD+"/message.jsp";
    }
 
    /**
     * 1.前端提交账号密码和验证码
     * 2.对比验证码 成功 ---》 对比账号密码
     * 3.对比账号密码
     *   失败: --》 回到登录页面 进行提示
     *   成功: --》 未激活  登录页面 进行提示
     *         --》 已激活  程序的首页  将用户放入session共享域
     */
    public String login(HttpServletRequest request,HttpServletResponse response) throws SQLException {
 
 
        //1.获取请求参数(用户名,密码,验证码)
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String code  = request.getParameter("code");//用户输入的验证码
        String auto = request.getParameter("auto"); //自动登录标识
 
        //正确的验证码
        HttpSession session = request.getSession();
        String codestr = (String) session.getAttribute("code");
 
        //2.判断验证码是否正确
 
        if (code == null || !code.equalsIgnoreCase(codestr)){
            request.setAttribute("msg","验证码错误");
            return Constants.FORWARD + "/login.jsp";
        }
        //3.调用业务逻辑判断账号密码
 
        UserService userService = new UserServiceImpl();
        User user = userService.login(username, password);
 
        //4.响应
        //user 等于null证明账号或者密码错误
        //user 不为null 但是user的状态是未激活状态
 
        if (user == null) {
            request.setAttribute("msg","账号或者密码错误");
            return Constants.FORWARD +"/login.jsp";
        }
 
        if (user.getUstatus().equals(Constants.USER_NOT_ACTIVE))
        {
            request.setAttribute("msg","账号未激活!");
            return Constants.FORWARD +"/login.jsp";
        }
 
        session.setAttribute("loginUser",user);
 
        //autoUser
        //判断是否勾选自动登录
        if (auto == null){
            //没有勾选!
            //将本地浏览器的存储的cookie'清空'
            Cookie cookie = new Cookie(Constants.AUTO_NAME,"");
            cookie.setPath("/");
            cookie.setMaxAge(0);
            response.addCookie(cookie);
        }else{
            //自定登录数据库存储 2周
            String content = username+Constants.FLAG+password;
            content = Base64Utils.encode(content);
            Cookie cookie = new Cookie(Constants.AUTO_NAME,content);
            cookie.setPath("/");
            cookie.setMaxAge(14*24*60*60);
            response.addCookie(cookie);
        }
 
 
        return Constants.REDIRECT + "/index.jsp";
    }
 
    /**
     * 注销登录!清空数据!跳转到登录页面
     * @param request
     * @param response
     * @return
     */
    public String logOut(HttpServletRequest request,HttpServletResponse response){
 
        //1.清空session中的用户数据
        HttpSession session = request.getSession();
        session.removeAttribute("loginUser");
 
        //2.清空和覆盖cookie存储的自动登录信息
 
        Cookie cookie = new Cookie(Constants.AUTO_NAME,"");
        cookie.setPath("/");
        cookie.setMaxAge(0);
        response.addCookie(cookie);
        //3.转发到登录页面
        request.setAttribute("msg","注销登录成功!");
        return  Constants.FORWARD + "/login.jsp";
    }
 
 
}

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

您可能感兴趣的文章:
阅读全文