SpringBoot整合web项目详细过程

本文记录了使用SpringBoot创建简单网站的过程,包括准备工作、首页实现、国际化、登录功能及CRUD操作。通过实例展示了如何配置项目、编写java类、处理国际化、实现登录拦截以及处理404错误页面。
摘要由CSDN通过智能技术生成

最近开始跟着学SpringBoot,记录一下SpringBoot实现简单网站的CRUD,以便日后回顾。

准备工作

新建spring项目,记得勾选springweb和thymeleaf!
pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.4.0</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.fanjh</groupId>
	<artifactId>spring-03-web</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>spring-03-web</name>
	<description>Demo project for Spring Boot</description>

	<properties>
		<java.version>1.8</java.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>


		<!--thymeleaf-->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-thymeleaf</artifactId>
		</dependency>

		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>

首先导入现有模板静态资源(可以网上找免费的):在这里插入图片描述
一般静态资源放在根目录下的static文件夹下。

html文件放在template文件夹下,这里包括:登录页面index.html, 首页dashboard.html, 错误页面404.html, 员工管理页面list.html。

项目目录截图
在这里插入图片描述

编写java类

(使用lombok插件)

  • Empoyee
package com.fanjh.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

import java.util.Date;

@Data
@NoArgsConstructor
public class Employee {
   

    private Integer id;
    private String lastName;
    private String email;
    private Integer gender;
    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;
        //日期内部生成
        this.birth = new Date();
    }
}

  • Department
package com.fanjh.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Department {
   
    private Integer id;
    private String departmentName;
}

编写dao层(不连接数据库)

伪造数据库

  • DepartmentDao
package com.fanjh.dao;

import com.fanjh.pojo.Department;
import org.springframework.stereotype.Repository;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

//@component的引申注解,实现bean的注入
@Repository
public class DepartmentDao {
   

    //模拟数据库中的数据
    private static Map<Integer, Department> 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<Department> getDepartments(){
   
        return departments.values();
    }

    //根据id获取部门
    public Department getDepartmentById(Integer id){
   
        return departments.get(id);
    }
}

  • EmployeeDao
package com.fanjh.dao;

import com.fanjh.pojo.Department;
import com.fanjh.pojo.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

//@component的引申注解,实现bean的注入
@Repository
public class EmployeeDao {
   

    //模拟数据库中的数据
    private static Map<Integer, Employee> employees = null;
    //员工有所属部门
    @Autowired
    private DepartmentDao departmentDao;

    static{
   
        employees = new HashMap<>();

        employees.put(1001, new Employee(1001, "AA", "A134324@qq.com", 1, new Department(101, "综合部")));
        employees.put(1002, new Employee(1002, "BB", "B134324@qq.com", 0, new Department(102, "媒体部")));
        employees.put(1003, new Employee(1003, "CC", "C134324@qq.com", 1, new Department(103, "主席团")));
        employees.put(1004, new Employee(1004, "DD", "D134324@qq.com", 0, new Department(104, "留学部")));
        employees.put(1005, new Employee(1005, "EE", "E134324@qq.com", 1, new Department(105, "文体部")));
    }

    //主键自增
    private static Integer initid = 1006;

    //增加成员
    public void save(Employee employee){
   
        if(employee.getId() == null){
   
            employee.setId(initid++);
        }

        employee.setDepartment(departmentDao.getDepartmentById(employee.getDepartment().getId()));
        employees.put(employee.getId(), employee);
    }

    //查询全部成员信息
    public Collection<Employee> getAll(){
   
        return employees.values();
    }

    //通过id查询成员
    public Employee getEmployeeById(Integer id){
   
        return employees.get(id);
    }

    //通过id删除成员
    public void delete(Integer id){
   
        employees.remove(id);
    }
}

首页实现

在这里插入图片描述

  • index.html
    注意引入命名空间;
    所有的页面静态资源都要用thymeleaf接管;
<!DOCTYPE html>
<!--所有的页面的静态资源都需要使用thymeleaf接管,所有的本地url格式都是@{}-->
<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 -->
		<!--"/"表示在根目录下,即classpath:,static不用写-->
		<link th:href="@{/css/bootstrap.min.css}" rel="stylesheet">
		<!-- Custom styles for this template -->
		<link th:href="@{/css/signin.css}" rel="stylesheet">
	</head>

	<body class="text-center">
		<!-- 点击提交按钮时,走/user/login请求 -->
		<form class="form-signin" th:action="@{/user/login}">
			<img class="mb-4" th:src="@{/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>

			<!--msg不为空,即密码错了,才显示提示-->
			<p style="color: red" th:text="${msg}" th:if="${not #strings.isEmpty(msg)}"></p>

			<input type="text" name="username" class="form-control" th:placeholder="#{login.uername}" required="" autofocus="">
			<input type="password" name="password" class="form-control" th:placeholder="#{login.password}" required="">
			<div class="checkbox mb-3">
				<label>
          <input type="checkbox" value="remember-me"> [[#{login.remember}]]
        </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="@{/index.html(l='zh_CN')}">中文</a>
			<a class="btn btn-sm" th:href="@{/index.html(l='en_US')}">English</a>
		</form>
	</body>
</html>

效果
在这里插入图片描述

国际化

首先确保设置中的File Encodings都是UTF-8,不然会有乱码。

在这里插入图片描述

  • login.properties
login.btn=登录
login.password=密码
login.remember=记住我
login.tip=请登录
login.uername=用户名
  • login_en_US.properties
login.btn=sign in
login.password=Password
login.remember=Remember me
login.tip=please sign in
login.uername=Username

登录页面点击中文/English时,会携带参数’l’传递给后台,此时我们自定义国际化组件解析参数。

配置完后怎么识别到这个国际化?

源码MessageSourceAutoConfiguration
在这里插入图片描述
去配置!

#关闭模板引擎缓存
spring.themeleaf.cache=false

#首页地址
#静态资源配置一般转为thymeleaf
server.servlet.context-path=/fanjh

#配置文件的真实位置
spring.messages.basename=i18n.login

#设置日期格式(默认格式)
spring.mvc.format.date=yyyy/MM/dd

自定义国际化组件

  • MyLocaleResolver
package com.fanjh.config;

import org.springframework.web.servlet.LocaleResolver;
import org.thymeleaf.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Locale;

public class MyLocaleResolver implements LocaleResolver {
   
    @Override
    public Locale resolveLocale(HttpServletRequest request) {
   
        //获取请求中的语言参数
        String language = request.getParameter("l");
        Locale locale = Locale.getDefault();//如果没有就使用默认的
        //如果请求的连接携带了国际化的参数
        if(!StringUtils.isEmpty(language)){
   
            //zh_CN
            String[] split = language.split("_");
            //国家 地区
            locale = new Locale(split[0], split[1]);
        }
        return locale;
    }
    @Override
    public void setLocale(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Locale locale) {
   
    }
}

将国际化组件注入到容器中,使之生效。

  • MyMvcConfig
    如果你想diy一些定制化的功能,只要写这个组件,然后将他交给springboot,springboot就会帮我们自动装配。
    如果我们要扩展springmvc,官方建议我们这样做。
package com.fanjh.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.Locale;

@Configuration
public class MyMvcConfig implements WebMvcConfigurer {
   

    //一般在这里配置根目录的东西
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
   
        registry.addViewController("/").setViewName("index");
        registry.addViewController("/index.html").setViewName("index");
        registry.addViewController("/main.html").setViewName("dashboard");
    }

    //自定义的国际化组件就生效了
    @Bean
    public LocaleResolver localeResolver(){
   
        return new MyLocaleResolver();
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
   
    	 //对所有的请求的拦截,除了"/index.html", "/", "/user/login",
        //                 "/css/*", "/js/**", "/img/**"
        registry.addInterceptor(new LoginHandlerInterceptor())
                .addPathPatterns("/**").excludePathPatterns("/index.html", "/", "/user/login",
                 "/css/*", "/js/**", "/img/**");
    }
}

第一部分添加视图,我们可以通过’/’或‘/index.html’访问index页面;
第二部分注入我们自定义的国际化组件;
第三部分添加拦截器,实现对未登录用户的拦截。

登录功能实现

  • LoginController
package com.fanjh.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;

@Controller
public class LoginController {
   
	//登录
    @RequestMapping("/user/login")
    public String login(@RequestParam("username") String username,
                        @RequestParam("password") String password,
                        Model model, HttpSession session){
   
        if("abc".equals(username) && "1234".equals(password)){
   
            session.setAttribute("loginUser", username);
            return "redirect:/main.html";
        }else{
   
            model.addAttribute("msg", "用户名或密码错误");
            return "index";
        }
    }
	//注销
    @RequestMapping("/user/logout")
    public String logout(HttpSession session){
   
        //注销session即可
        session.invalidate();
        return "redirect:/index/html";
    }
}

登录拦截器

  • LoginHandlerInterceptor
package com.fanjh.config;

import org.omg.PortableInterceptor.Interceptor;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot 是一个快速开发框架,可以很方便地搭建一个 Web 应用程序。MyBatis-Plus 是 MyBatis 的增强工具包,可以更加便捷地操作数据库。这里介绍一下 Spring Boot 整合 MyBatis-Plus 的详细过程。 1. 添加依赖 在 pom.xml 文件中添加 MyBatis-Plus 的依赖: ```xml <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>${mybatis-plus.version}</version> </dependency> ``` 其中,${mybatis-plus.version} 是你所使用的 MyBatis-Plus 的版本号。 2. 配置数据源 在 application.properties 或 application.yml 文件中配置数据源信息: ```properties spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai spring.datasource.username=root spring.datasource.password=root ``` 3. 配置 MyBatis-Plus 在 Spring Boot 中,MyBatis-Plus 的配置非常简单。只需要在 application.properties 或 application.yml 文件中添加以下配置即可: ```properties # MyBatis-Plus 配置 mybatis-plus.mapper-locations=classpath:mapper/*.xml ``` 其中,mybatis-plus.mapper-locations 指定了 Mapper 文件的位置。 4. 定义实体类 在 MyBatis-Plus 中,实体类需要继承 Model 类,并且需要使用 @TableName 注解指定表名: ```java @Data @TableName("user") public class User extends Model<User> { private Long id; private String name; private Integer age; private String email; } ``` 5. 定义 Mapper 接口 在 MyBatis-Plus 中,Mapper 接口不需要编写实现类,只需要继承 BaseMapper 接口即可。例如: ```java public interface UserMapper extends BaseMapper<User> { } ``` 6. 测试 编写一个测试类,测试 MyBatis-Plus 是否能够正确地操作数据库: ```java @RunWith(SpringRunner.class) @SpringBootTest public class UserMapperTest { @Autowired private UserMapper userMapper; @Test public void testSelect() { System.out.println("----- selectAll method test -----"); List<User> userList = userMapper.selectList(null); Assert.assertEquals(5, userList.size()); userList.forEach(System.out::println); } } ``` 在测试类中注入 UserMapper 对象,并调用 selectList 方法查询数据库中的所有用户信息。 以上就是使用 Spring Boot 整合 MyBatis-Plus 的详细过程

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值