狂神springboot员工管理系统

1.创建springboot项目,添加web依赖

  • 只能添加web依赖,不能添加jdbc,mysql,不然添加数据库配置

    测试tomcat

@RestController
public class HelloController {
    @RequestMapping("/hello")
    public String hello(){
        return "hello";
    }
}

2.导入静态资源

css,js,img放在static下,html放在templates

狂神springboot员工管理系统

导入thymeleaf依赖

<!--thymeleaf-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

使用thymeleaf修改静态页面

<html lang="en"xmlns:th="http://www.thymeleaf.org">
<link th:href="@{/css/bootstrap.min.css}" rel="stylesheet">
<!-- Custom styles for this template -->
<link th:href="@{/css/signin.css}" rel="stylesheet">

首页实现,扩展MVC,添加视图控制实现WebMvcConfigurer

//扩展MVC
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("index");
        registry.addViewController("/index.html").setViewName("index");
    }
}

3.创建对象

导入lomlok依赖

<!--        lombok-->
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
</dependency>

User

@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
    private Integer id;
    private String username;
    private String password;
}

Employee

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Employee {
    private Integer id;
    private String lastName;
    private String email;
    private Integer gender;
    private String department;
    private Date birth;
}

4.创建数据库,添加jdbc,mysql依赖,并创建application.yaml文件配置数据库

导入jdbc,mysql依赖

<!--jdbc-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
<!--        mysql-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>

创建数据库

CREATE DATABASE mydatabase;
create table `t_employee` (
	`id` int (11),
	`lastName` varchar (96),
	`email` varchar (96),
	`gender` int (32),
	`department` varchar (96),
	`birth` datetime 
); 
insert into `t_employee` (`id`, `lastName`, `email`, `gender`, `department`, `birth`) values('7','wanglichen','26735786@qq.com','1','科研部','1999-10-05 16:00:00.000000');
insert into `t_employee` (`id`, `lastName`, `email`, `gender`, `department`, `birth`) values('10','阮秀','26735786@qq.com','0','运营部','2021-10-08 16:00:00.000000');
insert into `t_employee` (`id`, `lastName`, `email`, `gender`, `department`, `birth`) values('1902','陈平安','a26735786@qq.com','1','教学部','1999-10-05 16:00:00.000000');
insert into `t_employee` (`id`, `lastName`, `email`, `gender`, `department`, `birth`) values('3525','赵晓','a26735786@qq.com','0','运营部','2021-10-08 16:00:00.000000');
insert into `t_employee` (`id`, `lastName`, `email`, `gender`, `department`, `birth`) values('9527','qingduchen','26735786@qq.com','1','科研部','1999-10-05 16:00:00.000000');



create table `t_user` (
	`id` int (11),
	`username` varchar (96),
	`password` varchar (96)
); 
insert into `t_user` (`id`, `username`, `password`) values('1','qingduchen','123456');
insert into `t_user` (`id`, `username`, `password`) values('2','admin','111111');
insert into `t_user` (`id`, `username`, `password`) values('3','root','222222');
    insert into `t_user` (`id`, `username`, `password`) values('4','yangxiqiao','333333');

配置数据库

application.yaml

spring:
  datasource:
    username: root
    password: 123456
    url: jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&userUnicode=true&characterEcoding=utf-8&useSSL=false
    driver-class-name: com.mysql.cj.jdbc.Driver

测试数据库

@SpringBootApplication
public class KuangshenSpringbootApplication {

    public static void main(String[] args) {
        SpringApplication.run(KuangshenSpringbootApplication.class, args);
    }

}

5.实现国际化

写配置文件并绑定配置文件

  #识别绑定国际化配置文件
messages:
  basename: i18n.login

index.html输出

<form class="form-signin" action="dashboard.html">
   <img class="mb-4" th:src="@{img/bootstrap-solid.svg}" alt="" width="72" height="72">
   <h1 class="h3 mb-3 font-weight-normal" th:text="#{login.tip}">Please sign in</h1>
   <label class="sr-only">Username</label>
   <input type="text" class="form-control" th:placeholder="#{login.username}" required="" autofocus="">
   <label class="sr-only">Password</label>
   <input type="password" class="form-control" th:placeholder="#{login.password}" required="">
   <div class="checkbox mb-3">
      <label>
        <input type="checkbox" value="remember-me"> [[#{login.remember}]]
      </label>
   </div>
   <button class="btn btn-lg btn-primary btn-block" type="submit">[[#{login.btn}]]</button>
   <p class="mt-5 mb-3 text-muted">© 2017-2018</p>
   <a class="btn btn-sm" th:href="@{/index.html(l='zh_CN')}">中文</a>
   <a class="btn btn-sm" th:href="@{/index.html(l='en_US')}">English</a>
</form>

扩展MVC实现中英文切换

 <a class="btn btn-sm" th:href="@{/index.html(l='zh_CN')}">中文</a>
   <a class="btn btn-sm" th:href="@{/index.html(l='en_US')}">English</a>
public class MyLocaleResolver implements LocaleResolver {
    //解析请求
    @Override
    public Locale resolveLocale(HttpServletRequest request) {
        //获取请求参数
        String language= request.getParameter("l");
        //没有就用默认的
        Locale locale =Locale.getDefault();
        //如果请求携带了参数
        if(!StringUtils.isEmpty(language)){
            String[] split =language.split("_");
            locale = new Locale(split[0],split[1]);
        }
        return locale;
    }

    @Override
    public void setLocale(HttpServletRequest request, HttpServletResponse response, Locale locale) {

    }
}

注入Bean

//注入Bean是国际化组件生效
@Bean
public LocaleResolver localeResolver(){
    return new MyLocaleResolver();
}

6.实现登录功能

实现Mapper Mapper.xml service login.controller 登陆拦截器 中英文切换

@Mapper
@Repository
public interface UserMapper {
    User queryUserByUsername(String username);
}
<?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.qiang.mapper.UserMapper">
    <select id="queryUserByUsername" resultType="User">
        select * from t_user where username=#{username}
    </select>
</mapper>
public interface UserService {
    User login(String username);
}
@Service
public class UserServiceImpl implements UserService{
    @Autowired
    UserMapper userMapper;
    @Override
    public User login(String username) {
        return userMapper.queryUserByUsername(username);
    }
}
@Controller
public class LoginController{
    @Autowired
    UserService userService;
    @RequestMapping("/user/login")
    public String login(String username,Model model,HttpSession session){
        User user = userService.login(username);
        if(user!=null){
            session.setAttribute("loginUser", username);
            return "redirect:/main.html";
        }else{
            model.addAttribute("msg", "用户名或密码错误");
            return "index";
        }
    }

}
public class LoginHandlerInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Object loginUser = request.getSession().getAttribute("loginUser");
        if(loginUser==null){
            request.setAttribute("msg", "没有权限请先登录");
            request.getRequestDispatcher("/index.html").forward(request, response);
            return false;
        }else {
            return true;
        }
        }
    }
       @Override
    public void addInterceptors(InterceptorRegistry registry) {
       registry.addInterceptor(new LoginHandlerInterceptor()).addPathPatterns("/**").excludePathPatterns("/","/index.html"
      ,"/user/login");
    }
}

7.实现增删改查

@Mapper
@Repository
public interface EmployeeMapper {
    List<Employee> queryEmpList();
    Employee queryEmpById(Integer id);
    int addEmp(Employee employee);
    int updateEmp(Employee employee);
    int deleteEmp(Integer 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.qiang.mapper.EmployeeMapper">
    <resultMap id="EmployeeMap" type="Employee">
        <id property="id" column="id"></id>
        <result property="lastName" column="lastName"></result>
        <result property="email" column="email"></result>
        <result property="gender" column="gender"></result>
        <result property="department" column="department"></result>
        <result property="birth" column="birth"></result>
    </resultMap>
    <select id="queryEmpList" resultMap="EmployeeMap">
        select * from t_employee
    </select>
    <select id="queryEmpById" resultType="Employee">
        select * from t_employee where id=#{id}
    </select>
    <insert id="addEmp" parameterType="Employee">
        insert into t_employee (id,lastName,email,gender,department,birth)
        values (#{id},#{lastName},#{email},#{gender},#{department},#{birth})
    </insert>
    <update id="updateEmp" parameterType="Employee">
        update t_employee set id=#{id},lastName=#{lastName},email=#{email},
                              gender=#{gender},department=#{department},birth=#{birth} where id=#{id}
    </update>
    <delete id="deleteEmp" parameterType="Integer">
        delete from t_employee where id=#{id}
    </delete>
</mapper>
public interface EmployeeService {
    List<Employee> list();
    Employee query(Integer id);
    int add(Employee employee);
    int update(Employee employee);
    int delete(Integer id);
}
@Service
public class EmployeeServiceImpl implements EmployeeService{
    @Autowired
    EmployeeMapper employeeMapper;
    @Override
    public List<Employee> list() {
        return employeeMapper.queryEmpList();
    }

    @Override
    public Employee query(Integer id) {
        return employeeMapper.queryEmpById(id);
    }

    @Override
    public int add(Employee employee) {
        return employeeMapper.addEmp(employee);
    }

    @Override
    public int update(Employee employee) {
        return employeeMapper.updateEmp(employee);
    }

    @Override
    public int delete(Integer id) {
        return employeeMapper.deleteEmp(id);
    }
}
@Controller
public class EmployeeController {
    @Autowired
    EmployeeService employeeService;
    @RequestMapping("/emps")
    public String list(Model model){
        List<Employee> employees = employeeService.list();
        model.addAttribute("emps", employees);
        return "list";
    }

    @GetMapping("/toAdd")
    public String toAdd(){
        return "emp/add";
    }

    @PostMapping("/addEmp")
    public String add(Employee employee){
        employeeService.add(employee);
        return "redirect:/emps";
    }
    @GetMapping("/update/{id}")
    public String toUpdate(@PathVariable("id") Integer id, Model model){
        Employee employee = employeeService.query(id);
        model.addAttribute("emp", employee);
        return "emp/update";
    }
    @PostMapping("/updateEmp")
    public String update(Employee employee){
        employeeService.update(employee);
        return "redirect:/emps";
    }
    @GetMapping("/delete/{id}")
    public String delete(@PathVariable("id") Integer id){
        employeeService.delete(id);
        return "redirect:/emps";
    }
}



上一篇:全场景效能平台猪齿鱼常用的前端css实现方案


下一篇:Leetcode Mysql 1873. 计算特殊奖金(DAY 4)