通用文件的设计和编写

(1)

BasePojo.java

package com.wu.entity;

import java.io.Serializable;
import java.util.Date;

public abstract class BasePojo implements Serializable{
	private Date created;
    private Date updated;
    private Integer status;
    
    public Date getCreated() {
        return created;
    }
    public void setCreated(Date created) {
        this.created = created;
    }
    public Date getUpdated() {
        return updated;
    }
    public void setUpdated(Date updated) {
        this.updated = updated;
    }
	public Integer getStatus() {
		return status;
	}
	public void setStatus(Integer status) {
		this.status = status;
	}
}

SysUser.java

package com.wu.entity;

import java.util.Date;

public class SysUser {
    private String id;
	private String organizationId;
	private String name;
	private String employeeNo;
	private Integer locked;
	private String pwd;

	public String getId() {
		return id;
	}

    //为了处理表单和地址栏提交过来的字符串信息,我们必须写成如下形式
	public void setId(String id) {
		this.id = id == null ? null : (id.trim()==""?null:id.trim());
	}
}

(2)

通用文件的设计和编写

BaseMapper.java

package com.wu.mapper.baseMapper;

import java.util.List;


/*Dao层的抽取*/
public interface BaseMapper<T> {
	/*通用方法*/
	//插入一条数据
	int insert(T obj);
	
	//批量刪除
	int delete(String[] ids);
    
	//查詢,mybatis会通过接口文件的返回值类型来判断返回的是集合还是对象。如果是对象,则按常规查询并返回;如果是List集合,mybatis则会将查询到的多条记录设置进集合中并返回。
	List<T> selectPage(T obj);
	
	//总记录数
	int count(T obj);
    
	//部分更新
	int updateByPKSelective(T obj);
    
	//全部更新,除了主键
	int updateByPK(T obj);
	
}

(3)

通用文件的设计和编写

SysUserMapper.java

package com.wu.mapper.sysUserMapper;

import com.wu.entity.SysUser;
import com.wu.mapper.baseMapper.BaseMapper;

public interface SysUserMapper extends BaseMapper<SysUser>{
      /*非通用方法*/
}

SysUserMapper.xml

<?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.wu.mapper.sysUserMapper.SysUserMapper">

  <resultMap id="BaseResultMap" type="sysUser">
    <id column="id" jdbcType="VARCHAR" property="id" />
    <result column="name" jdbcType="VARCHAR" property="name" />
    <result column="organization_id" jdbcType="VARCHAR" property="organizationId" />
    <result column="status" jdbcType="INTEGER" property="status" />
    <result column="created" jdbcType="TIMESTAMP" property="created" />
    <result column="locked" jdbcType="INTEGER" property="locked" />
    <result column="pwd" jdbcType="VARCHAR" property="pwd" />
  </resultMap>
  
  
  
  
  
  
  <sql id="Base_Column_List">
    id, organization_id, employee_no, status, created, locked, pwd
  </sql>


  <sql id="Where_If_Clause">
    <where>
      <if test="id!=null">and id = #{id}</if>
      <if test="name!=null">and name = #{name}</if>
      <if test="organizationId != null">and organization_id = #{organizationId} </if>
      <if test="status != null">and status = #{status}</if>
      <if test="created != null">and created = #{created}</if>
      <if test="locked != null">and locked = #{locked}</if>
    </where>
  </sql>
  
  
  <sql id="Set_If_Clause">
	<set>
		<if test="organizationId != null">organization_id = #{organizationId},</if>
		<if test="name!= null">name = #{name},</if>
		<if test="status != null">status = #{status},</if>
		<if test="created != null">created = #{created},</if>
		<if test="locked != null">locked = #{locked},</if>
		<if test="pwd != null">pwd = #{pwd},</if>
	</set>
  </sql>




  
  <insert id="insert" parameterType="sysUser">
    insert into sys_user (id,organization_id, name, status, created, locked, pwd)
    values (#{id},#{organizationId}, #{name}, #{status}, #{created}, #{locked}, #{pwd})
  </insert>
  
  
  
  
  
  
  
  <!-- 批量刪除-->
  <delete id="delete">
    delete 
    from sys_user
    where id in
    <foreach close=")" collection="list" item="id" open="(" separator=",">
         #{id}
    </foreach>
  </delete>
  
 
  
  
  
  <!-- where_if查詢,如果参数为空,则会查询全部 -->
  <select id="selectPage" parameterType="sysUser" resultMap="BaseResultMap">
    select 
    <include refid="Base_Column_List" />
    from sys_user
    <if test="_parameter!= null" >
        <include refid="Where_If_Clause" />
    </if>
  </select>
  
  
  
  
  <!--总记录数 -->
  <select id="count" parameterType="sysUser" resultType="java.lang.Integer" >
    select count(0) from sys_user
    <if test="_parameter != null" >
         <include refid="Where_If_Clause" />
    </if>
  </select>
  
  
  
  


  <!-- 部分更新 -->
  <update id="updateByPKSelective" parameterType="sysUser">
    update sys_user
    <if test="_parameter != null">
        <include refid="Set_If_Clause"/>
    </if>
    where id = #{id}
  </update>
  
  
  
 <!--  全部更新,除了主键 -->
  <update id="updateByPK" parameterType="sysUser">
    update sys_user
    set organization_id = #{organizationId},
      employee_no = #{employeeNo},
      status = #{status},
      created = #{created},
      locked = #{locked},
      pwd = #{pwd}
    where id = #{id}
  </update>


  
  
</mapper>

 

(4)

通用文件的设计和编写

BaseService.java

package com.wu.service.baseService;

import java.util.List;

//业务层的抽取
public interface BaseService<T> {
	/*通用业务*/
	
	// 插入一条数据
	int insert(T obj) throws Exception;

	//删除
	int delete(String[] ids) throws Exception;

	//查询
	List<T> selectPage(T obj) throws Exception;
	
	int count(T obj) throws Exception; 

	//部分修改
	int updateByPKSelective(T obj) throws Exception;

	//全部修改,除了主键
	int updateByPK(T obj) throws Exception;
}

BaseServiceImpl.java

注意:

1.如果一个类A中有个成员变量p被@Autowired注解,那么@Autowired注入是发生在A的构造方法执行完之后的。

2.如果想在生成对象时候完成某些初始化操作,而偏偏这些初始化操作又依赖于依赖注入,那么就无法在构造函数中实现。为此,可以使用@PostConstruct注解一个方法来完成初始化,@PostConstruct注解的方法将会在依赖注入完成后被自动调用。

3.执行顺序:A的构造方法->依赖注入@Autowired->初始化操作@PostConstruct

package com.wu.service.baseService;

import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.util.List;
import javax.annotation.PostConstruct;
import com.wu.mapper.baseMapper.BaseMapper;

public class BaseServiceImpl<T> implements BaseService<T>{
    
	protected BaseMapper<T> baseMapper;//因为baseMapper为空指针,故需要通过initBaseMapper()方法来让它指向(当前类被继承后的实例的mapper属性所指向的)
	
	@PostConstruct//表示在baseMapper的子mapper依赖注入完成后该初始化方法被自动调用
	private void initBaseMapper() throws Exception{
		//完成以下逻辑,需要对研发本身进行命名与使用规范
		//this关键字指对象本身,这里指的是调用此方法的实现类(子类)
        //获取当前类被继承后的泛型T的类型全名称(即 com.wu.service.baseService.BaseServiceImpl<com.AAA,com.BBB,com.CCC>中的<com.AAA,com.BBB,com.CCC>)
		ParameterizedType baseServiceTypes =(ParameterizedType) this.getClass().getGenericSuperclass();
		//获取第一个参数的class(即com.AAA)
		Class clazz = (Class)baseServiceTypes.getActualTypeArguments()[0];
		//获取clazz的简单类名(即AAA)
		String simpleName = clazz.getSimpleName();
		//转化为业务层实例的属性名(即与AAA相关的Mapper的引用名,事先约定第一个字母为小写,后面接着"Mapper")
		String mapperName = simpleName.substring(0,1).toLowerCase()+simpleName.substring(1)+"Mapper";
		//getDeclaredField:可以使用于包括私有、默认、受保护、公共字段,但不包括继承的字段
		//获取业务层实例的属性字段(即与AAA相关的Mapper的引用)
		Field mapperField = this.getClass().getDeclaredField(mapperName);
		//获取当前类的baseMapper的字段
		Field baseField = this.getClass().getSuperclass().getDeclaredField("baseMapper");
		//通过Field对象的方法:get(Object Field对象的拥有者)获取业务层实例的属性字段的值。例如:User相关的业务层实例中,baseMapper所指向的对象为其子类型UserMapper对象,子类型对象已被spring实例化于容器中。	
		Object springObject = mapperField.get(this);
		//设置baseField所指向的值
		baseField.set(this, springObject);
		System.out.println("——————————baseMapper所指向的、被spring容器实例化的dao层对象:"+springObject.getClass()+"——————————");
	}

	@Override
	public int insert(T obj) throws Exception {
		// TODO Auto-generated method stub
		return baseMapper.insert(obj);
	}

	@Override
	public int delete(String[] ids) throws Exception {
		// TODO Auto-generated method stub
		return baseMapper.delete(ids);
	}

	@Override
	public List<T> selectPage(T obj) throws Exception {
		// TODO Auto-generated method stub
		return baseMapper.select(obj);
	}
	
	@Override
	public int count(T obj) throws Exception {
		// TODO Auto-generated method stub
		return baseMapper.count(obj);
	}

	@Override
	public int updateByPKSelective(T obj) throws Exception {
		// TODO Auto-generated method stub
		return baseMapper.updateByPKSelective(obj);
	}

	@Override
	public int updateByPK(T obj) throws Exception {
		// TODO Auto-generated method stub
		return baseMapper.updateByPK(obj);
	}

	
	
}

(5)

通用文件的设计和编写

SysUserService.java

package com.wu.service.sysUserService;
​​​​​​​
import com.wu.entity.SysUser;
import com.wu.service.baseService.BaseService;

//继承了基础业务接口BaseService的基础接口方法
public interface SysUserService extends BaseService<SysUser>{
    /*非通用的业务方法*/	
}

SysUserServiceImpl.java

package com.wu.service.sysUserService;

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.wu.entity.SysUser;
import com.wu.mapper.sysUserMapper.SysUserMapper;
import com.wu.service.baseService.BaseServiceImpl;


//继承了基础业务实现类BaseServiceImpl的几个基础业务实现方法
//实现了相关业务接口SysUserService的非通用的接口方法
@Service
public class SysUserServiceImpl extends BaseServiceImpl<SysUser> implements SysUserService{
      
	@Autowired  //因为父类无法调用子类的被保护的属性,所以只能将子类的属性的权限设为public
	public SysUserMapper sysUserMapper;

}

(5)控制层的抽取

/src/com/wu/controller/BaseController.java

package com.wu.controller;

import javax.annotation.Resource;
import javax.servlet.ServletContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/baseController")
public class BaseController {
	
	/*日志记录器org.slf4j.Logger*/
	Logger logger = LoggerFactory.getLogger(this.getClass());  
	
	@Resource  //经过@Autowired是无法被继承的,
	ServletContext application;
	
	
	/*访问内部资源:
	 *  目的:可以使用以下方法,以直接通过超链接访问内部资源
	 *  原理:方法参数folder通过@PathVariable指定其值可以从@RequestMapping的{folder}获取,同理file也一样,它们指定请求的资源的地址和文件名
	 */
	@RequestMapping("/inF/{folder}/{file}")
	public String inF(@PathVariable String folder, @PathVariable String file) {
		return "forward:/WEB-INF/" + folder + "/" + file + ".jsp";
	}
	
	@RequestMapping("/inR/{folder}/{file}")
	public String inR(@PathVariable String folder, @PathVariable String file) {
		return "forward:/WEB-INF/" + folder + "/" + file + ".jsp";
	}

        /*访问外部资源:复用*/
	public String outF(@PathVariable String file) {
		return "forward:/" + file + ".jsp";
	}
	
	
	public String outR(@PathVariable String file) {
		return "redirect:/" + file + ".jsp";
	}
	
}

src/com/wu/controller/SysUserController.java

package com.wu.controller;

import java.util.List;
import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.wu.entity.SysUser;
import com.wu.service.sysUserService.SysUserService;


@Controller
@RequestMapping("/sysUserAction")// 为了防止多个控制层类有相同的方法所以要为每个控制层类起个唯一的标示名
public class SysUserController extends BaseController{
     
	@Resource
	SysUserService sysUserService;
	
	@RequestMapping("/checkEmployeeNo")
	public @ResponseBody String checkEmployeeNo(String employeeNo) throws Exception{
		String msg=null;
		//判断登录帐号(工号)是否为空
		if(null!=employeeNo){
			//设置id
			SysUser su = new SysUser();
			su.setEmployeeNo(employeeNo);
			logger.warn("登录帐号:"+employeeNo);
			//调用业务层查询该employee_no是否存在
			if(sysUserService.selectPage(su).isEmpty()){
				msg="该帐号不存在!";
			}else{
				msg="";
			}
		}else{
			msg="帐号不能为空!";
		}
		logger.warn("检查帐号是否存在:"+msg);
		return msg;
	}
	
	
	@RequestMapping("/login")
	public String login(SysUser su,ModelMap model,HttpSession httpSession) throws Exception{
		//声明和赋初值
		String url = outF("admLogin");
		String msg = "";
		/**
		 * 注意:
		 * (1)springMVC为类型为SysUser的参数su自动创建了一个SysUser对象,所以su不为空。
		 */
		//调用业务层查询该employeeNo是否存在
		List<SysUser> list = sysUserService.selectPage(su);
		if(list.isEmpty()){
			msg="该帐号不存在!There is no user with account of " + su.getEmployeeNo() +".";
		}else{
			SysUser sysUser = list.get(0);//获取用户信息
			if(sysUser.getPwd()!=su.getPwd()){//判断密码是否匹配
				msg="登录密码错误!Password for account "+su.getEmployeeNo()+" was incorrect.";
				url = outF("admLogin");//跳转到登录页面
			}else{
				httpSession.setAttribute("sysUser", sysUser);// 将sysUser放入httpSession
				url = inF("AdmView", "manager");//跳转到主页面
			}
		}
		model.addAttribute("msg", msg);//将msg放入request
		return url;
	}
	
	
}

(6)页面的抽取

/WebContent/common/common.jsp

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> 
<%-- jsp如何截取EL表达式? 答:首先引入标签库  <%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn"%> --%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>

<!-- base必须先设置在所有静态资源之前 -->
<c:set var="base" value="${pageContext.request.contextPath}"></c:set>
<link rel="stylesheet" type="text/css" href="${base}/jquery-easyui-1.3.5/themes/default/easyui.css"/>
<link rel="stylesheet" type="text/css" href="${base}/jquery-easyui-1.3.5/themes/icon.css"/>

<!--jq必须在easyui之前-->
<script type="text/javascript" src="${base}/jquery-easyui-1.3.5/jquery.min.js"></script>
<script type="text/javascript" src="${base}/jquery-easyui-1.3.5/jquery.easyui.min.js"></script>


<body>
</body>
</html>

/WebContent/admLogin.jsp

<%@ page language="java" contentType="text/html; charset=utf-8" 
	pageEncoding="utf-8"%>
<%@ include file="/common/common.jsp"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>管理员登录</title>
<script>
/* 验证帐号是否存在 */
    function  checkEmployeeNo(){
    	$.ajax({
			url:"${base}/sysUserAction/checkEmployeeNo.action",
			type:"post",
			data:{employeeNo:$("#employeeNo").val()},
			datatype:"text",
			success:function(msg){
				$("#employeeNo").next().text(msg);	
			}
		});
    }
/* 检查是否为空    */ 
    function checkBlank(){
    	if($("#employeeNo").val()!=""&&$("#pwd").val()!=""){
    		$("#ff").submit();
		}else{
			alert("帐号和密码不能为空!");
		}
    }


/* 监听 */
    $(function(){
    	$("#employeeNo").blur(function(){
    		checkEmployeeNo();
    	});
    	$("#login").click(function(){
    		checkBlank();
    	});
    });
    
</script>
</head>
<body class="easyui-layout">
	<div data-options="region:'center',title:'管理员登录'" style="padding: 5px; background: #eee;">
		<center>
			<table>
			        <span style="color:red">${msg}</span>
				<form id="ff" action="${base}/sysUserAction/login.action" method="post" style="padding-top: 200px;">
				   	   <tr>
						   <td colspan="2">
						        <label for="employeeNo">帐号:</label> 
						        <input style="width: 200px;" id = "employeeNo" type="text" name="employeeNo"  class="easyui-validatebox"  data-options="required:true,missingMessage:'请填写帐号!'" placeholder="工号"  />
					   	  </td>
					   </tr>
					   <tr>
						   <td colspan="2">
						        <label for="pwd">密码:</label> 
						        <input style="width: 200px;" id="pwd" type="password" name="pwd" class="easyui-validatebox" data-options="required:true,missingMessage:'请填写密码!'" />
					          </td>
					   </tr>
					   <tr>
						   <td colspan="2">
						        <label for="remind">记住密码:</label> 
						        <input style="width: 200px;" type="checkbox" name="remind" class="easyui-validatebox" data-options="required:true"  />
					           </td>
					   </tr> 
					   <tr>
					          <td><input type="button" value="登录" id="login"/></td>
					          <td><input type="reset" value="重置"/></td>
				           </tr>
				 </form>
			</table>
		</center>
	</div>
</body>
</html>


 

 

 

 

上一篇:Oracle进阶学习


下一篇:SpringBoot学习笔记3