亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

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

 更新時(shí)間:2023年11月03日 16:43:51   作者:勞心  
這篇文章主要介紹了SSM框架中entity mapper dao service controller層的使用方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教

1、entity:實(shí)體層

用戶(hù)實(shí)現(xiàn)對(duì)數(shù)據(jù)庫(kù)表的映射

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:數(shù)據(jù)訪(fǎng)問(wèn)對(duì)象層

對(duì)數(shù)據(jù)庫(kù)的增刪改查,因?yàn)橛衑ntity層,dao層實(shí)際上就是對(duì)entity進(jìn)行各種操作,但這里的增刪改查相對(duì)來(lái)說(shuō)與業(yè)務(wù)模型是分離的(但也只是相對(duì)來(lái)說(shuō),因?yàn)橐磺蠨ao層的操作本職上還是為了業(yè)務(wù)),所以Dao層實(shí)際上是提供更上層(service層)基礎(chǔ)的增刪改查方法的,dao是data access object,即數(shù)據(jù)訪(fǎng)問(wèn)對(duì)象。

數(shù)據(jù)可能保存到各種數(shù)據(jù)庫(kù),或者各種文件,或者內(nèi)存。dao層隱藏了這種實(shí)現(xiàn)細(xì)節(jié),更換數(shù)據(jù)庫(kù)或者文件或者內(nèi)存,對(duì)調(diào)用dao的更高層來(lái)說(shuō)不受影響。

mapper和dao不同,mapper的目的是為了把關(guān)系數(shù)據(jù)庫(kù)映射成java類(lèi)(對(duì)象)。

因此,如果只有mapper沒(méi)有dao層,那么一旦項(xiàng)目需要把數(shù)據(jù)保存到文件或者內(nèi)存,那么調(diào)用mapper的高層就會(huì)受到影響。

一般的項(xiàng)目可能只會(huì)使用數(shù)據(jù)庫(kù)作為數(shù)據(jù)存儲(chǔ),所以mapper和dao可以說(shuō)上就是一個(gè)東西了。

2.1 例如:dao

package com.fq.dao;
 
import com.fq.entity.User;
import org.apache.ibatis.jdbc.SQL;
 
import java.sql.SQLException;
 
/*用戶(hù)模塊數(shù)據(jù)庫(kù)訪(fǎng)問(wèn)接口*/
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;
/*用戶(hù)模塊數(shù)據(jù)庫(kù)訪(fǎng)問(wèn)實(shí)現(xiàn)類(lèi)*/
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">
    <!--配置實(shí)體類(lèi)屬性和數(shù)據(jù)庫(kù)表中列的對(duì)應(yīng)關(guān)系-->
    <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>
 
    <!--配置查詢(xún)的列名公共SQL語(yǔ)句-->
    <sql id="Base_Column_List">
        id, catalog_id, company_id, remark,subject,analysis,type, difficulty, is_classic,
        state, review_status, create_time, picture
    </sql>
 
    <!--配置查詢(xún)所有,帶條件-->
    <select id="findAll" resultMap="BaseResultMap">
        select
        <include refid="Base_Column_List"/>
        from st_question
        order by create_time desc
    </select>
 
    <!--配置根據(jù)ID查詢(xún)-->
    <select id="findById" parameterType="java.lang.String" resultMap="BaseResultMap">
        select
        <include refid="Base_Column_List"/>
        from st_question
        where id = #{id,jdbcType=VARCHAR}
    </select>
 
    <!--配置根據(jù)id刪除-->
    <delete id="delete" parameterType="java.lang.String">
        delete from st_question where id = #{id,jdbcType=VARCHAR}
    </delete>
 
    <!--配置全字段插入,當(dāng)某個(gè)字段沒(méi)有值時(shí),插入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>
 
    <!--配置全字段更新,當(dāng)提供的數(shù)據(jù)為null時(shí),數(shù)據(jù)庫(kù)數(shù)據(jù)會(huì)被更新為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層:業(yè)務(wù)邏輯層

這層主要實(shí)現(xiàn)業(yè)務(wù)真正的邏輯

例如:

package com.fq.service;
 
import com.fq.entity.User;
 
import java.sql.SQLException;
/*用戶(hù)模塊對(duì)應(yīng)的接口*/
public interface UserService {
    /*檢測(cè)用戶(hù)名是否存在*/
    boolean checkedUser(String username) throws SQLException;
    /*注冊(cè)新用戶(hù)*/
    int registerUser(User user) throws SQLException;
    /*激活用戶(hù)*/
    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;
/*用戶(hù)模塊接口實(shí)現(xiàn)類(lèi)*/
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);
        //發(fā)郵件
//        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層:控制層

實(shí)現(xiàn)請(qǐng)求和相應(yīng)的控制。

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");//獲取參數(shù)
        if (username == null){
            return Constants.HAS_USER;//判空,不能注冊(cè)
        }
        //判斷用戶(hù)名是否存在
        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.獲取用戶(hù)信息
        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.完善用戶(hù)信息
        //已經(jīng)賦值: 用戶(hù)名 密碼 郵箱 性別
        //沒(méi)有賦值: 激活狀態(tài) 賬號(hào)類(lèi)型 激活碼
        user.setUstatus(Constants.USER_NOT_ACTIVE); //未激活狀態(tài) 0 激活 1
        user.setUrole(Constants.ROLE_CUSTOMER); //普通客戶(hù)0  管理員1
        user.setCode(RandomUtils.createActive());
 
        //需要處理的屬性:密碼 md5進(jìn)行加密處理
        user.setUpassword(MD5Utils.md5(user.getUpassword()));
 
        //3.調(diào)用用戶(hù)的業(yè)務(wù)邏輯進(jìn)行注冊(cè)
        UserService userService = new UserServiceImpl();
        try {
            userService.registerUser(user);
        } catch (SQLException e) {
            e.printStackTrace();
 
            request.setAttribute("registerMsg","注冊(cè)失?。?);
 
            return Constants.FORWARD+"/register.jsp";
        }
 
        //4.響應(yīng)
        return Constants.FORWARD + "/registerSuccess.jsp";
    }
 
    /**
     * 激活方法!
     * @param request
     * @param response
     * @return
     */
    public String active(HttpServletRequest request,HttpServletResponse response) throws SQLException {
        //1.獲取激活碼
        //已經(jīng)轉(zhuǎn)成base64
        String c = request.getParameter("c");
        //base64翻轉(zhuǎn)
        String code = Base64Utils.decode(c);
        //2.調(diào)用激活的業(yè)務(wù)邏輯
        UserService userService = new UserServiceImpl();
        int i = userService.activeUser(code);
 
        //3.響應(yīng)(激活失敗(code沒(méi)有找到) 已經(jīng)激活 激活成功)
        if (i == Constants.ACTIVE_FAIL){
            request.setAttribute("msg","未激活成功!");
        }else if(i==Constants.ACTIVE_SUCCESS){
            request.setAttribute("msg","激活成功,請(qǐng)登錄!");
        }else{
            request.setAttribute("msg","已經(jīng)激活");
        }
 
        return Constants.FORWARD+"/message.jsp";
    }
 
    /**
     * 1.前端提交賬號(hào)密碼和驗(yàn)證碼
     * 2.對(duì)比驗(yàn)證碼 成功 ---》 對(duì)比賬號(hào)密碼
     * 3.對(duì)比賬號(hào)密碼
     *   失?。?--》 回到登錄頁(yè)面 進(jìn)行提示
     *   成功: --》 未激活  登錄頁(yè)面 進(jìn)行提示
     *         --》 已激活  程序的首頁(yè)  將用戶(hù)放入session共享域
     */
    public String login(HttpServletRequest request,HttpServletResponse response) throws SQLException {
 
 
        //1.獲取請(qǐng)求參數(shù)(用戶(hù)名,密碼,驗(yàn)證碼)
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String code  = request.getParameter("code");//用戶(hù)輸入的驗(yàn)證碼
        String auto = request.getParameter("auto"); //自動(dòng)登錄標(biāo)識(shí)
 
        //正確的驗(yàn)證碼
        HttpSession session = request.getSession();
        String codestr = (String) session.getAttribute("code");
 
        //2.判斷驗(yàn)證碼是否正確
 
        if (code == null || !code.equalsIgnoreCase(codestr)){
            request.setAttribute("msg","驗(yàn)證碼錯(cuò)誤");
            return Constants.FORWARD + "/login.jsp";
        }
        //3.調(diào)用業(yè)務(wù)邏輯判斷賬號(hào)密碼
 
        UserService userService = new UserServiceImpl();
        User user = userService.login(username, password);
 
        //4.響應(yīng)
        //user 等于null證明賬號(hào)或者密碼錯(cuò)誤
        //user 不為null 但是user的狀態(tài)是未激活狀態(tài)
 
        if (user == null) {
            request.setAttribute("msg","賬號(hào)或者密碼錯(cuò)誤");
            return Constants.FORWARD +"/login.jsp";
        }
 
        if (user.getUstatus().equals(Constants.USER_NOT_ACTIVE))
        {
            request.setAttribute("msg","賬號(hào)未激活!");
            return Constants.FORWARD +"/login.jsp";
        }
 
        session.setAttribute("loginUser",user);
 
        //autoUser
        //判斷是否勾選自動(dòng)登錄
        if (auto == null){
            //沒(méi)有勾選!
            //將本地瀏覽器的存儲(chǔ)的cookie'清空'
            Cookie cookie = new Cookie(Constants.AUTO_NAME,"");
            cookie.setPath("/");
            cookie.setMaxAge(0);
            response.addCookie(cookie);
        }else{
            //自定登錄數(shù)據(jù)庫(kù)存儲(chǔ) 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";
    }
 
    /**
     * 注銷(xiāo)登錄!清空數(shù)據(jù)!跳轉(zhuǎn)到登錄頁(yè)面
     * @param request
     * @param response
     * @return
     */
    public String logOut(HttpServletRequest request,HttpServletResponse response){
 
        //1.清空session中的用戶(hù)數(shù)據(jù)
        HttpSession session = request.getSession();
        session.removeAttribute("loginUser");
 
        //2.清空和覆蓋cookie存儲(chǔ)的自動(dòng)登錄信息
 
        Cookie cookie = new Cookie(Constants.AUTO_NAME,"");
        cookie.setPath("/");
        cookie.setMaxAge(0);
        response.addCookie(cookie);
        //3.轉(zhuǎn)發(fā)到登錄頁(yè)面
        request.setAttribute("msg","注銷(xiāo)登錄成功!");
        return  Constants.FORWARD + "/login.jsp";
    }
 
 
}

總結(jié)

以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論