SpringBoot Restful Crud

来源:https://www.cnblogs.com/thelovelybugfly/archive/2019/08/16/11361380.html
-Advertisement-
Play Games

一個簡單的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 Code

Controller

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"

您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • Android多渠道打包 Gradle打包 前言 由於App一般都會在多個應用市場上架,為了分析App在每個不同渠道的具體的數據,一般都會對不同渠道打包不同的App。多渠道打包有多種方式,這裡只介紹利用Gradle進行多渠道打包。 步驟 1、在AndroidManifest.xml中增加配置 其中, ...
  • 文章轉載自:http://www.pythonheidong.com/blog/article/3337/ 序言 招聘高峰期來了,大家都非常積極地準備著跳槽,那麼去一家公司面試就會有一堆新鮮的問題,可能不會,也可能會,但是瞭解不夠深。本篇文章為群里的小伙伴們去寶庫公司的筆試題,由筆者整理並提供筆者個 ...
  • 文章轉載自:http://www.pythonheidong.com/blog/article/3339/ 這些面試題是我在今年年初換工作的時候整理,沒有重點。包括java基礎,數據結構,網路,Android相關等等。適合中高級工程師。由於內容過多,將會分為上下兩部分。下部分跳轉鏈接:http:// ...
  • 文章轉載自:http://www.pythonheidong.com/blog/article/3329/ 本文為開發者奉獻了70道經典Android面試題加答案--重要知識點幾乎都涉及到了,你還等啥,趕緊收藏吧!! 1. 下列哪些語句關於記憶體回收的說明是正確的? (b) A、 程式員必須創建一個線 ...
  • 文章轉載自:http://www.pythonheidong.com/blog/article/3327/ iOS面試題 1.Difference between shallow copy and deep copy? 淺複製和深複製的區別? 淺層複製:指向對象的指針,而不複製引用對象本身。深層複製 ...
  • Data Structure Notes Chapter 1 Sorting Algorithm Insert Sorting: 對於近乎有序的數組可以降到$ O(n)$的時間複雜度。 Merge Sorting: Tips1 :Merge Sort Optimize in nearly order ...
  • 前言 前面一篇文章寫了 "《SimpleDateFormat 如何安全的使用?》" , 裡面介紹了 SimpleDateFormat 如何處理日期/時間,以及如何保證線程安全,及其介紹了在 Java 8 中的處理時間/日期預設就線程安全的 DateTimeFormatter 類。那麼 Java 8 ...
  • 以 Spring MVC 啟動 Servlet 為例,其應用上下文為 ServletWebServerApplicationContext,繼承了 GenericWebApplicationContext 的大部分方法,主要重寫了 postProcessBeanFactory()、refresh() ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...