SpringBoot——Web開發二(默認首頁,國際化,攔截器,RestfulCRUD)

1.默認訪問首頁


//使用WebMvcConfigurer可以用來擴展SpringMVC的功能
//@EnableWebMvc全面接管SpringMVC
@EnableWebMvc
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {
   
  
    //所有的WebMvcConfigurer組件都會一起起作用
    //使用組件註冊到容器中
    @Bean
    public WebMvcConfigurer myWebMvcConfigurer(){
        WebMvcConfigurer mvcConfigurer=new WebMvcConfigurer(){
            @Override
            public void addViewControllers(ViewControllerRegistry registry) {
                registry.addViewController("/").setViewName("login");
                registry.addViewController("/login.html").setViewName("login");
                registry.addViewController("/main.html").setViewName("dashboard");
            }
           
        };
        return mvcConfigurer;
    }

    @Bean
    public LocaleResolver localeResolver(){
        return new MyLocaleResolver();
    }


}

2.靜態資源放行

我們在訪問默認首頁的時候,發現首頁的樣式全丟了。我們知道CSS,JS全放在下圖所示的地方:

按照道理會放行,但是並沒有。經過查詢後,明白了需要在自己配置了MyConfig中添加放行靜態資源的方法:

  /*
    1.引入thymeleaf的依賴包(在pom.xml文件中加入)
    2.static裏面放所有的靜態資源,template放頁面。這兩個屬於同一級,都位於resource下面。就會自動轉化爲resource根路徑,中間不需要加static,直接接後面的文件路徑
     */

    //靜態資源放行方法
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/**").addResourceLocations("classpath:/static/");
    }

現在看下登錄頁面:

3.國際化

原來國際化怎麼編寫的:

(1)編寫國際化配置文件;

(2)使用ResourceBundleMessageSource管理國際化資源文件

(3)在頁面使用fmt:message取出國際化內容

下面看看SpringBoot的國際化配置:

3.1 步驟

1.編寫國際化配置文件,抽取頁面需要顯示的國際化消息

2.SpringBoot自動配置好了管理國際化資源文件的組件

@Configuration(proxyBeanMethods = false)
@ConditionalOnMissingBean(name = AbstractApplicationContext.MESSAGE_SOURCE_BEAN_NAME, search = SearchStrategy.CURRENT)
@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE)
@Conditional(ResourceBundleCondition.class)
@EnableConfigurationProperties
public class MessageSourceAutoConfiguration {

	private static final Resource[] NO_RESOURCES = {};

	@Bean
	@ConfigurationProperties(prefix = "spring.messages")
	public MessageSourceProperties messageSourceProperties() {
		return new MessageSourceProperties();
	}

    //我們的配置文件可以直接放在類路徑下叫message.properties
	@Bean
	public MessageSource messageSource(MessageSourceProperties properties) {
		ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
         //設置國際化資源文件的基礎名(去掉語言國家代碼的)
		if (StringUtils.hasText(properties.getBasename())) {
			messageSource.setBasenames(StringUtils
					.commaDelimitedListToStringArray(StringUtils.trimAllWhitespace(properties.getBasename())));
		}
		if (properties.getEncoding() != null) {
			messageSource.setDefaultEncoding(properties.getEncoding().name());
		}
		messageSource.setFallbackToSystemLocale(properties.isFallbackToSystemLocale());
		Duration cacheDuration = properties.getCacheDuration();
		if (cacheDuration != null) {
			messageSource.setCacheMillis(cacheDuration.toMillis());
		}
		messageSource.setAlwaysUseMessageFormat(properties.isAlwaysUseMessageFormat());
		messageSource.setUseCodeAsDefaultMessage(properties.isUseCodeAsDefaultMessage());
		return messageSource;
	}

3)去頁面獲取國際化的值

login.html代碼如下:

<!DOCTYPE html>
<html lang="en"  xmlns:th="http://www.thymeleaf.org">


	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
		<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
		<meta name="description" content="">
		<meta name="author" content="">
		<title>Signin Template for Bootstrap</title>
		<!-- Bootstrap core CSS 這裏引用的boostrap是從本地引入
		可以在pom文件中導入webjars包依賴
		然後使用th:href=“@{/webjars}”方式進行引入-->
		<link href="/asserts/css/bootstrap.min.css" rel="stylesheet">
		<!-- Custom styles for this template -->
		<link href="/asserts/css/signin.css" rel="stylesheet">
	</head>

	<body class="text-center">
		<form class="form-signin" action="dashboard.html" th:action="@{/user/login}" method="post">
			<img class="mb-4" src="asserts/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>
			<!--做一個判斷-->
			<p style="color: red" th:text="${msg}" th:if="${not #strings.isEmpty(msg)}"></p>
			<label class="sr-only" th:text="#{login.username}">Username</label>
			<input type="text" class="form-control" name="username" placeholder="Username" required="" autofocus="" th:placeholder="#{login.username}">
			<label class="sr-only" th:text="#{login.password}">Password</label>
			<input type="password" class="form-control" name="password" placeholder="Password" required="" th:placeholder="#{login.password}">
			<div class="checkbox mb-3">
				<label>
          <input type="checkbox" value="remember-me" > 記住我
        </label>
			</div>
			<button class="btn btn-lg btn-primary btn-block" type="submit" th:text="#{login.btn}">Sign in</button>
			<p class="mt-5 mb-3 text-muted">© 2017-2018</p>
			<a class="btn btn-sm" th:href="@{/login.html(l='zh_CN')}">中文</a>
			<a class="btn btn-sm" th:href="@{/login.html(l='en_US')}">English</a>
		</form>

	</body>

</html>

效果:根據瀏覽器語言設置的信息切換了國際化

3.2 點擊鏈接切換國際化

國際化Locale(區域信息對象);LocaleResolver(獲取區域信息對象);

/**
 * 可以在鏈接上攜帶區域信息
 * 記得在容器中國添加組件
 */

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[] sp= l.split("_");
           locale=new Locale(sp[0],sp[1]);
        }
        return locale;
    }

    @Override
    public void setLocale(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Locale locale) {

    }
}

我們知道所有自己配置的組件都需要在MyConfig進行註冊:

@EnableWebMvc
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {
    ... 

    @Bean
    public LocaleResolver localeResolver(){
        return new MyLocaleResolver();
    }


}

點擊中文按鈕出現的頁面:

點擊英文按鈕出現的頁面:

4.登錄以及攔截器設置

4.1 登錄錯誤信息

開發期間模板引擎頁面修改以後,要實時生效。

(1)禁用模板引擎的緩存

# 禁用緩存
spring.thymeleaf.cache=false

(2)頁面修改完成以後ctrl+f9:重新編譯;

我們在之前登錄的頁面可以看到登錄錯誤消息的顯示:

<p style="color: red" th:text="${msg}" th:if="${not #strings.isEmpty(msg)}"></p>

4.2 攔截器進行登錄檢查

攔截器編寫:

/**
 * 登錄檢查
 */
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("/login.html").forward(request,response);
            return false;
        }
        else{
            //已登錄,放行請求
            return true;
        }

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }
}

註冊攔截器:

 //所有的WebMvcConfigurer組件都會一起起作用
    //使用組件註冊到容器中
    @Bean
    public WebMvcConfigurer myWebMvcConfigurer(){
        WebMvcConfigurer mvcConfigurer=new WebMvcConfigurer(){
            @Override
            public void addViewControllers(ViewControllerRegistry registry) {
                registry.addViewController("/").setViewName("login");
                registry.addViewController("/login.html").setViewName("login");
                registry.addViewController("/main.html").setViewName("dashboard");
            }
            //註冊攔截器
            @Override
            public void addInterceptors(InterceptorRegistry registry) {
                registry.addInterceptor(new LoginHandlerInterceptor()).addPathPatterns("/**")
                .excludePathPatterns("/login.html","/user/login","/");

            }
        };
        return mvcConfigurer;
    }

當訪問dashboard頁面時,因爲攔截器的攔截返回到登錄頁面,顯示錯誤信息:

5. RestfulCRUD

5.1 實驗背景

5.1.1 實驗要求

Restful CRUD滿足REST風格。

URL:/資源名稱/資源標識 HTTP請求方式區分資源CRUD操作。

  普通CRUD(uri區分操作) RESTFULCRUD
查詢 getEmp emp-GET
添加 addEmp?xxx enp-POST
修改 updateEmp?id=xxx&xxx=xxx emp/{id}-PUT
刪除 deleteEmp?id=1 emp/{id}-DELETE

5.1.2 實驗的請求架構

實驗功能 請求URI 請求方式
查詢所有員工 emps GET
查詢某個員工(來到修改頁面) emp/1

GET

來到添加頁面 emp GET
添加員工 emp POST
來到修改頁面(查出員工進行信息回顯) emp/1 GET
修改員工 emp PUT
刪除員工 emp/1 DELETE

5.1.3 dao層和entities層

entities層的Emplyoee:

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 +
                '}';
    }
	
	
}

Department:

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 + "]";
	}
	
}

Dao層的EmplyoeeDao:

@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, "E-AA", "[email protected]", 1, new Department(101, "D-AA")));
		employees.put(1002, new Employee(1002, "E-BB", "[email protected]", 1, new Department(102, "D-BB")));
		employees.put(1003, new Employee(1003, "E-CC", "[email protected]", 0, new Department(103, "D-CC")));
		employees.put(1004, new Employee(1004, "E-DD", "[email protected]", 0, new Department(104, "D-DD")));
		employees.put(1005, new Employee(1005, "E-EE", "[email protected]", 1, new Department(105, "D-EE")));
	}
	
	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);
	}
}

DepartmentDao:

@Repository
public class DepartmentDao {

	private static Map<Integer, Department> departments = null;
	
	static{
		departments = new HashMap<Integer, Department>();
		
		departments.put(101, new Department(101, "D-AA"));
		departments.put(102, new Department(102, "D-BB"));
		departments.put(103, new Department(103, "D-CC"));
		departments.put(104, new Department(104, "D-DD"));
		departments.put(105, new Department(105, "D-EE"));
	}
	
	public Collection<Department> getDepartments(){
		return departments.values();
	}
	
	public Department getDepartment(Integer id){
		return departments.get(id);
	}
	
}

Dao層中有僞裝的數據。

5.2 thymeleaf公共頁面元素抽取

1.抽取公共片段

<div th:fragment="copy>
</div>

2.引入公共片段

<div th:insert="~{footer :: copy}"></div>
~{templatename::selector}:模板名::選擇器
~{templatename::fragmentname}:模板名::片段名

3.默認效果:insert的公共片段在div標籤中;如果使用th:insert等屬性進行引入,可以不用寫~{}: 行內寫法可以加上:[[~{}]];[(~{})]

三種引入公共片段的th屬性方法:

  • th:insert:將公共片段整個插入到聲明引入的元素中
  • th:replace:將聲明引入的元素替換爲公共片段
  • th:include:將被引入的片段的內容包含進這個標籤中

三種效果如下:

<footer th:fragment="copy">
   &copy; 2011 The Good Thymes Virtual Grocery
</footer>
引入方式
<div th:insert="footer :: copy"></div>
<div th:replace="footer :: copy"></div>
<div th:include="footer :: copy"></div>
效果
<div>
<footer>
    &copy; 2011 The Good Thymes Virtual Grocery
</footer>
</div>
<footer>
   &copy; 2011 The Good Thymes Virtual Grocery
</footer>
<div>
   &copy; 2011 The Good Thymes Virtual Grocery
</div>

我們按照上面的方法來抽取公共元素。首先創建一個公共元素的頁面:commons目錄下的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" id="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:class="${activeUri=='emps'?'nav-link active':'nav-link '}"
                   th:href="@{/emps}">
                    <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">
                <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-text">
                        <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"></path>
                        <polyline points="14 2 14 8 20 8"></polyline>
                        <line x1="16" y1="13" x2="8" y2="13"></line>
                        <line x1="16" y1="17" x2="8" y2="17"></line>
                        <polyline points="10 9 9 9 8 9"></polyline>
                    </svg>
                    Current month
                </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-text">
                        <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"></path>
                        <polyline points="14 2 14 8 20 8"></polyline>
                        <line x1="16" y1="13" x2="8" y2="13"></line>
                        <line x1="16" y1="17" x2="8" y2="17"></line>
                        <polyline points="10 9 9 9 8 9"></polyline>
                    </svg>
                    Last quarter
                </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-text">
                        <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"></path>
                        <polyline points="14 2 14 8 20 8"></polyline>
                        <line x1="16" y1="13" x2="8" y2="13"></line>
                        <line x1="16" y1="17" x2="8" y2="17"></line>
                        <polyline points="10 9 9 9 8 9"></polyline>
                    </svg>
                    Social engagement
                </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-text">
                        <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"></path>
                        <polyline points="14 2 14 8 20 8"></polyline>
                        <line x1="16" y1="13" x2="8" y2="13"></line>
                        <line x1="16" y1="17" x2="8" y2="17"></line>
                        <polyline points="10 9 9 9 8 9"></polyline>
                    </svg>
                    Year-end sale
                </a>
            </li>
        </ul>
    </div>
</nav>

</body>
</html>

我們可以看到在bar的dashboard和員工管理連接中有一個th:class屬性,在這個屬性中會有一個activeUri,這個屬性會在dashboard頁面被賦值main.html,在list頁面被賦值emps。在引入時判斷這個是main.html還是emps,然後是哪個的話,就會active賦值,這個標題就會亮。如下:

在dashboard的引入公共片段:

	<!--引入topbar-->
		<div th:replace="commons/bar::topbar"></div>

		<div class="container-fluid">
			<div class="row">
				<div th:replace="commons/bar::#sidebar(activeUri='main.html')"></div>

5.3 員工列表

5.3.1 EmpController

@Controller
public class EmpController {

    @Autowired
    EmployeeDao employeeDao;

    @Autowired
    DepartmentDao departmentDao;
    /**
     * 查詢所有員工返回列表頁面
     * @return
     */
    @GetMapping("/emps")
    public String list(Model model){
        //tf會默認拼串
       Collection<Employee> employees= employeeDao.getAll();
       //放在請求域中
        model.addAttribute("emps",employees);
        return "emp/list";
    }

...
}

5.3.2 HTML頁面

可以看到這個引入公共元素sidebar是會給activeUri賦值emps,然後在引入的時候就會判斷。

<!DOCTYPE html>
<!-- saved from url=(0052)http://getbootstrap.com/docs/4.0/examples/dashboard/ -->
<html lang="en" xmlns:th="http://www.thymeleaf.org">

	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
		<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
		<meta name="description" content="">
		<meta name="author" content="">

		<title>Dashboard Template for Bootstrap</title>
		<!-- Bootstrap core CSS -->
		<link href="asserts/css/bootstrap.min.css" rel="stylesheet">

		<!-- Custom styles for this template -->
		<link href="asserts/css/dashboard.css" rel="stylesheet">
		<style type="text/css">
			/* Chart.js */
			
			@-webkit-keyframes chartjs-render-animation {
				from {
					opacity: 0.99
				}
				to {
					opacity: 1
				}
			}
			
			@keyframes chartjs-render-animation {
				from {
					opacity: 0.99
				}
				to {
					opacity: 1
				}
			}
			
			.chartjs-render-monitor {
				-webkit-animation: chartjs-render-animation 0.001s;
				animation: chartjs-render-animation 0.001s;
			}
		</style>
	</head>

	<body>
		<!--引入抽取的navbar-->
		<!--模板名:會使用thymeleaf的前後綴配置規則進行解析-->
		<div th:replace="commons/bar::topbar"></div>

		<div class="container-fluid">
			<div class="row">
				<!--引入側邊欄-->
				<!--選擇器#id-->
				<div th:replace="commons/bar::#sidebar(activeUri='emps')"></div>

				<main role="main" class="col-md-9 ml-sm-auto col-lg-10 pt-3 px-4">
					<h2><a class="btn btn-sm btn-success" href="emp" th:href="@{/emp}">員工添加</a></h2>
					<div class="table-responsive">
						<table class="table table-striped table-sm">
							<thead>
								<tr>
									<th>#</th>
									<th>lastName</th>
									<th>email</th>
									<th>gender</th>
									<th>department</th>
									<th>birth</th>
								</tr>
							</thead>
							<tbody>
							  <tr th:each="emp:${emps}">
								  <td th:text="${emp.id}"></td>
								  <td th:text="${emp.lastName}"></td>
								  <td th:text="${emp.email}"></td>
								  <td th:text="${emp.gender==0?'女':'男'}"></td>
								  <td th:text="${emp.department.departmentName}"></td>
								  <td th:text="${#dates.format(emp.birth,'yyyy-MM-dd HH:mm')}"></td>
								  <td>
									  <a class="btn btn-sm btn-primary" th:href="@{'/emp/'+${emp.id}}">編輯</a>
									  <form th:action="@{/emp/}+${emp.id}" method="post">
										  <input name="_method" value="delete" type="hidden">
									  <button  class="btn btn-sm btn-danger ">刪除</button>
									  </form>
								  </td>
							  </tr>

							</tbody>


						</table>
					</div>
				</main>
			</div>
		</div>

		<script th:src="@{/webjars/jquery/3.3.1/jquery.js}">
			$(".deleteBtn").click(function () {
				$("#deleteEmp").attr("action",$(this).attr("del_uri")).submit();
				return false;
			});
		</script>
		<!-- Bootstrap core JavaScript
    ================================================== -->
		<!-- Placed at the end of the document so the pages load faster -->
		<script type="text/javascript" src="asserts/js/jquery-3.2.1.slim.min.js" th:src="@{/webjars/jquery/3.3.1/jquery.js}"></script>
		<script type="text/javascript" src="asserts/js/popper.min.js" th:src="@{/webjars/popper.js/1.11.1/dist/popper.js}"></script>
		<script type="text/javascript" src="asserts/js/bootstrap.min.js" th:src="@{/webjars/bootstrap/4.0.0/js/bootstrap.js}"></script>

		<!-- Icons -->
		<script type="text/javascript" src="asserts/js/feather.min.js" th:src="@{/asserts/js/feather.min.js}"></script>
		<script>
			feather.replace()
		</script>

		<!-- Graphs -->
		<script type="text/javascript" src="asserts/js/Chart.min.js"></script>
		<script>
			var ctx = document.getElementById("myChart");
			var myChart = new Chart(ctx, {
				type: 'line',
				data: {
					labels: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"],
					datasets: [{
						data: [15339, 21345, 18483, 24003, 23489, 24092, 12034],
						lineTension: 0,
						backgroundColor: 'transparent',
						borderColor: '#007bff',
						borderWidth: 4,
						pointBackgroundColor: '#007bff'
					}]
				},
				options: {
					scales: {
						yAxes: [{
							ticks: {
								beginAtZero: false
							}
						}]
					},
					legend: {
						display: false,
					}
				}
			});
		</script>

	</body>

</html>

5.3.3 頁面顯示

5.4 添加員工

5.4.1 EmpController

 //來到員工添加頁面
    @GetMapping("/emp")
    public String toAddPage(Model model){
        //來到添加頁面,查出所有的部門,在頁面顯示
        Collection<Department> departments=departmentDao.getDepartments();
        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";

    }

5.4.2 HTML頁面

<!DOCTYPE html>
<!-- saved from url=(0052)http://getbootstrap.com/docs/4.0/examples/dashboard/ -->
<html lang="en" xmlns:th="http://www.thymeleaf.org">

	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
		<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
		<meta name="description" content="">
		<meta name="author" content="">

		<title>Dashboard Template for Bootstrap</title>
		<!-- Bootstrap core CSS -->
		<link href="asserts/css/bootstrap.min.css" rel="stylesheet">

		<!-- Custom styles for this template -->
		<link href="asserts/css/dashboard.css" rel="stylesheet">
		<style type="text/css">
			/* Chart.js */
			
			@-webkit-keyframes chartjs-render-animation {
				from {
					opacity: 0.99
				}
				to {
					opacity: 1
				}
			}
			
			@keyframes chartjs-render-animation {
				from {
					opacity: 0.99
				}
				to {
					opacity: 1
				}
			}
			
			.chartjs-render-monitor {
				-webkit-animation: chartjs-render-animation 0.001s;
				animation: chartjs-render-animation 0.001s;
			}
		</style>
	</head>

	<body>
		<!--引入抽取的navbar-->
		<!--模板名:會使用thymeleaf的前後綴配置規則進行解析-->
		<div th:replace="commons/bar::topbar"></div>

		<div class="container-fluid">
			<div class="row">
				<!--引入側邊欄-->
				<!--選擇器#id-->
				<div th:replace="commons/bar::#sidebar(activeUri='emps')"></div>

				<main role="main" class="col-md-9 ml-sm-auto col-lg-10 pt-3 px-4">
					<form th:action="@{/emp}" method="post">
						<div class="form-group">
							<label>LastName</label>
							<input name="lastName" type="text" class="form-control" placeholder="zhangsan" >
						</div>
						<div class="form-group">
							<label>Email</label>
							<input name="email" type="email" class="form-control" placeholder="[email protected]" >
						</div>
						<div class="form-group">
							<label>Gender</label><br/>
							<div class="form-check form-check-inline">
								<input class="form-check-input" type="radio" name="gender" value="1" >
								<label class="form-check-label">男</label>
							</div>
							<div class="form-check form-check-inline">
								<input class="form-check-input" type="radio" name="gender" value="0" >
								<label class="form-check-label">女</label>
							</div>
						</div>
						<div class="form-group">
							<label>department</label>
							<!--提交的是部門的id-->
							<select class="form-control" name="department.id">
								<option th:value="${dept.id}" th:each="dept:${depts}" th:text="${dept.departmentName}"></option>
							</select>
						</div>
						<div class="form-group">
							<label>Birth</label>
							<input name="birth" type="text" class="form-control" placeholder="zhangsan" >
						</div>
						<button type="submit" class="btn btn-primary" >添加</button>
					</form>
				</main>
			</div>
		</div>

		<!-- Bootstrap core JavaScript
    ================================================== -->
		<!-- Placed at the end of the document so the pages load faster -->
		<script type="text/javascript" src="../../static/asserts/js/jquery-3.2.1.slim.min.js"></script>
		<script type="text/javascript" src="../../static/asserts/js/popper.min.js"></script>
		<script type="text/javascript" src="../../static/asserts/js/bootstrap.min.js"></script>

		<!-- Icons -->
		<script type="text/javascript" src="../../static/asserts/js/feather.min.js"></script>
		<script>
			feather.replace()
		</script>

		<!-- Graphs -->
		<script type="text/javascript" src="../../static/asserts/js/Chart.min.js"></script>
		<script>
			var ctx = document.getElementById("myChart");
			var myChart = new Chart(ctx, {
				type: 'line',
				data: {
					labels: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"],
					datasets: [{
						data: [15339, 21345, 18483, 24003, 23489, 24092, 12034],
						lineTension: 0,
						backgroundColor: 'transparent',
						borderColor: '#007bff',
						borderWidth: 4,
						pointBackgroundColor: '#007bff'
					}]
				},
				options: {
					scales: {
						yAxes: [{
							ticks: {
								beginAtZero: false
							}
						}]
					},
					legend: {
						display: false,
					}
				}
			});
		</script>

	</body>

</html>

5.4.3 頁面顯示

 

5.5 修改員工

5.5.1 EmpController

 //來到修改頁面,查出當前員工,在頁面回顯
    @GetMapping("/emp/{id}")
    public String toEditPage(@PathVariable("id") Integer id,Model model){
        //頁面顯示所有部門列表
        Collection<Department> departments=departmentDao.getDepartments();
        model.addAttribute("depts",departments);
        Employee employee=employeeDao.get(id);
        model.addAttribute("emp",employee);
        //回到修改頁面(add是一個修改添加二合一頁面)
        //回到修改頁面會發現這個樣式全丟,這是因爲
        return "emp/edit";
    }

    //員工修改:需要提交員工ID
    @PutMapping("/emp")
    public String updateEmp(Employee employee){
        System.out.println(employee);
        employeeDao.save(employee);
        return "redirect:/emps";
    }

5.5.2 HTML頁面

<!DOCTYPE html>
<!-- saved from url=(0052)http://getbootstrap.com/docs/4.0/examples/dashboard/ -->
<html lang="en" xmlns:th="http://www.thymeleaf.org">

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>Dashboard Template for Bootstrap</title>
    <!-- Bootstrap core CSS -->
    <link href="asserts/css/bootstrap.min.css" rel="stylesheet">

    <!-- Custom styles for this template -->
    <link href="asserts/css/dashboard.css" rel="stylesheet">
    <style type="text/css">
        /* Chart.js */

        @-webkit-keyframes chartjs-render-animation {
            from {
                opacity: 0.99
            }
            to {
                opacity: 1
            }
        }

        @keyframes chartjs-render-animation {
            from {
                opacity: 0.99
            }
            to {
                opacity: 1
            }
        }

        .chartjs-render-monitor {
            -webkit-animation: chartjs-render-animation 0.001s;
            animation: chartjs-render-animation 0.001s;
        }
    </style>
</head>

<body>
<!--引入抽取的navbar-->
<!--模板名:會使用thymeleaf的前後綴配置規則進行解析-->
<div th:replace="commons/bar::topbar"></div>

<div class="container-fluid">
    <div class="row">
        <!--引入側邊欄-->
        <!--選擇器#id-->
        <div th:replace="commons/bar::#sidebar(activeUri='emps')"></div>
        <!--需要區分是員工修改還是員工添加-->
        <main role="main" class="col-md-9 ml-sm-auto col-lg-10 pt-3 px-4">
            <form th:action="@{/emp}" method="post">
                <!--發送put請求修改員工數據
                    1.SpringMVC 配置HiddenHttpMethodFilter(SpringBoot自動配置的,新版本需要自己配置)
                    2.頁面創建一個POST表單
                    3.創建input表單,name="_method",值就是我們指定的請求方式
                -->
                <input type="hidden" name="_method" value="put" th:if="${emp!=null}">
                <input type="hidden" name="id" th:if="${emp!=null} " th:value="${emp.id}">

                <div class="form-group">
                    <label>LastName</label>
                    <input name="lastName" type="text" class="form-control" placeholder="zhangsan" th:value="${emp!=null}?${emp.lastName}">
                </div>
                <div class="form-group">
                    <label>Email</label>
                    <input name="email" type="email" class="form-control" placeholder="[email protected]" th:value="${emp!=null}?${emp.email}">
                </div>
                <div class="form-group">
                    <label>Gender</label><br/>
                    <div class="form-check form-check-inline">
                        <input class="form-check-input" type="radio" name="gender" value="1" th:checked="${emp!=null}?${emp.gender==1}">
                        <label class="form-check-label">男</label>
                    </div>
                    <div class="form-check form-check-inline">
                        <input class="form-check-input" type="radio" name="gender" value="0"  th:checked="${emp!=null}?${emp.gender==0}">
                        <label class="form-check-label">女</label>
                    </div>
                </div>
                <div class="form-group">
                    <label>department</label>
                    <!--提交的是部門的id-->
                    <select class="form-control" name="department.id">

                        <option th:value="${dept.id}" th:each="dept:${depts}" th:text="${dept.departmentName}" th:selected="${emp!=null}?${dept.id==emp.department.id}"></option>
                    </select>
                </div>
                <div class="form-group">
                    <label>Birth</label>
                    <input name="birth" type="text" class="form-control" placeholder="zhangsan" th:value="${emp!=null}?${#dates.format(emp.birth,'yyyy/MM/dd')}">
                </div>
                <button type="submit" class="btn btn-primary" th:text="${emp!=null}?'修改':'添加'">添加</button>
            </form>
        </main>
    </div>
</div>

<!-- Bootstrap core JavaScript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script type="text/javascript" src="../../static/asserts/js/jquery-3.2.1.slim.min.js"></script>
<script type="text/javascript" src="../../static/asserts/js/popper.min.js"></script>
<script type="text/javascript" src="../../static/asserts/js/bootstrap.min.js"></script>

<!-- Icons -->
<script type="text/javascript" src="../../static/asserts/js/feather.min.js"></script>
<script>
    feather.replace()
</script>

<!-- Graphs -->
<script type="text/javascript" src="../../static/asserts/js/Chart.min.js"></script>
<script>
    var ctx = document.getElementById("myChart");
    var myChart = new Chart(ctx, {
        type: 'line',
        data: {
            labels: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"],
            datasets: [{
                data: [15339, 21345, 18483, 24003, 23489, 24092, 12034],
                lineTension: 0,
                backgroundColor: 'transparent',
                borderColor: '#007bff',
                borderWidth: 4,
                pointBackgroundColor: '#007bff'
            }]
        },
        options: {
            scales: {
                yAxes: [{
                    ticks: {
                        beginAtZero: false
                    }
                }]
            },
            legend: {
                display: false,
            }
        }
    });
</script>

</body>

</html>

注意事項:

(1)我們知道這個修改員工的請求方式是POST,現在需要將其POST的方式轉換成PUT。之前我們在SSM實驗中使用的是HiddenHttpMethodFilter。在SpringBoot中低版本中是配置好的,但是在高版本中需要在application.properties中配置:

spring.mvc.hiddenmethod.filter.enabled=true

在form表單中,然後創建一個input:

   <input type="hidden" name="_method" value="put" th:if="${emp!=null}">

(2)提交的數據格式不對:生日:日期; 2017-12-12;2017/12/122017.12.12; 日期的格式化;SpringMVC將頁面提交的值需要轉換爲指定的類型; 2017-12-12---Date; 類型轉換,格式化; 默認日期是按照/的方式;這個在添加員工中也得到了體現:

   <input name="birth" type="text" class="form-control" placeholder="zhangsan" th:value="${emp!=null}?${#dates.format(emp.birth,'yyyy/MM/dd')}">

5.6 刪除員工

5.6.1 EmpController

 //員工刪除
    @PostMapping("/emp/{id}")
    public String deleteEmp(@PathVariable("id")Integer id){
        employeeDao.delete(id);
        return "redirect:/emps";
    }

5.6.2 刪除按鈕

有兩種方式:

(1)form表單:

  <form th:action="@{/emp/}+${emp.id}" method="post">
		 <input name="_method" value="delete" type="hidden">
		 <button  class="btn btn-sm btn-danger ">刪除</button>
 </form>

(2)JS方法:

<tr th:each="emp:${emps}">
<td th:text="${emp.id}"></td>
<td>[[${emp.lastName}]]</td>
<td th:text="${emp.email}"></td>
<td th:text="${emp.gender}==0?'女':'男'"></td>
<td th:text="${emp.department.departmentName}"></td>
<td th:text="${#dates.format(emp.birth, 'yyyy‐MM‐dd HH:mm')}"></td>
<td>
  <a class="btn btn‐sm btn‐primary" th:href="@{/emp/}+${emp.id}">編輯</a>
   <button th:attr="del_uri=@{/emp/}+${emp.id}" class="btn btn‐sm btn‐danger
     deleteBtn">刪除</button>
  </td>
</tr>
<script>
   $(".deleteBtn").click(function(){
   //刪除當前員工的
   $("#deleteEmpForm").attr("action",$(this).attr("del_uri")).submit();
   return false;
   });
</script>

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章