先不连接数据库,后面整合了mybatis再补充
步骤:
1、导入静态资源
下载地址:下载 - KuangStudy
2、在pojo包下写实体类
①Department
//部门表
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Department {
private Integer id;
private String departmentName;
}
②Employee
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 Department department;
private Date birth;
}
3、dao层
①DepartmentDao
//部门dao
@Repository
public class DepartmentDao {
//模拟数据库中的数据
private static Map departments = null;
static {
departments = new HashMap(); //创建一个部门表
departments.put(101, new Department(101,"研发部"));
departments.put(102, new Department(102,"销售部"));
departments.put(103, new Department(103,"运维部"));
departments.put(104, new Department(104,"财务部"));
departments.put(105, new Department(105,"市场部"));
}
//查所有的部门
public Collection getDepartments(){
return departments.values();
}
//通过id查部门
public Department getDepartmentById(Integer id){
return departments.get(id);
}
}
②EmployeeDao
//员工Dao
@Repository
public class EmployeeDao {
//模拟数据库中的数据
private static Map employees = null;
//员工有所属的部门
@Autowired
private DepartmentDao departmentDao;
static {
employees = new HashMap(); //创建一个员工表
employees.put(1001,new Employee(1001,"张一","[email protected]",1,new Department(101,"研发部"),new Date()));
employees.put(1002,new Employee(1002,"张二","[email protected]",0,new Department(101,"研发部"),new Date()));
employees.put(1003,new Employee(1003,"张三","[email protected]",1,new Department(102,"销售部"),new Date()));
employees.put(1004,new Employee(1004,"张四","[email protected]",1,new Department(104,"财务部"),new Date()));
employees.put(1005,new Employee(1005,"张五","[email protected]",1,new Department(105,"市场部"),new Date()));
}
//主键自增
private static Integer initId = 10086;
//增加或者修改一个员工
public void save(Employee employee){
if(employee.getId() == null){
employee.setId(initId++);
}
//从前端只传过来部门id的情况下,获取部门全部信息,再set进员工对象
employee.setDepartment(departmentDao.getDepartmentById(employee.getDepartment().getId()));
employees.put(employee.getId(),employee);
}
//查询全部员工
public Collection getAll(){
return employees.values();
}
//通过id删除员工
public void delete(Integer id){
employees.remove(id);
}
//通过id查询员工
public Employee getEmployeeByID(Integer id) {
return employees.get(id);
}
}
4、首页
①自定义视图跳转
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("index");
registry.addViewController("/index.html").setViewName("index");
}
}
②在index.html中引入thymeleaf,并把连接改为thymeleaf格式
同理,更改404.html、dashboard.html、list.html页面格式
③访问首页
5、国际化
①先把所有编码改为utf-8
②编写配置文件
③在application.properties中指定国际化配置文件的真实位置
#我们国际化配置文件的真实位置
spring.messages.basename=i18n.login
④在index.html中用#号取值(国际化要用#取值)
⑤给中英文的按钮添加链接,并携带参数
⑥ 自定义地区解析器
public class MyLocaleResolver implements LocaleResolver {
//解析请求
@Override
public Locale resolveLocale(HttpServletRequest request) {
//获取请求中的语言参数
String language = request.getParameter("l");
Locale locale = Locale.getDefault(); //如果没有,就使用默认的
//如果请求的链接携带了国际化的参数
if(!StringUtils.isEmpty(language)){
//把language按_分割为语言和国家
//比如:zh_CN中的zh是中文,CN是中国 en_US中的en是英文,US是美国
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
public LocaleResolver localeResolver(){
return new MyLocaleResolver();
}
⑧测试一下
6、登录功能实现
①把表单提交路径改为 /user/login 并且表单提交数据需要name属性,所以把name也加上
②在controller包下,编写一个LoginController
@Controller
public class LoginController {
@RequestMapping("/user/login")
public String login(@RequestParam("username") String username, @RequestParam("password") String password, Model model, HttpSession session){
//具体的业务
if (!StringUtils.isEmpty(username) && "123456".equals(password)) { //登录成功
return "redirect:/main.html";
}else {
//告诉用户,你登录失败了
model.addAttribute("msg","用户名或者密码错误,登录失败");
return "index";
}
}
}
③把登录失败时,设置的msg属性,展示在index.html
④把登录成功时,重定向的main.html注册到 MyMvcConfig 中
⑤测试一下
登录成功:
7、登录拦截器
之前的登录有一个问题:我们不登录,直接在地址栏访问main.html也可以进入这个页面
所以我们需要设置拦截器
①用户登录成功,把用户名存入session中
②自定义拦截器
public class LoginHandlerInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//登录成功之后,用户有session
Object loginUser = request.getSession().getAttribute("loginUser");
if(loginUser == null){ //没有登录
request.setAttribute("msg","没有权限,请先登录");
request.getRequestDispatcher("/index.html").forward(request,response);
return false;
}else {
return true;
}
}
}
③将拦截器注册到 MyMvcConfig 中
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LoginHandlerInterceptor())
.addPathPatterns("/**")
.excludePathPatterns("/index.html","/","/user/login","/css/*","/img/*","/js/*");
}
④测试一下
直接访问main.html:
登录成功进入main.html:
⑤优化:把Company name改为登录时输入的用户名
⑥再测试一下
8、展示员工列表
1)把list.html和dashboard.html的公共部分 (顶部导航栏和侧边栏)提取出来,放到commons.html中,再把公共部分引入到list.html和dashboard.html中
①抽取公共部分到commons.html页面中
②在dashboard.html中引入公共部分
③在 list.html中引入公共部分
其中,传入的参数是用来判断高亮的
2)在list.html页面中遍历员工信息
id
lastName
email
gender
department
birth
操作
3)显示结果
9、增加员工实现
①在list页面增加一个添加员工的按钮
添加员工
②编写对应的controller
@GetMapping("/add")
public String toAddPage(Model model){
//查出所有部门
Collection departments = departmentDao.getDepartments();
model.addAttribute("departments",departments);
return "emp/add";
}
③编写emp/add页面(顶部导航栏、侧边栏与list.html一样)
点击添加按钮,表单会提交到
th:action="@{/add}" method="post"
④编写对应的controller
@PostMapping("/add")
public String addEmp(Employee employee){
employeeDao.save(employee);
//增删改查的时候要用重定向,不然可能会出现表单重复提交
return "redirect:/emps";
}
⑤测试一下
点击添加按钮,确实添加成功了
10、修改员工信息
①在list.html中,把编辑按钮改成超链接
编辑
②编写controller
@GetMapping("/update/{id}")
public String update(@PathVariable("id")Integer id, Model model){
//查出原来的数据
Employee employee = employeeDao.getEmployeeByID(id);
model.addAttribute("emp",employee);
//查出所有部门
Collection departments = departmentDao.getDepartments();
model.addAttribute("departments",departments);
return "emp/update";
}
③编写 emp/update.html页面(顶部导航栏和侧边栏都跟list.html一样)
④点击修改按钮后,表单提交到 /updateEmp 编写对应的controller
@PostMapping("/updateEmp")
public String updateEmp(Employee employee){
employeeDao.save(employee);
return "redirect:/emps";
}
11、删除员工
①将list.html中的删除按钮更改为超链接
删除
②编写对应的controller
@GetMapping("/delete/{id}")
public String delete(@PathVariable("id") Integer id){
employeeDao.delete(id);
return "redirect:/emps";
}
12、404处理
在resources目录下,新建一个error目录,在error目录下建一个404.html,springboot会自动识别,如果是500错误,在error下创建500.html就行了
13、注销
①在顶部导航栏中,编写注销链接
注销
②编写controller
@GetMapping("/logout")
public String logout(HttpSession session){
session.invalidate();
return "redirect:/index.html";
}