SpringBoot+mybatis教师管理系统
全部复制时,springBoot不会立即响应需要重启
导入mybatis依赖
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.8</version>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.0</version>
</dependency>
项目结构
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.url=jdbc:mysql://localhost:3306/company?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.thymeleaf.cache=false
spring.messages.basename=i18n.login
spring.mvc.date-format=yyyy-MM-dd
#整合mybatis
mybatis.type-aliases-package=com.ji.pojo
#注册mapper文件
mybatis.mapper-locations=classpath:mybatis/mapper/*.xml
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
# druid参数调优(可选)
# 初始化大小,最小,最大
spring.datasource.druid.initial-size=5
spring.datasource.druid.min-idle=5
spring.datasource.druid.max-active=20
# 配置获取连接等待超时的时间
spring.datasource.druid.max-wait=60000
# 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
spring.datasource.druid.time-between-eviction-runs-millis=60000
# 配置一个连接在池中最小生存的时间,单位是毫秒
spring.datasource.druid.min-evictable-idle-time-millis=300000
# 测试连接
# spring.datasource.druid.validation-query=select 'x'
spring.datasource.druid.validationQuery=SELECT 1 FROM DUAL
spring.datasource.druid.test-while-idle=true
spring.datasource.druid.test-on-borrow=false
spring.datasource.druid.test-on-return=false
# 打开PSCache,并且指定每个连接上PSCache的大小
spring.datasource.druid.pool-prepared-statements=true
spring.datasource.druid.max-pool-prepared-statement-per-connection-size=20
# 配置监控统计拦截的filters
spring.datasource.druid.filters=stat,wall,log4j
spring.datasource.druid.maxPoolPreparedStatementPerConnectionSize=20
spring.datasource.druid.useGlobalDataSourceStat=true
connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
Druid配置文件
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.servlet.Filter;
import javax.servlet.ServletRegistration;
import javax.sql.DataSource;
import java.util.HashMap;
@Configuration
public class DruidConfig{
@ConfigurationProperties(prefix = "spring.datasource")
@Bean
public DataSource druidDataSource(){
return new DruidDataSource ();
}
//后台监控 web.xml
//因为SpringBoot内置了Servlet容器所有没有web.xml,替代方法ServletRegistrationBean
@Bean
public ServletRegistrationBean statViewServlet(){
//后台需要有人登录账号密码
HashMap<String, String> initParams = new HashMap<> ();
ServletRegistrationBean<StatViewServlet> bean = new ServletRegistrationBean<> (new StatViewServlet (), "/druid/*");
//增加配置
initParams.put ("loginUsername","admin"); //登录key是固定的
initParams.put ("loginPassword","123456");
//允许谁可以访问
initParams.put ("allow","");//""谁都可以访问
//禁止谁能访问呢
//initParams.put ("jsp","ip地址")
bean.setInitParameters (initParams);//设置初始化参数
return bean;
}
//filter 过滤器
@Bean
public FilterRegistrationBean webStartFilter(){
FilterRegistrationBean<Filter> bean = new FilterRegistrationBean<> ();
bean.setFilter (new WebStatFilter ());
//可以过滤那些请求
HashMap<String, String> initParams = new HashMap<> ();
initParams.put ("exclusions","*.js,*.css,/druid/*");//这些东西不通行
return bean;
}
}
自定义拦截器配置
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class LoginHandlerInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//登陆成功之后应该有用户的session
Object session = request.getSession ().getAttribute ("loginUser");
if(session==null)
{
request.setAttribute ("msg","没有权限,先登录");
request.getRequestDispatcher ("/index.html").forward (request,response);
return false;
}
else{
return true;
}
}
}
自定义视图解析器
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.LocaleResolver;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Locale;
public class MyLocaleResolver implements LocaleResolver {
//解析请求
@Override
public Locale resolveLocale(HttpServletRequest request) {
//获取请求中的语言参数
String l = request.getParameter ("l");
Locale locale = new Locale("en","US"); //默认情况如果没有就使用默认情况
//如果请求连接携带了参数,就需要判断
if (!StringUtils.isEmpty (l)) {
String[] s = l.split ("_");
//国家,地区
return new Locale (s[0], s[1]);
}
return locale;
}
@Override
public void setLocale(HttpServletRequest request, HttpServletResponse response, Locale locale) {
}
}
springMVC配置
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController ("/").setViewName ("index");
registry.addViewController ("/index.html").setViewName ("index");
registry.addViewController ("/main.html").setViewName ("dashboard");
}
@Bean
public LocaleResolver localeResolver(){
return new MyLocaleResolver ();
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor (new LoginHandlerInterceptor ()).addPathPatterns ("/**").excludePathPatterns ("/index.html","/","/user/login","/css/*","/js/**","/img/**");
}
}
Pojo层
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
//部门表
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Department {
private Integer id;
private String departmentName;
}
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.Date;
//员工表
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Employee {
private Integer id;
private String lastName;
private String email;
private Integer gender; //0女 1男
private Date birth;
private Department department;
}
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
//部门表
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Department {
private Integer id;
private String departmentName;
}
dao层
import com.ji.pojo.User;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;
import java.util.List;
@Mapper
@Repository
public interface UserMapper {
int addUser(User user);
int deleteUser(int id);
int updateUser(User user);
User queryUser(String username);
User queryUserById(int id);
List<User> queryAllUser();
}
<?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.ji.dao.UserMapper">
<insert id="addUser" parameterType="com.ji.pojo.User">
insert into`user`(`id`,`username`,`password`)
values (#{id},#{username},#{password})
</insert>
<delete id="deleteUser" parameterType="int">
delete from `user`
where `id`=#{id}
</delete>
<update id="updateUser" parameterType="com.ji.pojo.User">
update `user` set `password`=#{password}
where `id`=#{id} and `username`=#{username}
</update>
<select id="queryUser" parameterType="String" resultType="com.ji.pojo.User">
select * from `user`
where `username`=#{username}
</select>
<select id="queryAllUser" resultType="com.ji.pojo.User">
select * from `user`
</select>
<select id="queryUserById" resultType="com.ji.pojo.User" parameterType="int">
select * from `user`
where `id`=#{id}
</select>
</mapper>
import com.ji.pojo.Department;
import com.ji.pojo.Employee;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;
import java.util.List;
@Mapper
@Repository
public interface EmployeeMapper {
int addEmployee(Employee employee);
int deleteEmployee(int id);
int updateEmployee(Employee employee);
List<Employee> queryAllEmployee();
Employee queryEmployee(int id);
}
<?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.ji.dao.EmployeeMapper">
<insert id="addEmployee" parameterType="com.ji.pojo.Employee">
insert into`employee`(`id`,`lastName`,`email`,`gender`,`birth`,`departmentId`)
values (#{id},#{lastName},#{email},#{gender},#{birth},#{department.id})
</insert>
<delete id="deleteEmployee" parameterType="int">
delete from `employee`
where id=#{id}
</delete>
<update id="updateEmployee" parameterType="com.ji.pojo.Employee">
update `employee` set `lastName`=#{lastName},`email`=#{email},`gender`=#{gender},`birth`=#{birth},`departmentId`=#{department.id}
where id=#{id}
</update>
<resultMap id="queryAll" type="com.ji.pojo.Employee">
<result property="id" column="id"/>
<result property="lastName" column="lastName"/>
<result property="email" column="email"/>
<result property="gender" column="gender"/>
<result property="birth" column="birth"/>
<association property="department" javaType="Department">
<result property="id" column="d_id"/>
<result property="departmentName" column="d_department"/>
</association>
</resultMap>
<select id="queryAllEmployee" resultMap="queryAll">
select e.id,e.lastName,e.email,e.gender,d.id d_id,d.departmentName d_department,e.birth
from employee as e
inner join department as d
on e.departmentId=d.id
</select>
<resultMap id="query" type="com.ji.pojo.Employee">
<result property="id" column="id"/>
<result property="lastName" column="lastName"/>
<result property="email" column="email"/>
<result property="gender" column="gender"/>
<result property="birth" column="birth"/>
<association property="department" javaType="Department">
<result property="id" column="d_id"/>
<result property="departmentName" column="d_department"/>
</association>
</resultMap>
<select id="queryEmployee" resultMap="query" parameterType="int">
select e.id,e.lastName,e.email,e.gender,d.id d_id,d.departmentName d_department,e.birth
from employee as e
inner join department as d
on e.departmentId=d.id
where e.id=#{id}
</select>
</mapper>
import com.ji.pojo.Department;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;
import java.util.List;
@Mapper
@Repository
public interface DepartmentMapper {
int addDepartment(Department department);
int deleteDepartment(int id);
int updateDepartment(Department department);
List<Department> queryAllDepartment();
Department queryDepartment(int id);
}
<?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.ji.dao.DepartmentMapper">
<insert id="addDepartment" parameterType="com.ji.pojo.Department">
insert into`department`(`id`,`departmentName`)
values (#{id},#{departmentName})
</insert>
<delete id="deleteDepartment" parameterType="int">
delete from `department`
<where>
id=#{id}
</where>
</delete>
<update id="updateDepartment" parameterType="com.ji.pojo.Department">
update `department`set`departmentName`=#{departmentName}
<where>
id=#{id}
</where>
</update>
<select id="queryDepartment" parameterType="int" resultType="com.ji.pojo.Department">
select * from `department`
<where>
id=#{id}
</where>
</select>
<select id="queryAllDepartment" resultType="com.ji.pojo.Department">
select * from `department`
</select>
</mapper>
Service层
import java.util.List;
public interface UserService {
int addUser(User user);
int deleteUser(int id);
int updateUser(User user);
User queryUser(String username);
User queryUserById(int id);
List<User> queryAllUser();
}
import com.ji.dao.UserMapper;
import com.ji.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class UserServiceImpl implements UserService{
@Autowired
private UserMapper userMapper;
@Override
public int addUser(User user) {
return userMapper.addUser (user);
}
@Override
public int deleteUser(int id) {
return userMapper.deleteUser (id);
}
@Override
public int updateUser(User user) {
return userMapper.updateUser (user);
}
@Override
public User queryUser(String username) {
return userMapper.queryUser (username);
}
@Override
public User queryUserById(int id) {
return userMapper.queryUserById (id);
}
@Override
public List<User> queryAllUser() {
return userMapper.queryAllUser ();
}
}
import com.ji.pojo.Department;
import com.ji.pojo.Employee;
import java.util.List;
public interface EmployeeService {
int addEmployee(Employee employee);
int deleteEmployee(int id);
int updateEmployee(Employee employee);
List<Employee> queryAllEmployee();
Employee queryEmployee(int id);
}
import com.ji.dao.EmployeeMapper;
import com.ji.pojo.Department;
import com.ji.pojo.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class EmployeeServiceImpl implements EmployeeService{
@Autowired
private EmployeeMapper employeeMapper;
@Override
public int addEmployee(Employee employee) {
return employeeMapper.addEmployee (employee);
}
@Override
public int deleteEmployee(int id) {
return employeeMapper.deleteEmployee (id);
}
@Override
public int updateEmployee(Employee employee) {
return employeeMapper.updateEmployee (employee);
}
@Override
public List<Employee> queryAllEmployee() {
return employeeMapper.queryAllEmployee ();
}
@Override
public Employee queryEmployee(int id) {
return employeeMapper.queryEmployee (id);
}
}
import java.util.List;
public interface DepartmentService {
int addDepartment(Department department);
int deleteDepartment(int id);
int updateDepartment(Department department);
List<Department> queryAllDepartment();
Department queryDepartment(int id);
}
import com.ji.dao.DepartmentMapper;
import com.ji.pojo.Department;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class DepartmentServiceImpl implements DepartmentService{
@Autowired
private DepartmentMapper departmentMapper;
@Override
public int addDepartment(Department department) {
return departmentMapper.addDepartment (department);
}
@Override
public int deleteDepartment(int id) {
return departmentMapper.deleteDepartment (id);
}
@Override
public int updateDepartment(Department department) {
return departmentMapper.updateDepartment (department);
}
@Override
public List<Department> queryAllDepartment() {
return departmentMapper.queryAllDepartment ();
}
@Override
public Department queryDepartment(int id) {
return departmentMapper.queryDepartment (id);
}
}
Controller层
import com.ji.dao.UserMapper;
import com.ji.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.List;
@Controller
public class UserController {
@Autowired
private UserMapper userMapper;
@RequestMapping("/users")
public String listUser(Model model){
List<User> users = userMapper.queryAllUser ();
model.addAttribute ("userList",users);
return "user/userList";
}
@GetMapping("/toadduser")
public String toaddUser(){
return "user/addUser";
}
@PostMapping("/toadduser")
public String addUser(User user){
int i = userMapper.addUser (user);
if(i>0) System.out.println ("添加成功");
else System.out.println ("添加失败");
return "redirect:/users";
}
@GetMapping("/user/{id}")
public String toUpdateUser(@PathVariable("id") int id,Model model){
User user = userMapper.queryUserById (id);
model.addAttribute ("uuser",user);
return "user/updateUser";
}
@PostMapping("/toupdateuser")
public String updateUser(User user){
int i = userMapper.updateUser (user);
if(i>0) System.out.println ("添加成功");
else System.out.println ("添加失败");
return "redirect:/users";
}
@RequestMapping("/deleuser/{id}")
public String deleteUser(@PathVariable("id") int id){
int i = userMapper.deleteUser (id);
if(i>0) System.out.println ("添加成功");
else System.out.println ("添加失败");
return "redirect:/users";
}
}
import com.ji.dao.DepartmentMapper;
import com.ji.dao.EmployeeMapper;
import com.ji.pojo.Department;
import com.ji.pojo.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.Collection;
import java.util.List;
@Controller
public class EployeeController {
@Autowired
EmployeeMapper employeeMapper;
@Autowired
DepartmentMapper departmentMapper;
@RequestMapping("/emps")
public String list(Model model){
List<Employee> all = employeeMapper.queryAllEmployee ();
model.addAttribute ("emps",all);
return "emp/list";
}
@GetMapping("/emp")
public String toAddpage(Model model){
//查出所有部门信息
List<Department> departments = departmentMapper.queryAllDepartment ();
model.addAttribute ("departments",departments);
return "emp/add";
}
@PostMapping("/emp")
public String toEmp(Employee employee){
//查出所有部门信息
System.out.println (employee);
employeeMapper.addEmployee (employee);//调用底层业务方法保存员工信息
return "redirect:/emps";
}
/*去到员工的修改页面*/
@GetMapping("/emp/{id}")
public String toUpdate(@PathVariable("id") Integer id, Model model){
//查出原来的数据
Employee employee=employeeMapper.queryEmployee (id);
model.addAttribute ("emp",employee);
List<Department> departments = departmentMapper.queryAllDepartment ();
model.addAttribute ("departments",departments);
return "/emp/update";
}
@PostMapping("/updateEmp")
public String updateEmp(Employee employee)
{
employeeMapper.updateEmployee (employee);
return "redirect:/emps";
}
@GetMapping("/delemp/{id}")
public String toDelete(@PathVariable("id") Integer id){
//查出原来的数据
employeeMapper.deleteEmployee (id);
return "redirect:/emps";
}
}
import com.ji.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import javax.servlet.http.HttpSession;
@Controller
public class LoginController {
@Autowired
private UserService userService;
@RequestMapping("/user/login")
public String login(@RequestParam("username")String username, @RequestParam("password") String password, Model model, HttpSession session){
if(username!=null&&userService.queryUser (username)!=null&&password!=null&&password.equals (userService.queryUser (username).getPassword ()))
{
session.setAttribute ("loginUser",username);
return "redirect:/main.html";
}
else{
model.addAttribute ("msg","用户名或密码错误");
return "index";
}
}
@RequestMapping("user/loginOut")
public String UserLoginOut(HttpSession session){
session.invalidate ();
return "redirect:/index.html";
}
}
代码过多不再粘贴,如需要请留言