一個簡單的Restful Crud實驗 預設首頁的訪問設置: 項目結構: Bean: package com.project.javasystem.Bean; public class Department { private Integer id; private String departmen ...
一個簡單的Restful Crud實驗
預設首頁的訪問設置:
// 註冊 自定義的mvc組件,所有的WebMvcConfigurer組件都會一起起作用 @Bean public WebMvcConfigurer webMvcConfigurer(){ WebMvcConfigurer webMvcConfigureradapter = new WebMvcConfigurer(){ // 添加視圖解析 @Override public void addViewControllers(ViewControllerRegistry registry) { registry.addViewController("/").setViewName("login"); registry.addViewController("/index.html").setViewName("login"); registry.addViewController("/main.html").setViewName("dashboard"); } /*註冊攔截器
項目結構:
Bean:
package com.project.javasystem.Bean; public class Department { private Integer id; private String departmentName; public Department() { } public Department(int i, String string) { this.id = i; this.departmentName = string; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getDepartmentName() { return departmentName; } public void setDepartmentName(String departmentName) { this.departmentName = departmentName; } @Override public String toString() { return "Department [id=" + id + ", departmentName=" + departmentName + "]"; } }View Code
package com.project.javasystem.Bean; import java.util.Date; public class Employee { private Integer id; private String lastName; private String email; //1 male, 0 female private Integer gender; private Department department; private Date birth; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public Integer getGender() { return gender; } public void setGender(Integer gender) { this.gender = gender; } public Department getDepartment() { return department; } public void setDepartment(Department department) { this.department = department; } public Date getBirth() { return birth; } public void setBirth(Date birth) { this.birth = birth; } public Employee(Integer id, String lastName, String email, Integer gender, Department department) { super(); this.id = id; this.lastName = lastName; this.email = email; this.gender = gender; this.department = department; this.birth = new Date(); } public Employee() { } @Override public String toString() { return "Employee{" + "id=" + id + ", lastName='" + lastName + '\'' + ", email='" + email + '\'' + ", gender=" + gender + ", department=" + department + ", birth=" + birth + '}'; } }View Code
Component
package com.project.javasystem.Component; 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 httpServletRequest) { String l = httpServletRequest.getParameter("l"); Locale locale = Locale.getDefault(); if (!StringUtils.isEmpty(l)) { String[] split = l.split("_"); locale= new Locale(split[0],split[1]); } return locale; } @Override public void setLocale(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Locale locale) { } }View Code
package com.project.javasystem.Component; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; 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 { Object user = request.getSession().getAttribute("loginUser"); if(user == null){ // 沒有登錄 request.setAttribute("msg","沒有許可權,請先登錄"); request.getRequestDispatcher("/index.html").forward(request,response); return false; }else { //已登錄,放行請求 return true; } } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { /* response.setContentType("text/html;charset=UTF-8");*/ } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { } }View Code
Config
View CodeController
package com.project.javasystem.Controller; import ch.qos.logback.core.net.SyslogOutputStream; import com.project.javasystem.Bean.Department; import com.project.javasystem.Bean.Employee; import com.project.javasystem.Dao.DepartmentDao; import com.project.javasystem.Dao.EmployeeDao; 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.PostMapping; import java.util.Collection; //和員工相關的請求 @Controller public class EmployeeController { @Autowired DepartmentDao departmentDao; @Autowired EmployeeDao employeeDao ; // 查詢所有員工列表 @GetMapping("/emps") public String list(Model model){ Collection<Employee>employee = employeeDao.getAll(); // 放在請求域中 model.addAttribute("emps",employee); return "emp/list"; } //來到員工添加頁面 @GetMapping("/emp") public String toAddPage(Model model){ // 來到添加頁面 查出所有的部門,在頁面顯示 Collection<Department> departments = departmentDao.getDepartments(); //Alt + Enter 鍵 一鍵生成 model.addAttribute("depts",departments); return "emp/add"; } // 員工添加功能 // springMVC 自動將請求參數和入參對象的屬性進行一一綁定,所以請求參數名稱要和javabean的屬性名稱一樣 @PostMapping("/emp") public String addEmp(Employee employee){ //來到員工列表頁面 System.out.println("保存的員工信息"+employee); //保存員工 employeeDao.save(employee); // redirect:表示重定向一個地址,forward:表示轉發到一個地址 / 代表當前項目路徑 return "redirect:/emps"; } }View Code
package com.project.javasystem.Controller; import org.springframework.stereotype.Controller; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpSession; import java.util.Map; @Controller public class LoginController { @PostMapping(value = "/login") //restful 風格的請求方式,等於下麵得value的值限定方式 /*@RequestMapping(value = "/login",method = RequestMethod.POST)*/ public String Login(@RequestParam("username") String username, @RequestParam("password") String password, Map<String,Object> map, HttpSession session){ if (!StringUtils.isEmpty(username) && "123456".equals(password)){ // 登錄成功。為了防止表單重覆提交,用重定向的方式 session.setAttribute("loginUser",username); return "redirect:/main.html"; }else { //登錄失敗 map.put("msg","用戶名密碼錯誤"); return "login"; } } }View Code
Dao
package com.project.javasystem.Dao; import java.util.Collection; import java.util.HashMap; import java.util.Map; import com.project.javasystem.Bean.Department; import org.springframework.stereotype.Repository; @Repository public class DepartmentDao { private static Map<Integer, Department> departments = null; static{ departments = new HashMap<Integer, Department>(); 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<Department> getDepartments(){ return departments.values(); } public Department getDepartment(Integer id){ return departments.get(id); } }View Code
package com.project.javasystem.Dao; import java.util.Collection; import java.util.HashMap; import java.util.Map; import com.project.javasystem.Bean.Department; import com.project.javasystem.Bean.Employee; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; @Repository public class EmployeeDao { private static Map<Integer, Employee> employees = null; @Autowired private DepartmentDao departmentDao; static{ employees = new HashMap<Integer, Employee>(); employees.put(1001, new Employee(1001, "John", "[email protected]", 1, new Department(101, "總裁部"))); employees.put(1002, new Employee(1002, "Jack", "[email protected]", 1, new Department(102, "財務部"))); employees.put(1003, new Employee(1003, "Dany", "[email protected]", 0, new Department(103, "人力資源部"))); employees.put(1004, new Employee(1004, "Alven", "[email protected]", 0, new Department(104, "結算部"))); employees.put(1005, new Employee(1005, "Tina", "[email protected]", 1, new Department(105, "客服部"))); } private static Integer initId = 1006; public void save(Employee employee){ if(employee.getId() == null){ employee.setId(initId++); } employee.setDepartment(departmentDao.getDepartment(employee.getDepartment().getId())); employees.put(employee.getId(), employee); } //查詢所有員工 public Collection<Employee> getAll(){ return employees.values(); } public Employee get(Integer id){ return employees.get(id); } public void delete(Integer id){ employees.remove(id); } }View Code
bar.html
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <!--topbar--> <nav class="navbar navbar-dark sticky-top bg-dark flex-md-nowrap p-0" th:fragment="topbar"> <a class="navbar-brand col-sm-3 col-md-2 mr-0" href="http://getbootstrap.com/docs/4.0/examples/dashboard/#">[[${session.loginUser}]]</a> <input class="form-control form-control-dark w-100" type="text" placeholder="Search" aria-label="Search"> <ul class="navbar-nav px-3"> <li class="nav-item text-nowrap"> <a class="nav-link" href="http://getbootstrap.com/docs/4.0/examples/dashboard/#">Sign out</a> </li> </ul> </nav> <!--引入sidebar--> <nav class="col-md-2 d-none d-md-block bg-light sidebar" th:fragment="sidebar"> <div class="sidebar-sticky"> <ul class="nav flex-column"> <li class="nav-item"> <a class="nav-link active" th:class="${activeUri == 'main.html'?'nav-link active':'nav-link'}" th:href="@{/main.html}"> <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-home"> <path d="M3 9l9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"></path> <polyline points="9 22 9 12 15 12 15 22"></polyline> </svg> Dashboard <span class="sr-only">(current)</span> </a> </li> <li class="nav-item"> <a class="nav-link" href="http://getbootstrap.com/docs/4.0/examples/dashboard/#"> <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-file"> <path d="M13 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V9z"></path> <polyline points="13 2 13 9 20 9"></polyline> </svg> Orders </a> </li> <li class="nav-item"> <a class="nav-link" href="http://getbootstrap.com/docs/4.0/examples/dashboard/#"> <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-shopping-cart"> <circle cx="9" cy="21" r="1"></circle> <circle cx="20" cy="21" r="1"></circle> <path d="M1 1h4l2.68 13.39a2 2 0 0 0 2 1.61h9.72a2 2 0 0 0 2-1.61L23 6H6"></path> </svg> Products </a> </li> <li class="nav-item"> <a class="nav-link active" href="/#" th:href="@{/emps}" th:class="${activeUri =='emps'?'nav-link active':'nav-link'}"> <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-users"> <path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"></path> <circle cx="9" cy="7" r="4"></circle> <path d="M23 21v-2a4 4 0 0 0-3-3.87"></path> <path d="M16 3.13a4 4 0 0 1 0 7.75"></path> </svg> 員工管理 </a> </li> <li class="nav-item"> <a class="nav-link" href="http://getbootstrap.com/docs/4.0/examples/dashboard/#"> <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-bar-chart-2"> <line x1="18" y1="20" x2="18" y2="10"></line> <line x1="12" y1="20" x2="12" y2="4"></line> <line x1="6" y1="20" x2="6" y2="14"></line> </svg> Reports </a> </li> <li class="nav-item"> <a class="nav-link" href="http://getbootstrap.com/docs/4.0/examples/dashboard/#"> <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-layers"> <polygon points="12 2 2 7 12 12 22 7 12 2"></polygon> <polyline points="2 17 12 22 22 17"></polyline> <polyline points="2 12 12 17 22 12"></polyline> </svg> Integrations </a> </li> </ul> <h6 class="sidebar-heading d-flex justify-content-between align-items-center px-3 mt-4 mb-1 text-muted"> <span>Saved reports</span> <a class="d-flex align-items-center text-muted" href="http://getbootstrap.com/docs/4.0/examples/dashboard/#"> <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-plus-circle"><circle cx="12" cy="12" r="10"></circle><line x1="12" y1="8" x2="12" y2="16"></line><line x1="8" y1="12" x2="16" y2="12"></line></svg> </a> </h6> <ul class="nav flex-column mb-2"> <li class="nav-item"