小言_互联网的博客

使用SSM完成增删改查

271人阅读  评论(0)

随便写的

先上图

1.添加页面

                      

2.展示页面

3.修改页面

4.查询指定部门下的员工

先看目录结构创建对应的包

1.先导入该有的Jar包(建议用maven)

2.建表

employee表

department表

3配置文件

编写Spring.xml
 

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:mybatis-spring="http://mybatis.org/schema/mybatis-spring"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://mybatis.org/schema/mybatis-spring http://mybatis.org/schema/mybatis-spring-1.2.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
    
    <!-- 组件扫描 -->
    <context:component-scan base-package="com.yzw.ssm">
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>
    
    <!-- 数据源 -->
    <!-- 引入外部属性文件 -->
    <context:property-placeholder location="classpath:db.properties"/>
    <!-- 配置c3p0 -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${jdbc.driver}"></property>
        <property name="jdbcUrl" value="${jdbc.url}"></property>
        <property name="user" value="${jdbc.username}"></property>
        <property name="password" value="${jdbc.password}"></property>
        <property name="initialPoolSize" value="${jdbc.initPoolSize}"></property>
        <property name="maxPoolSize" value="${jdbc.maxPoolSize}"></property>
    </bean>
    
    <!-- 事务 -->
    <bean id="dataSourceTransactionManager"
         class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>    
    </bean>
    <!-- 使用声明式事务 -->
    <tx:annotation-driven transaction-manager="dataSourceTransactionManager"/>
    
    <!-- Spring整合Mybatis  -->
    <!-- a.SqlSession对象的创建及管理
           Mybatis: 基于全局配置文件==>SqlSessionFactory===>SqlSession
           SSM: SqlSessionFactoryBean
     -->
    <bean class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 数据源 -->
        <property name="dataSource" ref="dataSource"></property>
        <!-- Mybatis的全局配置文件 -->
        <property name="configLocation" value="classpath:mybatis-config.xml"></property>
        <!-- 别名处理 -->
        <property name="typeAliasesPackage" value="com.yzw.ssm.bean"></property>
        <!-- SQL映射文件 -->
        <property name="mapperLocations" value="classpath:com/yzw/ssm/mapper/*.xml"></property>
        
    </bean>
    
    <!-- b.Mapper接口代理实现类对象的创建及管理
             MyBatis: session.getMapper(xxxMapper.class);
            SSM: MapperScannerConfigurer
                 EmployeeMapper ==> 代理实现类对象==>IOC==> employeeMapper
    -->
    <!-- 方式一 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.yzw.ssm.mapper"></property>    
    </bean>
    <!-- 方式二 -->
    <!-- <mybatis-spring:scan base-package="com.yzw.ssm.mapper"/> -->

</beans>

编写springmvc.xml
 

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">

    <!-- 组件扫描  -->
    <context:component-scan base-package="com.yzw.ssm" use-default-filters="false">
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>
    
    <!-- 视图解析器 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/views/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>
    
    <!-- mvc配置 -->
    <mvc:default-servlet-handler/>
    <mvc:annotation-driven/>
    
    <!-- 配置上传组件
         注意: id必须指定成multipartResolver,因为springmvc会通过multipartResolver在容器中查找对应的bean对象.
      -->
     <bean id="multipartResolver"
         class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
         <!-- 编码 要设置成与页面的编码一致 -->
         <property name="defaultEncoding" value="utf-8"></property>
         <!-- 设置文件放入临时文件夹的最小大小限制
         此为阈值,低于此值,则保存在内存中,如高于此值,则生成硬盘上的临时文件-->
         <property name="maxInMemorySize" value="1"></property>
         <!-- 设置上传大小 -->
         <property name="maxUploadSize" value="104857600"></property>
     </bean>
    
</beans>

编写web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">

    <!-- 字符编码过滤器 -->
  <filter>
      <filter-name>CharacterEncodingFilter</filter-name>
      <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
      <init-param>
          <param-name>encoding</param-name>
          <param-value>UTF-8</param-value>
      </init-param>
  </filter>
  <filter-mapping>
      <filter-name>CharacterEncodingFilter</filter-name>
      <url-pattern>/*</url-pattern>
  </filter-mapping>
 
  <!-- REST 过滤器 -->
  <filter>
      <filter-name>HiddenHttpMethodFilter</filter-name>
      <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
  </filter>
 
  <filter-mapping>
      <filter-name>HiddenHttpMethodFilter</filter-name>
      <url-pattern>/*</url-pattern>
  </filter-mapping>
 
  <!-- 实例化Spring容器的监听器 -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring.xml</param-value>
    </context-param>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
 
  <!-- 前端控制器 -->
    <servlet>
        <servlet-name>springDispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springmvc.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>springDispatcherServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

</web-app>

Mybatis核心配置文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
  PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>

    <settings>
        <setting name="mapUnderscoreToCamelCase" value="true"/>
        
        <!-- 开启延迟加载 -->
         <setting name="lazyLoadingEnabled" value="true"/>
         <!-- 设置按需加载 -->
         <setting name="aggressiveLazyLoading" value="false"/>
        
        <!-- 开启二级缓存的使用 -->
         <setting name="cacheEnabled" value="true"/>
         
    </settings>
    
    <!-- 注册插件 -->
    <plugins>
        <!-- 分页插件 -->
        <plugin interceptor="com.github.pagehelper.PageInterceptor"></plugin>
    </plugins>
    
</configuration>

4.实体类

public class Department implements Serializable {
    private Integer deptId;
    private String deptName;
    private List<Employee> emps;
 }

 

public class Employee implements Serializable { 
    private String empId;

    private String empName;

    private String gender;

    private String email;

    private String empPictrue;
    private Integer dId;

5.Mapper接口
 

public interface EmployeeMapper {
    
    //查询所有员工
    public List<Employee> getEmps();
    
    //查询指定员工
    public Employee getEmpByEmpId(@Param("empId")String empId);
    
    //添加员工
    public Integer addEmp(Employee employee);

    //修改指定员工
    public Integer updateEmpByEmpId(Employee employee);
    
    //删除指定员工
    public Integer deleteEmpByEmpId(@Param("empId")String empId);
}

public interface DepartmentMapper {
    
    //查询员工所在部门
    public Department getDept(@Param("deptId")Integer deptId);
    
    //查询所有部门
    public List<Department> getDepts();
    
    //根据指定部门查询对应的员工
    public Department getAllEmpsByDept(@Param("deptId")Integer deptId);

}

6.SQL映射文件

employeeMapper.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.yzw.ssm.mapper.EmployeeMapper">

	<!-- 查询所有员工 -->
	<select id="getEmps" resultType="com.yzw.ssm.bean.Employee">
		select emp_id,emp_name,gender,email,emp_pictrue,d_id
		from tbl_emp  
	</select>
	
	<!-- 查询指定员工 -->
	<select id="getEmpByEmpId" resultType="com.yzw.ssm.bean.Employee">
		select emp_id,emp_name,gender,email,emp_pictrue,d_id
		from tbl_emp where emp_id = #{empId}
	</select>
	
	<!-- 添加员工 -->
	<insert id="addEmp">
		insert into tbl_emp(emp_id,emp_name,gender,email,emp_pictrue,d_id)
		values(#{empId},#{empName},#{gender},#{email},#{empPictrue},#{dId});
	</insert>
	
	<!-- 修改指定员工 -->
	<update id="updateEmpByEmpId">
		update tbl_emp set 
		emp_name=#{empName},gender=#{gender},email=#{email},
		emp_pictrue=#{empPictrue},d_id=#{dId} where emp_id=#{empId}
	</update>
	
	<!-- 删除指定员工 -->
	<delete id="deleteEmpByEmpId">
		delete from tbl_emp where emp_id = #{empId}
	</delete>
	
</mapper>

departmentMapper.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.yzw.ssm.mapper.DepartmentMapper">

	<!-- 查询员工所在部门 -->
	<select id="getDept" resultType="com.yzw.ssm.bean.Department">
		select dept_id,dept_name from tbl_dept where dept_id = #{deptId}
	</select>
	
	<!-- 查询所有部门 -->
	<select id="getDepts" resultType="com.yzw.ssm.bean.Department">
		select dept_id,dept_name from tbl_dept
	</select>
	
	<!-- 根据指定部门查询对应的员工 -->
	<select id="getAllEmpsByDept" resultMap="getDeptAndEmps">
		select emp_id,emp_name,gender,email,emp_pictrue,dept_id,dept_name from tbl_dept d
		inner join tbl_emp e on d.dept_id = e.d_id
		where dept_id = #{deptId}
	</select>
	
	<resultMap type="com.yzw.ssm.bean.Department" id="getDeptAndEmps">
		<id column="dept_id" property="deptId"/>
		<result column="dept_name" property="deptName"/>
		
		<collection property="emps" ofType="com.yzw.ssm.bean.Employee">
			<id column="emp_id" property="empId"/>
		  	<result column="emp_name" property="empName"/>
		  	<result column="gender" property="gender"/>
		  	<result column="email" property="email"/>
		  	<result column="emp_pictrue" property="empPictrue"/>
		</collection>
		
	</resultMap>
	
</mapper>

7.前端处理器

@Controller
public class EmployeeHandler {
	
	@Autowired
	private EmployeeService employeeService;
	
	@Autowired
	private DepartmentService departmentService; 
	
	/**
	 * 查询所有员工
	 * @param map
	 * @return
	 */
	@Deprecated
	//@RequestMapping(value="/emps",method=RequestMethod.GET)
	public String getEmps(Map<String,Object> map) {
		List<Employee> emps = employeeService.getEmps();
		System.out.println(emps);
		map.put("emps", emps);
		return "list";
		
	}
	
	/**
	 * 查询员工并分页
	 * @param map
	 * @return
	 */
	@RequestMapping(value="/emps/{pageNum}",method=RequestMethod.GET)
	public String getEmpsAndPage(@PathVariable("pageNum")Integer pageNum,Map<String,Object> map) {
		
		//pageNum:页码   pageSize:每页显示数量
		PageHelper.startPage(pageNum, 5);
		
		List<Employee> emps = employeeService.getEmps();
		
		//List<T> list:page结果     navigatePages:页码数量
		PageInfo<Employee> pageInfo = new PageInfo<>(emps,5);
		
		map.put("pageInfo", pageInfo);
		
		return "list";
		
	}
	
	
	/**
	 * 去往修改页面
	 * @param empId
	 * @param map
	 * @return
	 */
	@RequestMapping(value="emp/{empId}",method=RequestMethod.GET)
	public String toUpdatePage(@PathVariable("empId")String empId,Map<String,Object> map) {
		//查询指定员工
		Employee employee = employeeService.getEmpByEmpId(empId);
		//查询员工所在部门
		Department department = departmentService.getDept(employee.getdId());
		map.put("employee", employee);
		map.put("department", department);
		System.out.println(employee);
		System.out.println(department);
		return "update";
	}
	
	
	/**
	 * 真正的修改
	 * @param employee
	 * @return
	 */
	@RequestMapping(value="emp",method=RequestMethod.PUT)
	public String updateEmpByEmpId(Employee employee) {
		employeeService.updateEmpByEmpId(employee);
		//表示修改完成后重定向到第一页(其实可以获取所修改的页面修改完成后重定向到指定页面而不是                        
        //默认第一页,比较简单大家自己实现)
        return "redirect:/emps/1";
	}
	
	/**
	 * 删除员工(批量删除大家可以自己实现,就是通过全选框获取的id值传递到后台通过字符串切割放到 
     * list集合里进行批量删除)
	 * @param empId
	 * @return
	 */
	@RequestMapping(value="emp/{empId}",method=RequestMethod.DELETE)
	public String deleteEmpByEmpId(@PathVariable("empId")String empId) {
		employeeService.deleteEmpByEmpId(empId);
		return "redirect:/emps/1";
	}
	
   /**
	 * 去往添加页面
	 * @param empId
	 * @return
	 */
	@RequestMapping(value="/emp",method=RequestMethod.GET)
	public String toAddPage(Map<String,Object> map) {
		//先查询所有部门
		List<Department> depts = departmentService.getDepts();
		map.put("depts", depts);
		return "add";
	}
	
	/**
	 * 文件上传必须发布到tomcat webapps下,而不是发布在 wtpwebapps下(访问不到)
	 * @param file
	 * @param (其实可以直接传递POJO)
	 * @param session
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="emp",method=RequestMethod.POST)
	public String upload(@RequestParam("uploadFile")MultipartFile file,
			@RequestParam("empName")String empName,@RequestParam("gender")String gender,
			@RequestParam("email")String email,@RequestParam("dId")Integer dId,
			HttpSession session) throws Exception {
		System.out.println(file);
		
		//获取文件名
		String fileName = file.getOriginalFilename();
		InputStream is = file.getInputStream();
		
		ServletContext context = session.getServletContext();
		String path = context.getRealPath("upload");
		System.out.println(path);
		
		//生成员工id
		String empId = UUID.randomUUID().toString().substring(0, 6);
		
		//生成随机字符串
		fileName = UUID.randomUUID().toString().substring(0, 6) + "-" + fileName;
		
		//目标文件
		File target = new File(path+File.separator+fileName);
		
		  //判断文件是否存在
		if (!target.exists()) {
              target.createNewFile();
        }
		
		 //此代码就相当于文件复制
		 file.transferTo(target);
		 is.close();
		 
		 //封装Employee对象(其实可以直接传递POJO)
		 Employee employee = new Employee();
		 employee.setEmpId(empId);
		 employee.setEmpName(empName);
		 employee.setGender(gender);
		 employee.setEmail(email);
		 employee.setEmpPictrue(fileName);
		 employee.setdId(dId);
		 
		 System.out.println(employee);
		 
		 employeeService.addEmp(employee);
		
		
		return "redirect:/emps/1";
	}
	
}
@Controller
@RequestMapping("/dept")
public class DepartmentHandler {
	
	@Autowired
	private DepartmentService departmentService; 
	
	@RequestMapping(value="/emps/{deptId}/{pageNum}",method=RequestMethod.GET)
	public String getAllEmpsByDept(@PathVariable("deptId")Integer deptId,
			@PathVariable("pageNum")Integer pageNum,Map<String,Object> map) {
		
		PageHelper.startPage(pageNum,3);
		Department dept = departmentService.getAllEmpsByDept(deptId);
		PageInfo<Employee> pageInfo = new PageInfo<>(dept.getEmps(), 5);
		map.put("pageInfo", pageInfo);
		map.put("dept", dept);
		System.out.println(dept);
		
		return "empsByDept";
	}

}

 

index.jsp

<a href="emps/1">查询所有员工</a><br>
<a href="dept/emps/1/1">查询指定部门下所有员工</a>

"emps/1" :默认查询第一页的员工信息
"dept/emps/1/1" :表示查询第一页部门编号为1的所有员工

list.jsp
 

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>所有员工</title>

 
    <!-- Bootstrap -->
    <link href="${pageContext.request.contextPath}/bootstrap/css/bootstrap.min.css"
          rel="stylesheet">

    <!-- jQuery (Bootstrap 的所有 JavaScript 插件都依赖 jQuery,所以必须放在前边) -->
    <script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery-1.12.4.js"></script>
    <script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery.validate.min.js"></script>
    <script type="text/javascript" src="${pageContext.request.contextPath}/js/messages_zh.js"></script>

    <!-- 加载 Bootstrap 的所有 JavaScript 插件,你也可以根据需要只加载单个插件. -->
    <script src="${pageContext.request.contextPath}/bootstrap/js/bootstrap.min.js"></script>
    
</head>
<body>

<table class="table table-hover">
    <thead>
        <tr>
              <td>姓名</td>
              <td>性别</td>
              <td>邮箱</td>
              <td>头像</td>
              <td>部门</td>
              <td> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 操作</td>
        </tr>
    </thead>
      
      <!-- 未分页的数据 -->
      <%-- <tbody>
     <c:forEach items="${emps}" var="emp">
      <tr>
          <td>${emp.empName}</td>
          <td>${emp.gender==0?"女":"男"}</td>
          <td>${emp.email}</td>
         <td><img src="${pageContext.request.contextPath}/upload/${emp.empPictrue}"
              width="120px" height="50px" ></td>
          <td>
              <c:choose>
                  <c:when test="${emp.dId==1}">开发部</c:when>
                  <c:when test="${emp.dId==2}">测试部</c:when>
                  <c:when test="${emp.dId==3}">运维部</c:when>
                  <c:when test="${emp.dId==4}">财务部</c:when>
              </c:choose>
          </td>
          <td><a class="btn btn-primary btn-sm active" role="button"
                 href="${pageContext.request.contextPath}/emp/${emp.empId}">修改</a> &nbsp;&nbsp;
          <a class="delete_emp btn btn-primary btn-sm active" role="button"
                 href="${pageContext.request.contextPath}/emp/${emp.empId}">删除</a>
          </td>
      </tr>
      </c:forEach> --%>
      
      <!-- 进行分页 -->
      <tbody>
     <c:forEach items="${pageInfo.list}" var="emp">
      <tr>
          <td>${emp.empName}</td>
          <td>${emp.gender==0?"女":"男"}</td>
          <td>${emp.email}</td>
          <td><img src="${pageContext.request.contextPath}/upload/${emp.empPictrue}"
              width="120px" height="50px" ></td>
          <td>
              <c:choose>
                  <c:when test="${emp.dId==1}">开发部</c:when>
                  <c:when test="${emp.dId==2}">测试部</c:when>
                  <c:when test="${emp.dId==3}">运维部</c:when>
                  <c:when test="${emp.dId==4}">财务部</c:when>
              </c:choose>
          </td>
          <td><a class="btn btn-primary btn-sm active" role="button"
                 href="${pageContext.request.contextPath}/emp/${emp.empId}">修改</a> &nbsp;&nbsp;
          <a class="delete_emp btn btn-primary btn-sm active" role="button"
                 href="${pageContext.request.contextPath}/emp/${emp.empId}">删除</a>
          </td>
      </tr>
      </c:forEach>
       <tr>
           <td></td>
           <td></td>
           <td></td>
           <td></td>
           <td></td>
           <td>
              <a class="btn btn-primary btn-sm" href="${pageContext.request.contextPath}/emp">添加新员工</a>
            </td>
         </tr>
    </tbody>
    
    <!-- 删除 -->
    <form id="delForm" action="" method="post">
        <input type="hidden" name="_method" value="DELETE">
    </form>
    
</table>

<!-- 分页导航栏 -->
<nav aria-label="Page navigation" style="text-align: center">
  <ul class="pagination">
    
    <!-- 上一页 -->
    <!-- 使用isFirstPage也可以 -->
    <c:choose>
        <c:when test="${!pageInfo.hasPreviousPage}">
            <li class="disabled">
                    <span aria-hidden="true">&laquo;</span>
            </li>
        </c:when>
        <c:otherwise>
            <li>
                  <a href="${pageInfo.prePage}" aria-label="Previous">
                    <span aria-hidden="true">&laquo;</span>
                  </a>
            </li>
        </c:otherwise>
    </c:choose>
    
   <!-- 导航页码数 -->
   <c:forEach items="${pageInfo.navigatepageNums}" var="navpageNum">
           <c:if test="${pageInfo.pageNum==navpageNum}">
                <li class="active">
                    <a href="javascript:;">${navpageNum}</a>
                </li>
           </c:if>
           
           <c:if test="${pageInfo.pageNum!=navpageNum}">
               <li>
                   <a href="${navpageNum}">${navpageNum}</a>
               </li>
           </c:if>
   </c:forEach>
    
    <!-- 下一页 -->
    <!-- pageInfo里面的isLastPage过时了,不好用 -->
    <c:choose>
        <c:when test="${!pageInfo.hasNextPage}">
            <li class="disabled">
                    <span aria-hidden="true">&raquo;</span>
            </li>    
        </c:when>
        <c:otherwise>
            <li>
                 <a href="${pageInfo.nextPage}" aria-label="Next">
                    <span aria-hidden="true">&raquo;</span>
                 </a>
            </li>
        </c:otherwise>
    </c:choose>
    
  </ul>
 
  <div id="tailNav">共<span class="badge">${pageInfo.pages}</span>页,
                共<span class="badge">${pageInfo.total}</span>条数据
   </div>
 
</nav>

<span></span>

<script type="text/javascript">
    /* 发送delete请求  */
    $(function() {
        $(".delete_emp").click(function() {
            //确认是否要删除
            if(!confirm("(づ ̄3 ̄)づ╭❤~,您确定要删除吗?")) {
                return false;
            }
            
            var href = $(this)[0].href;
            $("#delForm").attr("action",href).submit();
            return false;
        });
        
    })
</script>

</body>
</html>

add.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>添加员工</title>

    <!-- Bootstrap -->
    <link href="${pageContext.request.contextPath}/bootstrap/css/bootstrap.min.css"
          rel="stylesheet">

    <!-- jQuery (Bootstrap 的所有 JavaScript 插件都依赖 jQuery,所以必须放在前边) -->
    <script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery-1.12.4.js"></script>
    <script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery.validate.min.js"></script>
    <script type="text/javascript" src="${pageContext.request.contextPath}/js/messages_zh.js"></script>

    <!-- 加载 Bootstrap 的所有 JavaScript 插件,你也可以根据需要只加载单个插件. -->
    <script src="${pageContext.request.contextPath}/bootstrap/js/bootstrap.min.js"></script>

</head>
<body>

<form action="${pageContext.request.contextPath}/emp" method="post" enctype="multipart/form-data">
  <div class="form-group">
    <label for="exampleInputEmpName">姓名</label>
    <input type="text" class="form-control" id="exampleInputempName" name="empName" placeholder="请输入姓名">
  </div>
 
     性别:&nbsp;&nbsp;&nbsp;     
     <label class="radio-inline">
      <input type="radio" name="gender" id="inlineRadio1" value="0">女
    </label>
    <label class="radio-inline">
      <input type="radio" name="gender" id="inlineRadio2" value="1">男
    </label>

  <div class="form-group">
    <label for="exampleInputEmail">邮箱</label>
    <input type="email" class="form-control" id="exampleInputEmail" name="email" placeholder="请输入邮箱">
  </div>
 
  <div class="form-group">
    <label for="exampleInputFile">头像</label>
    <input type="file" id="exampleInputFile" name="uploadFile">
    <p class="help-block">请上传头像.</p>
  </div>
 
  <select class="form-control" name="dId">
      <c:forEach items="${depts}" var="dept">
          <option value="${dept.deptId}">${dept.deptName}</option>
      </c:forEach>
  </select>
 
  <button type="submit" class="btn btn-default">提交</button>
</form>

</body>
</html>

update.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>修改员工</title>

    <!-- Bootstrap -->
    <link href="${pageContext.request.contextPath}/bootstrap/css/bootstrap.min.css"
          rel="stylesheet">

    <!-- jQuery (Bootstrap 的所有 JavaScript 插件都依赖 jQuery,所以必须放在前边) -->
    <script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery-1.12.4.js"></script>
    <script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery.validate.min.js"></script>
    <script type="text/javascript" src="${pageContext.request.contextPath}/js/messages_zh.js"></script>

    <!-- 加载 Bootstrap 的所有 JavaScript 插件,你也可以根据需要只加载单个插件. -->
    <script src="${pageContext.request.contextPath}/bootstrap/js/bootstrap.min.js"></script>

</head>
<body>

<form action="${pageContext.request.contextPath}/emp" method="post">
  <input type="hidden" name="_method" value="PUT">
  <input type="hidden" name="empId" value="${employee.empId}">
  <div class="form-group">
    <label for="exampleInputEmpName">姓名</label>
    <input type="text" class="form-control" id="exampleInputempName" name="empName" value="${employee.empName}">
  </div>
  
      性别:&nbsp;&nbsp;&nbsp;     
	 <label class="radio-inline">
	  <input type="radio" name="gender" id="inlineRadio1" value="0">女
	</label>
	<label class="radio-inline">
	  <input type="radio" name="gender" id="inlineRadio2" value="1">男
	</label>
	
  <div class="form-group">
    <label for="exampleInputEmail">邮箱</label>
    <input type="email" class="form-control" id="exampleInputEmail" name="email" value="${employee.email}">
  </div>
  <!-- <div class="form-group">
    <label for="exampleInputFile">File input</label>
    <input type="file" id="exampleInputFile">
    <p class="help-block">Example block-level help text here.</p>
  </div> -->
  
  <input type="hidden" name="empPictrue" value="${employee.empPictrue}">
  
  <select class="form-control" name="dId">
  	<option value="${employee.dId}">${department.deptName}</option>
  </select>
  
  <button type="submit" class="btn btn-default">提交</button>
</form> 

</body>
</html>

empsByDept.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>特定部门下的所有员工</title>

<%--官方文档--%>
    <!-- Bootstrap -->
    <link href="${pageContext.request.contextPath}/bootstrap/css/bootstrap.min.css"
          rel="stylesheet">

    <!-- jQuery (Bootstrap 的所有 JavaScript 插件都依赖 jQuery,所以必须放在前边) -->
    <script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery-1.12.4.js"></script>
    <script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery.validate.min.js"></script>
    <script type="text/javascript" src="${pageContext.request.contextPath}/js/messages_zh.js"></script>

    <!-- 加载 Bootstrap 的所有 JavaScript 插件,你也可以根据需要只加载单个插件. -->
    <script src="${pageContext.request.contextPath}/bootstrap/js/bootstrap.min.js"></script>

</head>
<body>

<h2 align="center">${dept.deptName}</h2>

<table class="table table-hover">
	<thead>
		<tr>
			<td>姓名</td>
		  	<td>性别</td>
		  	<td>邮箱</td>
		  	<td>头像</td>
		  	<!-- <td>部门</td> -->
		  	<td> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 操作</td>
		</tr>
	</thead>
  	
  	<!-- 分页 -->
  	<tbody>
     <c:forEach items="${pageInfo.list}" var="emp">
      <tr>
          <td>${emp.empName}</td>
          <td>${emp.gender==0?"女":"男"}</td>
          <td>${emp.email}</td>
         <td><img src="${pageContext.request.contextPath}/upload/${emp.empPictrue}"
              width="120px" height="50px" ></td>
          <td><a class="btn btn-primary btn-sm active" role="button"
                 href="${pageContext.request.contextPath}/emp/${emp.empId}">修改</a> &nbsp;&nbsp;
          <a class="delete_emp btn btn-primary btn-sm active" role="button"
                 href="${pageContext.request.contextPath}/emp/${emp.empId}">删除</a>
          </td>
      </tr>
      </c:forEach> 
	</tbody>      
</table>

<!-- 分页导航栏 -->
<nav aria-label="Page navigation" style="text-align: center">
  <ul class="pagination">
    
    <!-- 上一页 -->
    <!-- 使用isFirstPage也可以 -->
    <c:choose>
    	<c:when test="${!pageInfo.hasPreviousPage}">
    		<li class="disabled">
        			<span aria-hidden="true">&laquo;</span>
    		</li>
    	</c:when>
    	<c:otherwise>
    		<li>
     	 		<a href="${pageInfo.prePage}" aria-label="Previous">
        			<span aria-hidden="true">&laquo;</span>
      			</a>
    		</li>
    	</c:otherwise>
    </c:choose>
    
   <!-- 导航页码数 -->
   <c:forEach items="${pageInfo.navigatepageNums}" var="navpageNum">
   		<c:if test="${pageInfo.pageNum==navpageNum}">
   			 <li class="active">
   			 	<a href="javascript:;">${navpageNum}</a>
   			 </li>
   		</c:if>
   		
   		<c:if test="${pageInfo.pageNum!=navpageNum}">
   			<li>
   				<a href="${navpageNum}">${navpageNum}</a>
   			</li>
   		</c:if>
   </c:forEach>
    
    <!-- 下一页 -->
    <!-- pageInfo里面的isLastPage过时了,不好用 -->
    <c:choose>
    	<c:when test="${!pageInfo.hasNextPage}">
    		<li class="disabled">
			        <span aria-hidden="true">&raquo;</span>
	    	</li>	
    	</c:when>
    	<c:otherwise>
    		<li>
			     <a href="${pageInfo.nextPage}" aria-label="Next">
			        <span aria-hidden="true">&raquo;</span>
			     </a>
	    	</li>
    	</c:otherwise>
    </c:choose>
    
  </ul>
  
  <div id="tailNav">共<span class="badge">${pageInfo.pages}</span>页,
                共<span class="badge">${pageInfo.total}</span>条数据
   </div>
  
</nav>

</body>
</html>

注意还有数据库配置文件哦

useUnicode=true&characterEncoding=UTF8:解决乱码
allowMultiQueries=true:允许进行批量操作

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssm?useUnicode=true&characterEncoding=UTF8&allowMultiQueries=true
jdbc.username=root
jdbc.password=root
jdbc.initPoolSize=5
jdbc.maxPoolSize=20

log4j(只是为了更加容易找错误,不加也没关系)

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
 
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
 
 <appender name="STDOUT" class="org.apache.log4j.ConsoleAppender">
   <param name="Encoding" value="UTF-8" />
   <layout class="org.apache.log4j.PatternLayout">
    <param name="ConversionPattern" value="%-5p %d{MM-dd HH:mm:ss,SSS} %m  (%F:%L) \n" />
   </layout>
 </appender>
 <logger name="java.sql">
   <level value="debug" />
 </logger>
 <logger name="org.apache.ibatis">
   <level value="info" />
 </logger>
 <root>
   <level value="debug" />
   <appender-ref ref="STDOUT" />
 </root>
</log4j:configuration>

 

 


转载:https://blog.csdn.net/qq_42691671/article/details/100987695
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场