Preparation
Put resources in the corresponding folder
java simulation database
Department Java Department entity class
//Department table @Data @NoArgsConstructor //Parameterless constructor @AllArgsConstructor //Parametric constructor public class Department { private Integer id; private String departmentName; }
Employee Java employee entity class
//Employee table @Data @NoArgsConstructor public class Employee { private Integer id; private String lastName; private String email; private Integer gender; //0: female 1: difficult private Department department; private Date birth; public Employee(Integer id, String lastName, String email, Integer gender, Department department) { this.id = id; this.lastName = lastName; this.email = email; this.gender = gender; this.department = department; //Default creation date! this.birth = new Date(); } }
DepartmentDao.java
//Department dao @Repository public class DepartmentDao { //Simulate data in the database private static Map<Integer,Department> departments = null; static { //Create department table departments = new HashMap<Integer,Department>(); departments.put(101,new Department(101,"Teaching Department")); departments.put(102,new Department(102,"Marketing Department")); departments.put(103,new Department(103,"Teaching and Research Department")); departments.put(104,new Department(104,"Operation Department")); departments.put(105,new Department(105,"Logistics Department")); } //Get all department information public Collection<Department> getDepartments(){ return departments.values(); } //Get department by id public Department getDepartmentById(Integer id){ return departments.get(id); } }
EmployeeDao.java
//Employees dao @Repository public class EmployeeDao { //Simulate data in the database private static Map<Integer,Employee> employees = null; //Department to which the employee belongs @Autowired private DepartmentDao departmentDao; static { //Create department table employees = new HashMap<Integer,Employee>(); employees.put(101,new Employee(1001,"AA","A6131313@qq.com",1,new Department(101,"Teaching Department"))); employees.put(102,new Employee(1002,"BB","B6131313@qq.com",0,new Department(102,"Marketing Department"))); employees.put(103,new Employee(1003,"CC","C6131313@qq.com",1,new Department(103,"Teaching and Research Department"))); employees.put(104,new Employee(1004,"DD","D4234524@qq.com",0,new Department(104,"Operation Department"))); employees.put(105,new Employee(1005,"EE","E6131313@qq.com",1,new Department(105,"Logistics Department"))); } //===Add / delete / modify query=== //Primary key auto increment private static Integer initId = 1006; //Add an employee public void add(Employee employee){ if (employee.getId()==null){ employee.setId(initId++); } employee.setDepartment(departmentDao.getDepartmentById(employee.getDepartment().getId())); employees.put(employee.getId(),employee); } //Query all employee information public Collection<Employee> getAll(){ return employees.values(); } //Query employees by id public Employee getEmployeeById(Integer id){ return employees.get(id); } //Delete employee by id public void delete(Integer id){ employees.remove(id); } }
Home page implementation
Notes:
- The static resources of all pages need to be taken over by thymeleaf
- url: @{}
Com Peng Config/mymvcconfig Java configuration home page
@Configuration public class MyConfig implements WebMvcConfigurer { @Override public void addViewControllers(ViewControllerRegistry registry) { registry.addViewController("/").setViewName("index"); registry.addViewController("/index.html").setViewName("index"); } }
Page internationalization
Notes:
- We need to configure the i18n file
- If we need to switch buttons automatically in the project, we need to customize a component, LocaleResolver
- Remember to configure the components you write to the spring container @Bean
- #{}
Using bundle visualization, several files can be configured at the same time, and Yaml configuration
#Our profile is in the real location of spring: messages: basename: i18n.login
Change the syntax of the home button link to thymeleaf
<a class="btn btn-sm" th:href="@{/index.html(l='zh_CN')}">Chinese</a> <a class="btn btn-sm" th:href="@{/index.html(l='en_US')}">English</a>
Mylocaleresolver Local parser written by Java
public class MyLocaleResolver implements LocaleResolver { //Resolve request @Override public Locale resolveLocale(HttpServletRequest httpServletRequest) { //Get the language parameter link in the request String language = httpServletRequest.getParameter("l"); Locale locale = Locale.getDefault(); //If not, use the default //If the requested link carries internationalization parameters if (! StringUtils.isEmpty(language)){ //zh_CN String[] split = language.split("_"); //Country, region locale = new Locale(split[0], split[1]); } return locale; } //It is not used here, but an error will be reported if this class in the interface is not implemented @Override public void setLocale(HttpServletRequest httpServletRequest, @Nullable HttpServletResponse httpServletResponse, @Nullable Locale locale) { } }
On com Peng Config/myconfig Registering bean s in Java configuration file
//The customized internationalization component takes effect in the bean @Bean public LocaleResolver localeResolver(){ return new MyLocaleResolver(); }
test result
Realize login function
Logincontroller Java login controller
@Controller public class LoginController { @RequestMapping("/user/login") public String login( @RequestParam("username") String username, @RequestParam("password") String password, Model model){ //Specific business if (!StringUtils.isEmpty(username) && "123456".equals(password)){ return "dashboard"; }else { //Tell the user that login failed model.addAttribute("msg","Wrong user name or password"); return "index"; } } }
Corresponding index Insert reminder in HTML home page
<p style="color: red" th:text="${msg}" th:if="${not #strings.isEmpty(msg)}"></p>
Login interceptor
public class LoginHandlerInterceptor implements HandlerInterceptor { //Return Boolean value, release or not @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { //After Lu succeeds, there should be a sessoin for the user Object loginUser = request.getSession().getAttribute("loginUser"); if (loginUser==null){ //not logged on request.setAttribute("msg","No permission, please log in first"); request.getRequestDispatcher("/index.html").forward(request,response); return false; }else { return true; } } }
Show employee list
- Extract public pages
- th: fragment="si debar"
- th: replace="~{ commons/ commons : : topbar}"
- If you want to transfer parameters, you can directly use () to transfer parameters and receive the judgment
- List circulation display
Employeecontroller Java employee controller
@Controller public class EmployeeController { @Autowired EmployeeDao employeeDao; @RequestMapping("emps") public String list(Model model){ Collection<Employee> employees = employeeDao.getAll(); model.addAttribute("emps",employees); return "emp/list"; } }
Add employee implementation
- Button submit
- Jump to add page
- Employee added successfully
- Back to home page
Employeecontroller Java employee controller, adding two methods
@GetMapping("/emp") public String toAddpage(Model model){ //Find out the information of all departments Collection<Department> departments = departmentDao.getDepartments(); model.addAttribute("departments",departments); return "emp/add"; } @PostMapping("/emp") public String addEmp(Employee employee){ System.out.println("save => "+employee); //Save employee information by adjusting the underlying business method of Sichuan employeeDao.add(employee); return "redirect:emps"; }
Modify employee implementation
Employeecontroller Java employee controller, adding two more methods
//Go to the employee modification page @GetMapping("/emp/{id}") public String toUpdateEmp(@PathVariable("id")Integer id,Model model){ //Find out the original data Employee employee = employeeDao.getEmployeeById(id); model.addAttribute("emp",employee); //Find out the information of all departments Collection<Department> departments = departmentDao.getDepartments(); model.addAttribute("departments",departments); return "emp/update"; } @PostMapping("/updateEmp") public String updateEmp(Employee employee){ employeeDao.add(employee); //modify return "redirect:/emps"; }
Delete employee implementation
Employeecontroller Java employee controller, adding another method
//Delete employee @GetMapping("/delemp/{id}") public String deleteEmp(@PathVariable("id")Integer id){ employeeDao.delete(id); return "redirect:/emps"; }
logout
Add this function in LoginController
//logout @RequestMapping("/user/logout") public String logout(HttpSession session){ session.invalidate(); return "redirect:/index.html"; }
404
Create a new error folder and put a 404 Html is enough, so is 500
Write site steps
- The front end is done. What does the page look like? Data
- Design database (database design difficulties!)
- The front-end enables him to run automatically and independently
- How to connect data interfaces: json, object all in one!
- Front and rear end joint commissioning test
-
Attention points
-
There is a set of familiar background templates: work is necessary, and x- admin is recommended
-
Front end interface: at least you can combine a website page through the front-end framework
index,about,blog,post,user
-
Let this website run independently
-