课程介绍:
开发环境配置:
项目结构:
配置和注解:
数据库设计:
建表语句:
drop database if exists sm;
create database sm;
use sm;
create table department(
id int primary key auto_increment,
name varchar(20) not null,
address varchar(100)
);
create table staff(
id int primary key auto_increment,
account varchar(20) not null,
password varchar(20) not null,
status varchar(10) not null,
did int,
name varchar(20),
sex char(2),
id_number char(18),
work_time datetime,
leave_time datetime,
born_date date,
info varchar(200)
);
create table log(
opr_time datetime not null,
type varchar(10) not null,
operator varchar(20) not null,
moudle varchar(20) not null,
operation varchar(20) not null,
result varchar(100) not null
);
alter table staff add constraint fk_staff_dep foreign key(did) references department(id);
创建项目:
项目结构:
sm的pom文件:sm作为父module,主要配置其子module
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.imooc</groupId>
<artifactId>sm</artifactId>
<packaging>pom</packaging>
<version>1.0-SNAPSHOT</version>
<!-- 仓库配置 -->
<repositories>
<repository>
<!-- 创建私服的地址,优先从阿里云下载 -->
<id>aliyun</id>
<name>aliyun</name>
<url>https://maven.aliyun.com/repository/public</url>
</repository>
</repositories>
<modules>
<module>sm_service</module>
<module>sm_web</module>
</modules>
<properties>
<spring.version>4.0.2.RELEASE</spring.version>
</properties>
</project>
sm_service的pom文件:主要配置其使用的依赖
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>sm</artifactId>
<groupId>com.imooc</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<!-- 仓库配置 -->
<repositories>
<repository>
<!-- 创建私服的地址,优先从阿里云下载 -->
<id>aliyun</id>
<name>aliyun</name>
<url>https://maven.aliyun.com/repository/public</url>
</repository>
</repositories>
<artifactId>sm_service</artifactId>
<packaging>jar</packaging>
<dependencies>
<!-- Mybatis -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.44</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.4</version>
</dependency>
<!-- Spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.0.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>4.0.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.0.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>4.0.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.0</version>
</dependency>
<!-- 事务 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>4.0.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>4.0.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.1</version>
</dependency>
</dependencies>
</project>
sm_web的pom文件:配置其使用的依赖和父module
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<parent>
<artifactId>sm</artifactId>
<groupId>com.imooc</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<!-- 仓库配置 -->
<repositories>
<repository>
<!-- 创建私服的地址,优先从阿里云下载 -->
<id>aliyun</id>
<name>aliyun</name>
<url>https://maven.aliyun.com/repository/public</url>
</repository>
</repositories>
<artifactId>sm_web</artifactId>
<packaging>war</packaging>
<name>sm_web Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>com.imooc</groupId>
<artifactId>sm_service</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.0</version>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
</dependencies>
<build>
<finalName>sm_web</finalName>
</build>
</project>
引入配置文件:
sm_service下的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:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="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.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- Spring整合Mybatis -->
<!-- 将原先mybatis管理的sessionFactory和持久化操作对象交给spring进行管理-->
<!-- 数据源-->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/sm?useUnicode=true&characterEncoding=UTF-8"/>
<property name="username" value="root"/>
<property name="password" value="mima19971009"/>
</bean>
<!-- session工厂-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<!-- 配置别名-->
<property name="typeAliasesPackage" value="com.imooc.sm.entity"/>
</bean>
<!-- 持久化对象-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.imooc.sm.dao"/>
<!-- 需要调用sessionFactory的时候,选择调用哪一个-->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
</bean>
<!-- 声明式事务 -->
<!-- 事务管理器-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!-- 关联数据源-->
<property name="dataSource" ref="dataSource"/>
</bean>
<!-- 声明通知-->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<!-- 设置对进行不同的事务管理-->
<tx:attributes>
<tx:method name="get*" read-only="true"/>
<tx:method name="find*" read-only="true"/>
<tx:method name="search*" read-only="true"/>
<tx:method name="*" propagation="REQUIRED"/>
</tx:attributes>
</tx:advice>
<!-- 植入操作-->
<aop:config>
<!-- 声明切入点-->
<aop:pointcut id="txPointcut" expression="execution(* com.imooc.sm.service.*.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut"/>
</aop:config>
<!-- 全局扫描 -->
<context:component-scan base-package="com.imooc.sm"/>
<!-- 自动代理 -->
<aop:aspectj-autoproxy/>
</beans>
工具类:
编码过滤器:
EncodingFilter:
package com.imooc.sm.global;
import javax.servlet.*;
import java.io.IOException;
public class EncodingFilter implements Filter {
private String encoding ="UTF-8";
public void init(FilterConfig filterConfig) throws ServletException {
if(filterConfig.getInitParameter("ENCODING")!=null)
encoding = filterConfig.getInitParameter("ENCODING");
}
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
servletRequest.setCharacterEncoding(encoding);
servletResponse.setCharacterEncoding(encoding);
filterChain.doFilter(servletRequest,servletResponse);
}
public void destroy() {
encoding=null;
}
}
在web.xml对编码过滤器进行配置:
<!--配置编码过滤器-->
<filter>
<filter-name>Encoding</filter-name>
<filter-class>com.imooc.sm.global.EncodingFilter</filter-class>
<!-- 初始化参数-->
<init-param>
<param-name>ENCODING</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>Encoding</filter-name>
<!-- 配置所有的请求都要被编码过滤器过滤-->
<url-pattern>/*</url-pattern>
</filter-mapping>
核心控制器:
DispatcherServlet:核心控制器
package com.imooc.sm.global;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import javax.servlet.GenericServlet;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class DispatcherServlet extends GenericServlet {
private ApplicationContext context;
public void init() throws ServletException {
super.init();
context = new ClassPathXmlApplicationContext("spring.xml");
}
public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse;
/*
staff/add.do login.do
staffController
public void add(HttpServletRequest request, HttpServletResponse response){}
*
*/
String path = request.getServletPath().substring(1);
String beanName = null;
String methodName = null;
int index = path.indexOf('/');
if (index != -1) {
beanName = path.substring(0, index) + "Controller";
methodName = path.substring(index + 1, path.indexOf(".do"));
} else {
beanName = "selfController";
methodName = path.substring(0, path.indexOf(".do"));
}
Object obj = context.getBean(beanName);
try {
Method method = obj.getClass().getMethod(methodName,HttpServletRequest.class,HttpServletResponse.class);
method.invoke(obj,request,response);
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
配置核心控制器代码:
<!--配置核心控制器-->
<servlet>
<servlet-name>Global</servlet-name>
<servlet-class>com.imooc.sm.global.DispatcherServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Global</servlet-name>
<!-- 对所有以.do结尾的都交给核心控制器进行处理-->
<url-pattern>*.do</url-pattern>
</servlet-mapping>
功能实现:
部门管理实现--业务:
创建Department实体类:
package com.imooc.sm.entity;
public class Department {
private Integer id;
private String name;
private String address;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
创建部门持久化操作接口DepartmentDao:
package com.imooc.sm.dao;
import com.imooc.sm.entity.Department;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository("departmentDao")
public interface DepartmentDao {
void insert(Department department);
void delete(Integer id);
void update(Department department);
Department selectById(Integer id);
List<Department> selectAll();
}
对DepartmentDao进行配置:至此,持久化操作实现成功
<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.4//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.imooc.sm.dao.DepartmentDao">
<resultMap id="resultMap" type="Department">
<id property="id" column="id" javaType="Integer"/>
<result property="name" column="name" javaType="String"/>
<result property="address" column="address" javaType="String"/>
</resultMap>
<!-- 调用的是自增主键,所以使用参数useGeneratedKeys-->
<insert id="insert" parameterType="Department" useGeneratedKeys="true">
insert into department(name,address) values(#{name},#{address})
</insert>
<delete id="delete" parameterType="Integer">
delete from department where id=#{id}
</delete>
<update id="update" parameterType="Department">
update department set name=#{name},address=#{address} where id=#{id}
</update>
<select id="selectById" parameterType="Integer" resultMap="resultMap">
select * from department where id=#{id}
</select>
<select id="selectAll" resultMap="resultMap">
select * from department
</select>
</mapper>
声明部门业务层接口DepartmentService:
package com.imooc.sm.service;
import com.imooc.sm.entity.Department;
import java.util.List;
public interface DepartmentService {
void add(Department department);
void remove(Integer id);
void edit(Department department);
Department get(Integer id);
List<Department> getAll();
}
部门业务层实现DepartmentServiceImpl:
package com.imooc.sm.service.impl;
import com.imooc.sm.dao.DepartmentDao;
import com.imooc.sm.entity.Department;
import com.imooc.sm.service.DepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service("departmentService")
public class DepartmentServiceImpl implements DepartmentService {
@Autowired
private DepartmentDao departmentDao;
public void add(Department department) {
departmentDao.insert(department);
}
public void remove(Integer id) {
departmentDao.delete(id);
}
public void edit(Department department) {
departmentDao.update(department);
}
public Department get(Integer id) {
return departmentDao.selectById(id);
}
public List<Department> getAll() {
return departmentDao.selectAll();
}
}
部门管理实现--界面:控制器
package com.imooc.sm.controller;
import com.imooc.sm.entity.Department;
import com.imooc.sm.service.DepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
@Controller("departmentController")
public class DepartmentController {
@Autowired
private DepartmentService departmentService;
// 访问/department/list.do 转向/department_list.jsp
public void list(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
List<Department> list = departmentService.getAll();
request.setAttribute("LIST",list);
request.getRequestDispatcher("../department_list.jsp").forward(request,response);
}
}
部门界面:department_list.jsp:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>部门列表</title>
<link rel="stylesheet" type="text/css" href="../css/reset.css"/>
<link rel="stylesheet" type="text/css" href="../css/common.css"/>
<link rel="stylesheet" type="text/css" href="../css/thems.css">
<script type="text/javascript" src="../js/jquery-1.8.3.min.js"></script>
<script type="text/javascript">
$(function(){
//自适应屏幕宽度
window.onresize=function(){ location=location };
var main_h = $(window).height();
$('.hy_list').css('height',main_h-45+'px');
var search_w = $(window).width()-40;
$('.search').css('width',search_w+'px');
//$('.list_hy').css('width',search_w+'px');
});
</script>
<!--框架高度设置-->
</head>
<body onLoad="Resize();">
<div id="right_ctn">
<div class="right_m">
<div class="hy_list">
<div class="box_t">
<span class="name">部门列表</span>
</div>
<div class="space_hx"> </div>
<!--列表-->
<table cellpadding="0" cellspacing="0" class="list_hy">
<tr>
<th scope="col">名称</th>
<th scope="col">地址</th>
<th scope="col">操作</th>
</tr>
<c:forEach items="${LIST}" var="dep">
<tr>
<td>${dep.name}</td>
<td>${dep.address}</td>
<td>
<a href="toEdit.do?id=${dep.id}" class="btn">编辑</a>
<a href="remove.do?id=${dep.id}" class="btn">删除</a>
</td>
</tr>
</c:forEach>
</table>
<!--列表-->
<!--右边底部-->
<div class="r_foot">
<div class="r_foot_m">
<a href="toAdd.do" class="btn">添加</a>
</div>
</div>
<!--右边底部-->
</div>
<!--会议列表-->
</div>
</div>
</body>
</html>
tomcat配置:
输出结果:和数据库里数据保持一致
增加部门页面实现:
package com.imooc.sm.controller;
import com.imooc.sm.entity.Department;
import com.imooc.sm.service.DepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
@Controller("departmentController")
public class DepartmentController {
@Autowired
private DepartmentService departmentService;
// 访问/department/list.do 转向/department_list.jsp
public void list(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
List<Department> list = departmentService.getAll();
request.setAttribute("LIST",list);
request.getRequestDispatcher("../department_list.jsp").forward(request,response);
}
public void toAdd(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.getRequestDispatcher("../department_add.jsp").forward(request,response);
}
public void add(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String name = request.getParameter("name");
String address = request.getParameter("address");
Department department = new Department();
department.setName(name);
department.setAddress(address);
departmentService.add(department);
response.sendRedirect("list.do");
}
}
增加部门页面:department_add.jsp:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=8" >
<title>添加部门</title>
<link rel="stylesheet" type="text/css" href="../css/reset.css"/>
<link rel="stylesheet" type="text/css" href="../css/common.css"/>
<link rel="stylesheet" type="text/css" href="../css/thems.css">
<script type="text/javascript" src="../js/jquery-1.8.3.min.js"></script>
<script type="text/javascript">
$(function(){
//自适应屏幕宽度
window.onresize=function(){ location=location };
var main_h = $(window).height();
$('.hy_list').css('height',main_h-45+'px');
var main_w = $(window).width();
$('.xjhy').css('width',main_w-40+'px');
});
</script>
</head>
<body onLoad="Resize();">
<div id="right_ctn">
<div class="right_m">
<div class="hy_list">
<div class="box_t">
<span class="name">添加部门</span>
</div>
<div class="space_hx"> </div>
<form action="add.do" method="post" name="addForm">
<div class="xjhy">
<!--高级配置-->
<ul class="hypz gjpz clearfix">
<li class="clearfix">
<span class="title">名称:</span>
<div class="li_r">
<input class="chang" name="name" type="text"/>
<i>*</i>
</div>
</li>
<li class="clearfix">
<span class="title">地址:</span>
<div class="li_r">
<input class="chang" name="address" type="text"/>
</div>
</li>
<li class="tj_btn">
<a href="javascript:history.go(-1);" class="back">返回</a>
<a href="javascript:addForm.submit();">保存</a>
</li>
</ul>
<!--高级配置-->
</div>
</form>
</div>
</div>
</div>
</body>
</html>
测试结果:访问
http://localhost:8080/sm/department/toAdd.do
输出结果:
点击保存:
编辑部门和删除界面:
package com.imooc.sm.controller;
import com.imooc.sm.entity.Department;
import com.imooc.sm.service.DepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
@Controller("departmentController")
public class DepartmentController {
@Autowired
private DepartmentService departmentService;
// 访问/department/list.do 转向/department_list.jsp
public void list(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
List<Department> list = departmentService.getAll();
request.setAttribute("LIST",list);
request.getRequestDispatcher("../department_list.jsp").forward(request,response);
}
//增加部门
public void toAdd(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.getRequestDispatcher("../department_add.jsp").forward(request,response);
}
public void add(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String name = request.getParameter("name");
String address = request.getParameter("address");
Department department = new Department();
department.setName(name);
department.setAddress(address);
departmentService.add(department);
response.sendRedirect("list.do");
}
//编辑部门
public void toEdit(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Integer id = Integer.parseInt(request.getParameter("id"));
Department department = departmentService.get(id);
request.setAttribute("OBJ",department);
request.getRequestDispatcher("../department_edit.jsp").forward(request,response);
}
public void edit(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Integer id = Integer.parseInt(request.getParameter("id"));
String name = request.getParameter("name");
String address = request.getParameter("address");
Department department = new Department();
department.setId(id);
department.setName(name);
department.setAddress(address);
departmentService.edit(department);
response.sendRedirect("list.do");
}
//删除部门
public void remove(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Integer id = Integer.parseInt(request.getParameter("id"));
departmentService.remove(id);
response.sendRedirect("list.do");
}
}
department_edit.jsp:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=8" >
<title>编辑部门</title>
<link rel="stylesheet" type="text/css" href="../css/reset.css"/>
<link rel="stylesheet" type="text/css" href="../css/common.css"/>
<link rel="stylesheet" type="text/css" href="../css/thems.css">
<script type="text/javascript" src="../js/jquery-1.8.3.min.js"></script>
<script type="text/javascript">
$(function(){
//自适应屏幕宽度
window.onresize=function(){ location=location };
var main_h = $(window).height();
$('.hy_list').css('height',main_h-45+'px');
var main_w = $(window).width();
$('.xjhy').css('width',main_w-40+'px');
});
</script>
</head>
<body onLoad="Resize();">
<div id="right_ctn">
<div class="right_m">
<div class="hy_list">
<div class="box_t">
<span class="name">编辑部门</span>
</div>
<div class="space_hx"> </div>
<form action="edit.do" method="post" name="addForm">
<input name="id" type="hidden" value="${OBJ.id}"/>
<div class="xjhy">
<!--高级配置-->
<ul class="hypz gjpz clearfix">
<li class="clearfix">
<span class="title">名称:</span>
<div class="li_r">
<input class="chang" name="name" type="text" value="${OBJ.name}"/>
<i>*</i>
</div>
</li>
<li class="clearfix">
<span class="title">地址:</span>
<div class="li_r">
<input class="chang" name="address" type="text" value="${OBJ.address}"/>
</div>
</li>
<li class="tj_btn">
<a href="javascript:history.go(-1);" class="back">返回</a>
<a href="javascript:addForm.submit();">保存</a>
</li>
</ul>
<!--高级配置-->
</div>
</form>
</div>
</div>
</div>
</body>
</html>
测试结果:
删除研发部:
员工管理实现:
员工实体类staff:
package com.imooc.sm.entity;
import java.util.Date;
public class Staff {
private Integer id;
private String account;
private String password;
private String status;
private Integer did;
private String name;
private String sex;
private String idNumber;
private Date workTime;
private Date leaveTime;
private Date bornDate;
private String info;
private Department department;
public Department getDepartment() {
return department;
}
public void setDepartment(Department department) {
this.department = department;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getAccount() {
return account;
}
public void setAccount(String account) {
this.account = account;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public Integer getDid() {
return did;
}
public void setDid(Integer did) {
this.did = did;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getIdNumber() {
return idNumber;
}
public void setIdNumber(String idNumber) {
this.idNumber = idNumber;
}
public Date getWorkTime() {
return workTime;
}
public void setWorkTime(Date workTime) {
this.workTime = workTime;
}
public Date getLeaveTime() {
return leaveTime;
}
public void setLeaveTime(Date leaveTime) {
this.leaveTime = leaveTime;
}
public Date getBornDate() {
return bornDate;
}
public void setBornDate(Date bornDate) {
this.bornDate = bornDate;
}
public String getInfo() {
return info;
}
public void setInfo(String info) {
this.info = info;
}
}
员工接口层:
package com.imooc.sm.dao;
import com.imooc.sm.entity.Staff;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository("staffDao")
public interface StaffDao {
void insert(Staff staff);
void delete(Integer id);
void update(Staff staff);
Staff selectById(Integer id);
List<Staff> selectAll();
}
staffDao.xml:至此,持久层定义成功
<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.4//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.imooc.sm.dao.StaffDao">
<resultMap id="resultMap" type="Staff">
<id property="id" column="id" javaType="Integer"/>
<result property="account" column="account" javaType="String"/>
<result property="password" column="password" javaType="String"/>
<result property="status" column="status" javaType="String"/>
<result property="did" column="did" javaType="Integer"/>
<result property="name" column="name" javaType="String"/>
<result property="sex" column="sex" javaType="String"/>
<result property="idNumber" column="id_number" javaType="String"/>
<result property="workTime" column="work_time" javaType="java.util.Date"/>
<result property="leaveTime" column="leave_time" javaType="java.util.Date"/>
<result property="bornDate" column="born_date" javaType="java.util.Date"/>
<result property="info" column="info" javaType="String"/>
<!-- 配置获得所属部门-->
<association property="department" column="did" javaType="Department"
select="com.imooc.sm.dao.DepartmentDao.selectById"/>
</resultMap>
<!-- 调用的是自增主键,所以使用参数useGeneratedKeys-->
<insert id="insert" parameterType="Staff" useGeneratedKeys="true">
insert into staff(account,password,status,did,name,sex,id_number,work_time,leave_time,born_date,info)
values (#{account},#{password},#{status},#{did},#{name},#{sex},#{idNumber},#{workTime},#{leaveTime},#{bornDate},#{info})
</insert>
<delete id="delete" parameterType="Integer">
delete from staff where id=#{id}
</delete>
<update id="update" parameterType="Staff">
update staff set account=#{account},password=#{password},status=#{status},
did=#{did},name=#{name},sex=#{sex},id_number=#{idNumber},
work_time=#{workTime},leave_time=#{leaveTime},born_date=#{bornDate},info=#{info}
where id=#{id}
</update>
<select id="selectById" parameterType="Integer" resultMap="resultMap">
select * from staff where id=#{id}
</select>
<select id="selectAll" resultMap="resultMap">
select * from staff
</select>
</mapper>
开始定义员工业务层:StaffService:
package com.imooc.sm.service;
import com.imooc.sm.entity.Department;
import com.imooc.sm.entity.Staff;
import java.util.List;
public interface StaffService {
void add(Staff staff);
void remove(Integer id);
void edit(Staff staff);
Staff get(Integer id);
List<Staff> getAll();
}
员工业务层实现类: StaffServiceImpl:
package com.imooc.sm.service.impl;
import com.imooc.sm.dao.StaffDao;
import com.imooc.sm.entity.Staff;
import com.imooc.sm.service.StaffService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.List;
@Service("staffService")
public class StaffServiceImpl implements StaffService {
@Autowired
private StaffDao staffDao;
public void add(Staff staff) {
staff.setPassword("123456");
staff.setWorkTime(new Date());
staff.setStatus("正常");
staffDao.insert(staff);
}
public void remove(Integer id) {
staffDao.delete(id);
}
public void edit(Staff staff) {
staffDao.update(staff);
}
public Staff get(Integer id) {
return staffDao.selectById(id);
}
public List<Staff> getAll() {
return staffDao.selectAll();
}
}
StaffController:
package com.imooc.sm.controller;
import com.imooc.sm.entity.Department;
import com.imooc.sm.entity.Staff;
import com.imooc.sm.service.DepartmentService;
import com.imooc.sm.service.StaffService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
@Controller("staffController")
public class StaffController {
@Autowired
private StaffService staffService;
@Autowired
private DepartmentService departmentService;
public void list(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
List<Staff> list = staffService.getAll();
request.setAttribute("LIST",list);
request.getRequestDispatcher("../staff_list.jsp").forward(request,response);
}
public void toAdd(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
List<Department> list = departmentService.getAll();
request.setAttribute("DLIST",list);
request.getRequestDispatcher("../staff_add.jsp").forward(request,response);
}
public void add(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String account = request.getParameter("account");
String name = request.getParameter("name");
String sex = request.getParameter("sex");
String idNumber = request.getParameter("idNumber");
String info =request.getParameter("info");
Date bornDate=null;
try {
bornDate = new SimpleDateFormat("yyyy-MM-dd").parse(request.getParameter("bornDate"));
} catch (ParseException e) {
e.printStackTrace();
}
Integer did = Integer.parseInt(request.getParameter("did"));
Staff staff = new Staff();
staff.setInfo(info);
staff.setBornDate(bornDate);
staff.setIdNumber(idNumber);
staff.setDid(did);
staff.setAccount(account);
staff.setName(name);
staff.setSex(sex);
staffService.add(staff);
response.sendRedirect("list.do");
}
public void toEdit(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Integer id = Integer.parseInt(request.getParameter("id"));
Staff staff = staffService.get(id);
request.setAttribute("OBJ",staff);
List<Department> list = departmentService.getAll();
request.setAttribute("DLIST",list);
request.getRequestDispatcher("../staff_edit.jsp").forward(request,response);
}
public void edit(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Integer id = Integer.parseInt(request.getParameter("id"));
String account = request.getParameter("account");
String name = request.getParameter("name");
String sex = request.getParameter("sex");
String idNumber = request.getParameter("idNumber");
String info =request.getParameter("info");
Date bornDate=null;
try {
bornDate = new SimpleDateFormat("yyyy-MM-dd").parse(request.getParameter("bornDate"));
} catch (ParseException e) {
e.printStackTrace();
}
Integer did = Integer.parseInt(request.getParameter("did"));
Staff staff = staffService.get(id);
staff.setInfo(info);
staff.setBornDate(bornDate);
staff.setIdNumber(idNumber);
staff.setDid(did);
staff.setAccount(account);
staff.setName(name);
staff.setSex(sex);
staffService.edit(staff);
response.sendRedirect("list.do");
}
public void remove(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Integer id = Integer.parseInt(request.getParameter("id"));
staffService.remove(id);
response.sendRedirect("list.do");
}
public void detail(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Integer id = Integer.parseInt(request.getParameter("id"));
Staff staff = staffService.get(id);
request.setAttribute("OBJ",staff);
request.getRequestDispatcher("../staff_detail.jsp").forward(request,response);
}
}
staff_list.jsp:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>员工列表</title>
<link rel="stylesheet" type="text/css" href="../css/reset.css"/>
<link rel="stylesheet" type="text/css" href="../css/common.css"/>
<link rel="stylesheet" type="text/css" href="../css/thems.css">
<script type="text/javascript" src="../js/jquery-1.8.3.min.js"></script>
<script type="text/javascript">
$(function(){
//自适应屏幕宽度
window.onresize=function(){ location=location };
var main_h = $(window).height();
$('.hy_list').css('height',main_h-45+'px');
var search_w = $(window).width()-40;
$('.search').css('width',search_w+'px');
//$('.list_hy').css('width',search_w+'px');
});
</script>
<!--框架高度设置-->
</head>
<body onLoad="Resize();">
<div id="right_ctn">
<div class="right_m">
<div class="hy_list">
<div class="box_t">
<span class="name">员工列表</span>
</div>
<div class="space_hx"> </div>
<!--列表-->
<table cellpadding="0" cellspacing="0" class="list_hy">
<tr>
<th scope="col">姓名</th>
<th scope="col">性别</th>
<th scope="col">出生日期</th>
<th scope="col">入职时间</th>
<th scope="col">部门</th>
<th scope="col">状态</th>
<th scope="col">操作</th>
</tr>
<c:forEach items="${LIST}" var="staff">
<tr>
<td>${staff.name}</td>
<td>${staff.sex}</td>
<td><fmt:formatDate value="${staff.bornDate}" pattern="yyyy-MM-dd"/></td>
<td><fmt:formatDate value="${staff.workTime}" pattern="yyyy-MM-dd HH:mm"/> </td>
<td>${staff.department.name}</td>
<td>${staff.status}</td>
<td>
<a href="toEdit.do?id=${staff.id}" class="btn">编辑</a>
<a href="remove.do?id=${staff.id}" class="btn">删除</a>
<a href="detail.do?id=${staff.id}" class="btn">详情</a>
</td>
</tr>
</c:forEach>
</table>
<!--列表-->
<!--右边底部-->
<div class="r_foot">
<div class="r_foot_m">
<a href="toAdd.do" class="btn">添加</a>
</div>
</div>
<!--右边底部-->
</div>
<!--会议列表-->
</div>
</div>
</body>
</html>
staff_add.jsp:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=8" >
<title>添加员工</title>
<link rel="stylesheet" type="text/css" href="../css/reset.css"/>
<link rel="stylesheet" type="text/css" href="../css/common.css"/>
<link rel="stylesheet" type="text/css" href="../css/thems.css">
<script type="text/javascript" src="../js/jquery-1.8.3.min.js"></script>
<script type="text/javascript">
$(function(){
//自适应屏幕宽度
window.onresize=function(){ location=location };
var main_h = $(window).height();
$('.hy_list').css('height',main_h-45+'px');
var main_w = $(window).width();
$('.xjhy').css('width',main_w-40+'px');
});
</script>
</head>
<body onLoad="Resize();">
<div id="right_ctn">
<div class="right_m">
<div class="hy_list">
<div class="box_t">
<span class="name">添加员工</span>
</div>
<div class="space_hx"> </div>
<form action="add.do" method="post" name="addForm">
<div class="xjhy">
<!--高级配置-->
<ul class="hypz gjpz clearfix">
<li class="clearfix">
<span class="title">账户名:</span>
<div class="li_r">
<input class="chang" name="account" type="text"/>
<i>*</i>
</div>
</li>
<li class="clearfix">
<span class="title">部门:</span>
<div class="li_r">
<select name="did">
<c:forEach items="${DLIST}" var="dep">
<option value="${dep.id}">${dep.name}</option>
</c:forEach>
</select>
<i>*</i>
</div>
</li>
<li class="clearfix">
<span class="title">姓名:</span>
<div class="li_r">
<input class="chang" name="name" type="text"/>
</div>
</li>
<li class="clearfix">
<span class="title">性别:</span>
<div class="li_r">
<span class="radio">
<input name="sex" type="radio" value="男" checked="checked"/>
<em>男</em>
</span>
<span class="radio">
<input name="sex" type="radio" value="女"/>
<em>女</em>
</span>
</div>
</li>
<li class="clearfix">
<span class="title">身份证号:</span>
<div class="li_r">
<input class="chang" name="idNumber" type="text"/>
</div>
</li>
<li class="clearfix">
<span class="title">出生日期:</span>
<div class="li_r">
<input class="chang" name="bornDate" type="text"/>
</div>
</li>
<li class="clearfix">
<span class="title">备注:</span>
<div class="li_r">
<input class="chang" name="info" type="text"/>
</div>
</li>
<li class="tj_btn">
<a href="javascript:history.go(-1);" class="back">返回</a>
<a href="javascript:addForm.submit();">保存</a>
</li>
</ul>
<!--高级配置-->
</div>
</form>
</div>
</div>
</div>
</body>
</html>
staff_edit.jsp:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=8" >
<title>编辑员工</title>
<link rel="stylesheet" type="text/css" href="../css/reset.css"/>
<link rel="stylesheet" type="text/css" href="../css/common.css"/>
<link rel="stylesheet" type="text/css" href="../css/thems.css">
<script type="text/javascript" src="../js/jquery-1.8.3.min.js"></script>
<script type="text/javascript">
$(function(){
//自适应屏幕宽度
window.onresize=function(){ location=location };
var main_h = $(window).height();
$('.hy_list').css('height',main_h-45+'px');
var main_w = $(window).width();
$('.xjhy').css('width',main_w-40+'px');
});
</script>
</head>
<body onLoad="Resize();">
<div id="right_ctn">
<div class="right_m">
<div class="hy_list">
<div class="box_t">
<span class="name">编辑员工</span>
</div>
<div class="space_hx"> </div>
<form action="edit.do" method="post" name="addForm">
<input type="hidden" name="id" value="${OBJ.id}"/>
<div class="xjhy">
<!--高级配置-->
<ul class="hypz gjpz clearfix">
<li class="clearfix">
<span class="title">账户名:</span>
<div class="li_r">
<input class="chang" name="account" type="text" value="${OBJ.account}"/>
<i>*</i>
</div>
</li>
<li class="clearfix">
<span class="title">部门:</span>
<div class="li_r">
<select name="did">
<c:forEach items="${DLIST}" var="dep">
<c:if test="${OBJ.did==dep.id}">
<option value="${dep.id}" selected="selected">${dep.name}</option>
</c:if>
<c:if test="${OBJ.did!=dep.id}">
<option value="${dep.id}">${dep.name}</option>
</c:if>
</c:forEach>
</select>
<i>*</i>
</div>
</li>
<li class="clearfix">
<span class="title">姓名:</span>
<div class="li_r">
<input class="chang" name="name" type="text" value="${OBJ.name}"/>
</div>
</li>
<li class="clearfix">
<span class="title">性别:</span>
<div class="li_r">
<span class="radio">
<input name="sex" type="radio" value="男" checked="checked"/>
<em>男</em>
</span>
<c:if test="${OBJ.sex=='女'}">
<span class="radio">
<input name="sex" type="radio" value="女" checked="checked"/>
<em>女</em>
</span>
</c:if>
<c:if test="${OBJ.sex!='女'}">
<span class="radio">
<input name="sex" type="radio" value="女"/>
<em>女</em>
</span>
</c:if>
</div>
</li>
<li class="clearfix">
<span class="title">身份证号:</span>
<div class="li_r">
<input class="chang" name="idNumber" type="text" value="${OBJ.idNumber}"/>
</div>
</li>
<li class="clearfix">
<span class="title">出生日期:</span>
<div class="li_r">
<input class="chang" name="bornDate" type="text" value="<fmt:formatDate value="${OBJ.bornDate}" pattern="yyyy-MM-dd"/>"/>
</div>
</li>
<li class="clearfix">
<span class="title">备注:</span>
<div class="li_r">
<input class="chang" name="info" type="text" value="${OBJ.info}"/>
</div>
</li>
<li class="tj_btn">
<a href="javascript:history.go(-1);" class="back">返回</a>
<a href="javascript:addForm.submit();">保存</a>
</li>
</ul>
<!--高级配置-->
</div>
</form>
</div>
</div>
</div>
</body>
</html>
staff_detail.jsp:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=8" >
<title>员工信息</title>
<link rel="stylesheet" type="text/css" href="../css/reset.css"/>
<link rel="stylesheet" type="text/css" href="../css/common.css"/>
<link rel="stylesheet" type="text/css" href="../css/thems.css">
<script type="text/javascript" src="../js/jquery-1.8.3.min.js"></script>
<script type="text/javascript">
$(function(){
//自适应屏幕宽度
window.onresize=function(){ location=location };
var main_h = $(window).height();
$('.hy_list').css('height',main_h-45+'px');
var main_w = $(window).width();
$('.xjhy').css('width',main_w-40+'px');
});
</script>
</head>
<body onLoad="Resize();">
<div id="right_ctn">
<div class="right_m">
<div class="hy_list">
<div class="box_t">
<span class="name">员工信息</span>
</div>
<div class="space_hx"> </div>
<div class="xjhy">
<!--高级配置-->
<ul class="hypz gjpz clearfix">
<li class="clearfix">
<span class="title">账户名:</span>
<div class="li_r">${OBJ.account}</div>
</li>
<li class="clearfix">
<span class="title">状态:</span>
<div class="li_r">${OBJ.status}</div>
</li>
<li class="clearfix">
<span class="title">部门:</span>
<div class="li_r">${OBJ.department.name}</div>
</li>
<li class="clearfix">
<span class="title">姓名:</span>
<div class="li_r">${OBJ.account}</div>
</li>
<li class="clearfix">
<span class="title">性别:</span>
<div class="li_r">${OBJ.sex}</div>
</li>
<li class="clearfix">
<span class="title">身份证号:</span>
<div class="li_r">${OBJ.idNumber}</div>
</li>
<li class="clearfix">
<span class="title">出生日期:</span>
<div class="li_r">
<fmt:formatDate value="${OBJ.bornDate}" pattern="yyyy-MM-dd"/>
</div>
</li>
<li class="clearfix">
<span class="title">入职时间:</span>
<div class="li_r">
<fmt:formatDate value="${OBJ.workTime}" pattern="yyyy-MM-dd hh:mm"/>
</div>
</li>
<li class="clearfix">
<span class="title">离职时间:</span>
<div class="li_r">
<fmt:formatDate value="${OBJ.leaveTime}" pattern="yyyy-MM-dd hh:mm"/>
</div>
</li>
<li class="clearfix">
<span class="title">备注:</span>
<div class="li_r">${OBJ.info}</div>
</li>
<li class="tj_btn">
<a href="javascript:history.go(-1);" class="back">返回</a>
</li>
</ul>
<!--高级配置-->
</div>
</div>
</div>
</div>
</body>
</html>
测试:
员工列表页:
员工添加页:
添加成功:
详情页:
员工编辑页:
编辑成功:
再次查看详情页:
登陆与个人中心实现:
登陆与个人中心实现--业务:
持久层实现:
SelfDao:
package com.imooc.sm.dao;
import com.imooc.sm.entity.Staff;
import org.springframework.stereotype.Repository;
@Repository("selfDao")
public interface SelfDao {
Staff selectByAccount(String account);
}
SelfDao.xml:
<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.4//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.imooc.sm.dao.SelfDao">
<select id="selectByAccount" parameterType="String" resultMap="com.imooc.sm.dao.StaffDao.resultMap">
select * from staff where account=#{account}
</select>
</mapper>
业务层实现:
SelfService:
package com.imooc.sm.service;
import com.imooc.sm.entity.Staff;
public interface SelfService {
//登陆
Staff login(String account, String password);
//修改密码
void changePassword(Integer id, String password);
}
SelfServiceImpl:
package com.imooc.sm.service.impl;
import com.imooc.sm.dao.SelfDao;
import com.imooc.sm.dao.StaffDao;
import com.imooc.sm.entity.Staff;
import com.imooc.sm.service.SelfService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service("selfService")
public class SelfServiceImpl implements SelfService {
@Autowired
private SelfDao selfDao;
@Autowired
private StaffDao staffDao;
public Staff login(String account, String password) {
Staff staff =selfDao.selectByAccount(account);
if(staff==null)return null;
if(staff.getPassword().equals(password))return staff;
return null;
}
public void changePassword(Integer id, String password) {
Staff staff = staffDao.selectById(id);
staff.setPassword(password);
staffDao.update(staff);
}
}
至此,业务层实现成功。
登陆与个人中心实现--界面(登陆):
login.jsp:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>登录</title>
<link rel="stylesheet" type="text/css" href="css/reset.css"/>
<link rel="stylesheet" type="text/css" href="css/common.css"/>
<link rel="stylesheet" type="text/css" href="css/thems.css"/>
<script type="text/javascript" src="js/jquery-1.8.3.min.js"></script>
<!--框架高度设置-->
<script type="text/javascript">
$(function(){
//自适应屏幕宽度
window.onresize=function(){ location=location };
var w_height=$(window).height();
$('.bg_img').css('height',w_height+'px');
var bg_wz=1920-$(window).width();
$('.bg_img img').css('margin-left','-'+bg_wz/2+'px')
$('.language .lang').click(function(){
$(this).siblings('.lang_ctn').toggle();
});
})
</script>
<!--框架高度设置-->
</head>
<body>
<!--登录-->
<div class="login">
<div class="bg_img"><img src="images/login_bg.jpg"/></div>
<div class="logo">
<a href=""><img src="images/logo.png" alt=""/></a>
</div>
<div class="login_m">
<form action="login.do" method="post" name="login_form">
<ul>
<li class="wz">用户名</li>
<li><input name="account" type="text"></li>
<li class="wz">密码</li>
<li><input name="password" type="password"></li>
<li class="l_btn">
<a href="javascript:login_form.submit();">登录</a>
</li>
</ul>
</form>
</div>
</div>
<!--登录-->
</body>
</html>
index.jsp:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>人员管理系统</title>
</head>
<frameset rows="85,*" cols="*" frameborder="no" border="0" framespacing="0">
<frame src="top.jsp" name="topFrame" scrolling="no">
<frameset cols="250,*" name="btFrame" frameborder="NO" border="0" framespacing="0">
<frame src="left.jsp" noresize name="menu" scrolling="yes">
<frame src="self/info.do" class="frame_r" noresize name="main" scrolling="yes">
</frameset>
</frameset>
<noframes>
<body>您的浏览器不支持框架!</body>
</noframes>
</html>
top.jsp:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>头部</title>
<link rel="stylesheet" type="text/css" href="css/reset.css"/>
<link rel="stylesheet" type="text/css" href="css/common.css"/>
</head>
<body>
<div class="head clearfix">
<div class="logo"><a href="#"><img src="images/logo.png" alt="慕课商城"/></a></div>
<div class="curr"><span>欢迎您,${USER.name}[ <a href="logout.do" target="_top">退出</a> ]</span></div>
</div>
</body>
</html>
left.jsp:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=8" >
<title>左边导航</title>
<link rel="stylesheet" type="text/css" href="css/reset.css"/>
<link rel="stylesheet" type="text/css" href="css/common.css"/>
<script type="text/javascript" src="js/jquery-1.8.3.min.js"></script>
<!--框架高度设置-->
<script type="text/javascript">
$(function(){
$('.sidenav li').click(function(){
$(this).siblings('li').removeClass('now');
$(this).addClass('now');
});
$('.erji li').click(function(){
$(this).siblings('li').removeClass('now_li');
$(this).addClass('now_li');
});
var main_h = $(window).height();
$('.sidenav').css('height',main_h+'px');
})
</script>
<!--框架高度设置-->
</head>
<body>
<div id="left_ctn">
<ul class="sidenav">
<li>
<div class="nav_m">
<span><a>人员管理</a></span>
<i> </i>
</div>
<ul class="erji">
<li>
<span><a href="staff/list.do" target="main">员工管理</a></span>
</li>
<li>
<span><a href="department/list.do" target="main">部门管理</a></span>
</li>
</ul>
</li>
<li>
<div class="nav_m">
<span><a>日志信息</a></span>
<i> </i>
</div>
<ul class="erji">
<li>
<span><a href="log/operationLog.do" target="main">操作日志</a></span>
</li>
<li>
<span><a href="log/loginLog.do" target="main">登陆日志</a></span>
</li>
<li>
<span><a href="log/systemLog.do" target="main">系统日志</a></span>
</li>
</ul>
</li>
<li class="now">
<div class="nav_m">
<span><a>个人中心</a></span>
<i> </i>
</div>
<ul class="erji">
<li>
<span><a href="self/info.do" target="main">个人信息</a></span>
</li>
<li>
<span><a href="self/toChangePassword.do" target="main">修改密码</a></span>
</li>
</ul>
</li>
<li>
<div class="nav_m">
<span><a href="logout.do" target="_top">退出系统</a></span>
</div>
</li>
</ul>
</div>
</body>
</html>
SelfController:
package com.imooc.sm.controller;
import com.imooc.sm.entity.Staff;
import com.imooc.sm.service.SelfService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
@Controller("selfController")
public class SelfController {
@Autowired
private SelfService selfService;
// /toLogin.do
public void toLogin(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.getRequestDispatcher("login.jsp").forward(request,response);
}
// /login.do
public void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String account =request.getParameter("account");
String password = request.getParameter("password");
Staff staff = selfService.login(account,password);
if(staff==null){
response.sendRedirect("toLogin.do");
}else{
HttpSession session = request.getSession();
session.setAttribute("USER",staff);
response.sendRedirect("main.do");
}
}
// /logout.do
public void logout(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession();
session.setAttribute("USER", null);
response.sendRedirect("toLogin.do");
}
// /main.do
public void main(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.getRequestDispatcher("index.jsp").forward(request,response);
}
// /self/info.do
public void info(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.getRequestDispatcher("../info.jsp").forward(request,response);
}
// /self/toChangePassword.do
public void toChangePassword(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.getRequestDispatcher("../change_password.jsp").forward(request,response);
}
// /self/changePassword.do
public void changePassword(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String password = request.getParameter("password");
String password1 = request.getParameter("password1");
HttpSession session = request.getSession();
Staff staff = (Staff)session.getAttribute("USER");
if(!staff.getPassword().equals(password)){
response.sendRedirect("toChangePassword.do");
}else{
selfService.changePassword(staff.getId(),password1);
//response.sendRedirect("../logout.do");
response.getWriter().print("<script type=\"text/javascript\">parent.location.href=\"../logout.do\"</script>");
}
}
}
LoginFilter:登陆过滤器
package com.imooc.sm.global;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
public class LoginFilter implements Filter {
public void init(FilterConfig filterConfig) throws ServletException {
}
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest request=(HttpServletRequest)servletRequest;
HttpServletResponse response = (HttpServletResponse)servletResponse;
String path = request.getServletPath();
if(path.toLowerCase().indexOf("login")!=-1){
filterChain.doFilter(request,response);
}else{
HttpSession session = request.getSession();
Object obj =session.getAttribute("USER");
if(obj!=null){
filterChain.doFilter(request,response);
}else{
response.sendRedirect(request.getContextPath()+"/toLogin.do");
}
}
}
public void destroy() {
}
}
在web.xml配置登陆过滤器,拦截所有的jsp页面和do页面:
<!-- 配置登陆过滤器-->
<filter>
<filter-name>Login</filter-name>
<filter-class>com.imooc.sm.global.LoginFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>Login</filter-name>
<url-pattern>*.jsp</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>Login</filter-name>
<url-pattern>*.do</url-pattern>
</filter-mapping>
实现结果:
登陆与个人中心实现(个人中心):
info.jsp:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=8" >
<title>个人信息</title>
<link rel="stylesheet" type="text/css" href="../css/reset.css"/>
<link rel="stylesheet" type="text/css" href="../css/common.css"/>
<link rel="stylesheet" type="text/css" href="../css/thems.css">
<script type="text/javascript" src="../js/jquery-1.8.3.min.js"></script>
<script type="text/javascript">
$(function(){
//自适应屏幕宽度
window.onresize=function(){ location=location };
var main_h = $(window).height();
$('.hy_list').css('height',main_h-45+'px');
var main_w = $(window).width();
$('.xjhy').css('width',main_w-40+'px');
});
</script>
</head>
<body onLoad="Resize();">
<div id="right_ctn">
<div class="right_m">
<div class="hy_list">
<div class="box_t">
<span class="name">个人信息</span>
</div>
<div class="space_hx"> </div>
<div class="xjhy">
<!--高级配置-->
<ul class="hypz gjpz clearfix">
<li class="clearfix">
<span class="title">账户名:</span>
<div class="li_r">${USER.account}</div>
</li>
<li class="clearfix">
<span class="title">状态:</span>
<div class="li_r">${USER.status}</div>
</li>
<li class="clearfix">
<span class="title">部门:</span>
<div class="li_r">${USER.department.name}</div>
</li>
<li class="clearfix">
<span class="title">姓名:</span>
<div class="li_r">${USER.account}</div>
</li>
<li class="clearfix">
<span class="title">性别:</span>
<div class="li_r">${USER.sex}</div>
</li>
<li class="clearfix">
<span class="title">身份证号:</span>
<div class="li_r">${USER.idNumber}</div>
</li>
<li class="clearfix">
<span class="title">出生日期:</span>
<div class="li_r">
<fmt:formatDate value="${USER.bornDate}" pattern="yyyy-MM-dd"/>
</div>
</li>
<li class="clearfix">
<span class="title">入职时间:</span>
<div class="li_r">
<fmt:formatDate value="${USER.workTime}" pattern="yyyy-MM-dd hh:mm"/>
</div>
</li>
<li class="clearfix">
<span class="title">离职时间:</span>
<div class="li_r">
<fmt:formatDate value="${USER.leaveTime}" pattern="yyyy-MM-dd hh:mm"/>
</div>
</li>
<li class="clearfix">
<span class="title">备注:</span>
<div class="li_r">${USER.info}</div>
</li>
</ul>
<!--高级配置-->
</div>
</div>
</div>
</div>
</body>
</html>
change_password.jsp:更改密码
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=8" >
<title>修改密码</title>
<link rel="stylesheet" type="text/css" href="../css/reset.css"/>
<link rel="stylesheet" type="text/css" href="../css/common.css"/>
<link rel="stylesheet" type="text/css" href="../css/thems.css">
<script type="text/javascript" src="../js/jquery-1.8.3.min.js"></script>
<script type="text/javascript">
$(function(){
//自适应屏幕宽度
window.onresize=function(){ location=location };
var main_h = $(window).height();
$('.hy_list').css('height',main_h-45+'px');
var main_w = $(window).width();
$('.xjhy').css('width',main_w-40+'px');
});
</script>
</head>
<body onLoad="Resize();">
<div id="right_ctn">
<div class="right_m">
<div class="hy_list">
<div class="box_t">
<span class="name">修改密码</span>
</div>
<div class="space_hx"> </div>
<form action="changePassword.do" method="post" name="addForm">
<div class="xjhy">
<!--高级配置-->
<ul class="hypz gjpz clearfix">
<li class="clearfix">
<span class="title">账户名:</span>
<div class="li_r">${USER.account}</div>
</li>
<li class="clearfix">
<span class="title">原始密码:</span>
<div class="li_r">
<input class="chang" name="password" type="password"/>
</div>
</li>
<li class="clearfix">
<span class="title">新密码:</span>
<div class="li_r">
<input class="chang" name="password1" type="password"/>
</div>
</li>
<li class="tj_btn">
<a href="javascript:history.go(-1);" class="back">返回</a>
<a href="javascript:addForm.submit();">保存</a>
</li>
</ul>
<!--高级配置-->
</div>
</form>
</div>
</div>
</div>
</body>
</html>
测试结果:
日志处理:
日志处理实现--业务:
Log实体类:
package com.imooc.sm.entity;
import java.util.Date;
public class Log {
private Date oprTime;
private String type;
private String operator;
private String moudle;
private String operation;
private String result;
public Date getOprTime() {
return oprTime;
}
public void setOprTime(Date oprTime) {
this.oprTime = oprTime;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getOperator() {
return operator;
}
public void setOperator(String operator) {
this.operator = operator;
}
public String getMoudle() {
return moudle;
}
public void setMoudle(String moudle) {
this.moudle = moudle;
}
public String getOperation() {
return operation;
}
public void setOperation(String operation) {
this.operation = operation;
}
public String getResult() {
return result;
}
public void setResult(String result) {
this.result = result;
}
}
LogDao:
package com.imooc.sm.dao;
import com.imooc.sm.entity.Log;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository("logDao")
public interface LogDao {
void insert(Log log);
List<Log> selectByType(String type);
}
LogDao.xml:映射文件
<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.4//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.imooc.sm.dao.LogDao">
<resultMap id="resultMap" type="Log">
<result property="oprTime" column="opr_time" javaType="java.util.Date"/>
<result property="type" column="type" javaType="String"/>
<result property="operator" column="operator" javaType="String"/>
<result property="moudle" column="moudle" javaType="String"/>
<result property="operation" column="operation" javaType="String"/>
<result property="result" column="result" javaType="String"/>
</resultMap>
<insert id="insert" parameterType="Log">
insert into log values(#{oprTime},#{type},#{operator},#{moudle},#{operation},#{result});
</insert>
<select id="selectByType" parameterType="String" resultMap="resultMap">
select * from log where type=#{type} order by opr_time desc
</select>
</mapper>
日志持久层实现成功。
日志业务层:
LogService:
package com.imooc.sm.service;
import com.imooc.sm.entity.Log;
import java.util.List;
public interface LogService {
void addSystemLog(Log log);
void addLoginLog(Log log);
void addOperationLog(Log log);
List<Log> getSystemLog();
List<Log> getLoginLog();
List<Log> getOperationLog();
}
LogServiceImpl:
package com.imooc.sm.service.impl;
import com.imooc.sm.dao.LogDao;
import com.imooc.sm.entity.Log;
import com.imooc.sm.service.LogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.List;
@Service("logService")
public class LogServiceImpl implements LogService {
@Autowired
private LogDao logDao;
public void addSystemLog(Log log) {
log.setOprTime(new Date());
log.setType("system");
logDao.insert(log);
}
public void addLoginLog(Log log) {
log.setOprTime(new Date());
log.setType("login");
logDao.insert(log);
}
public void addOperationLog(Log log) {
log.setOprTime(new Date());
log.setType("operation");
logDao.insert(log);
}
public List<Log> getSystemLog() {
return logDao.selectByType("system");
}
public List<Log> getLoginLog() {
return logDao.selectByType("login");
}
public List<Log> getOperationLog() {
return logDao.selectByType("operation");
}
}
日志业务层实现。
在业务层注册全局LogService:
package com.imooc.sm.global;
import com.imooc.sm.entity.Log;
import com.imooc.sm.entity.Staff;
import com.imooc.sm.service.LogService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
@Component
@Aspect
public class LogAdvice {
@Autowired
private LogService logService;
@AfterReturning("execution(* com.imooc.sm.controller.*.*(..)) && !execution(* com.imooc.sm.controller.SelfController.*(..)) && !execution(* com.imooc.sm.controller.*.to*(..))")
public void operationLog(JoinPoint joinPoint){
Log log = new Log();
log.setMoudle(joinPoint.getTarget().getClass().getSimpleName());
log.setOperation(joinPoint.getSignature().getName());
HttpServletRequest request =(HttpServletRequest) joinPoint.getArgs()[0];
HttpSession session = request.getSession();
Object obj = session.getAttribute("USER");
Staff staff =(Staff)obj;
log.setOperator(staff.getAccount());
log.setResult("成功");
logService.addOperationLog(log);
}
@AfterThrowing(throwing ="e",pointcut ="execution(* com.imooc.sm.controller.*.*(..)) && !execution(* com.imooc.sm.controller.SelfController.*(..))")
public void systemLog(JoinPoint joinPoint,Throwable e){
Log log = new Log();
log.setMoudle(joinPoint.getTarget().getClass().getSimpleName());
log.setOperation(joinPoint.getSignature().getName());
HttpServletRequest request =(HttpServletRequest) joinPoint.getArgs()[0];
HttpSession session = request.getSession();
Object obj = session.getAttribute("USER");
Staff staff =(Staff)obj;
log.setOperator(staff.getAccount());
log.setResult(e.getClass().getSimpleName());
logService.addSystemLog(log);
}
@After("execution(* com.imooc.sm.controller.SelfController.login(..))")
public void loginLog(JoinPoint joinPoint){
log(joinPoint);
}
@Before("execution(* com.imooc.sm.controller.SelfController.logout(..))")
public void logoutLog(JoinPoint joinPoint){
log(joinPoint);
}
private void log(JoinPoint joinPoint){
Log log = new Log();
log.setMoudle(joinPoint.getTarget().getClass().getSimpleName());
log.setOperation(joinPoint.getSignature().getName());
HttpServletRequest request =(HttpServletRequest) joinPoint.getArgs()[0];
HttpSession session = request.getSession();
Object obj = session.getAttribute("USER");
if(obj==null){
log.setOperator(request.getParameter("account"));
log.setResult("失败");
}else {
Staff staff = (Staff) obj;
log.setOperator(staff.getAccount());
log.setResult("成功");
}
logService.addLoginLog(log);
}
}
日志处理实现--查看:
LogController:
package com.imooc.sm.controller;
import com.imooc.sm.entity.Department;
import com.imooc.sm.entity.Log;
import com.imooc.sm.service.LogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
@Controller("logController")
public class LogController {
@Autowired
private LogService logService;
public void operationLog(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
List<Log> list = logService.getOperationLog();
request.setAttribute("LIST",list);
request.setAttribute("TYPE","操作");
request.getRequestDispatcher("../log_list.jsp").forward(request,response);
}
public void loginLog(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
List<Log> list = logService.getLoginLog();
request.setAttribute("LIST",list);
request.setAttribute("TYPE","登陆");
request.getRequestDispatcher("../log_list.jsp").forward(request,response);
}
public void systemLog(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
List<Log> list = logService.getSystemLog();
request.setAttribute("LIST",list);
request.setAttribute("TYPE","系统");
request.getRequestDispatcher("../log_list.jsp").forward(request,response);
}
}
log_list.jsp:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>${TYPE}日志</title>
<link rel="stylesheet" type="text/css" href="../css/reset.css"/>
<link rel="stylesheet" type="text/css" href="../css/common.css"/>
<link rel="stylesheet" type="text/css" href="../css/thems.css">
<script type="text/javascript" src="../js/jquery-1.8.3.min.js"></script>
<script type="text/javascript">
$(function(){
//自适应屏幕宽度
window.onresize=function(){ location=location };
var main_h = $(window).height();
$('.hy_list').css('height',main_h-45+'px');
var search_w = $(window).width()-40;
$('.search').css('width',search_w+'px');
//$('.list_hy').css('width',search_w+'px');
});
</script>
<!--框架高度设置-->
</head>
<body onLoad="Resize();">
<div id="right_ctn">
<div class="right_m">
<div class="hy_list">
<div class="box_t">
<span class="name">${TYPE}日志</span>
</div>
<div class="space_hx"> </div>
<!--列表-->
<table cellpadding="0" cellspacing="0" class="list_hy">
<tr>
<th scope="col">操作时间</th>
<th scope="col">操作员</th>
<th scope="col">模块</th>
<th scope="col">操作</th>
<th scope="col">结果</th>
</tr>
<c:forEach items="${LIST}" var="log">
<tr>
<td><fmt:formatDate value="${log.oprTime}" pattern="yyyy-MM-dd HH:mm:ss"/></td>
<td>${log.operator}</td>
<td>${log.moudle}</td>
<td>${log.operation}</td>
<td>${log.result}</td>
</tr>
</c:forEach>
</table>
<!--列表-->
</div>
<!--会议列表-->
</div>
</div>
</body>
</html>