软件编程
位置:首页>> 软件编程>> java编程>> 利用Spring boot如何创建简单的web交互应用

利用Spring boot如何创建简单的web交互应用

作者:Be a funny man.  发布时间:2023-07-15 12:47:00 

标签:springboot,web,交互应用

关于页面渲染

其实在工作中,一直都是前后端分离,也就是说,我的工作从来都是提供接口,而不写 html css js 之类的,所以在这方面也没有经验。

这里为了给大家介绍下模板引擎,我将会写个非常非常简单的页面,如果不好看,请见谅~

Spring Boot 官方推荐的模板引擎是 Thymeleaf ,点击可以进入其官网了解详情。

本章目标

  • 让 Spring Boot 应用可以访问到静态资源文件

  • 创建用户登录表单,并对用户名、密码进行校验

  • 校验失败,将返回登录页,并展示错误信息

  • 校验成功,重定向到苹果列表页面

快速开始

添加依赖文件

创建一个 quick-thymeleaf 项目,创建方式参见上一篇文章 Springboot 入门。

创建好之后,修改我们的 POM 文件,添加 Thymeleaf 依赖,这里我们同时用到了 lombok 注解。


<!-- 模板 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!-- 引入 lombok ,用于注解 Model -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.12.6</version>
</dependency>

创建 Model 类

依赖添加完毕后,创建需要用到的类,这里需要用到两个,一个 User 用于用户登录,一个 Apple 用于展示作用。

User.java


@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
@NotEmpty(message = "用户名不能为空")
@Length(min = 5, message = "用户名长度不能小于5位")
private String username;
@NotEmpty(message = "密码不能为空")
@Length(min = 6, message = "密码长度不能小于6位")
private String password;
/**
* 校验是否合法用户
*
* @param user
* @return
*/
public static boolean isUserValid(User user) {
return "admin".equals(user.getUsername()) && "123456".equals(user.getPassword());
}
}

Apple.java


@Data
@NoArgsConstructor
@AllArgsConstructor
public class Apple {
private Float price;
private String color;
/**
* 制造苹果,这里生成 9 只
*
* @return
*/
public static List<Apple> generateApples() {
List<Float> prices = Arrays.asList(2.5f, 1.3f, 3.2f);
List<String> colors = Arrays.asList("red", "green", "black");
return prices.stream().flatMap(
p -> colors.stream().map(c -> new Apple(p, c))).collect(toList());
}

}

java8 新特性

Apple类为我们提供一些苹果,在用户登录成功后展示。

其中 generateApples 方法用到了 Java8 的新特性 函数式编程,这样代码会少很多,看起来很舒服。

关于 Java8 函数式编程 ,有时间的话,我会专门开一个系列来和大家聊聊,敬请期待。

lombok 注解

简单说明一下 lombok 注解

@Data:为所有属性增加 getter setter 方法,并且自动重写 toString hashCode 方法,并且以所有非空的字段创建了构造方法。

@NoArgsConstructor:生成无参构造方法。

AllArgsConstructor:包含所有参数的构造方法。

该类中其他的注解大家应该常用就不说明了。

创建控制器

Model 创建完毕,接着创建一个UserController 控制器。

该控制器包含三个方法

  • 在浏览器访问主页的时候,我们希望进入到登录页面,所以含有一个 toLoginForm 方法

  • 用户在登录页面输入用户名、密码之后,需要进行登录操作,所以包含一个 login 方法

  • 登录成功后,将跳转到苹果列表页面,需要一个 apples方法

UserController.java


@Controller
@RequestMapping("/user") // 在类中定义,表示该类中的所有方法都将以这个路径作为前缀
public class UserController {
@GetMapping // 4.3 版本后的新特性
public ModelAndView toLoginForm(@ModelAttribute("errorMsg") String errorMsg, @ModelAttribute("user") User user) {
// 返回 templates/login.html 页面, html 可以省略
return new ModelAndView("/login");
}
@PostMapping("/login") // 4.3 版本后的新特性
public ModelAndView login(HttpServletRequest request, @Valid User user, BindingResult result,
 RedirectAttributes redirect) {
// 如果 user 的字段不符合要求,则返回到登录页面,并将 valid error 信息传入登录页面
if (result.hasErrors())
return new ModelAndView("/login", "formErrors", result.getAllErrors());
// 用户名或密码不正确
if (!User.isUserValid(user)) {
// 添加错误消息,该消息将一起带到重定向后的页面,
// 浏览器刷新后,该数据将消失
redirect.addFlashAttribute("errorMsg", "登录失败,用户名或密码错误");
// 重定向到 login.html 页面
return new ModelAndView("redirect:/user");
}
// 将用户登录信息添加到 session 中
request.getSession().setAttribute("userLogin", true);
return new ModelAndView("redirect:/user/apples");
}
@GetMapping("/apples")
public ModelAndView apples(HttpServletRequest request) {
Boolean userLogin = (Boolean) request.getSession().getAttribute("userLogin");
if (userLogin != null && userLogin) {
List<Apple> apples = Apple.generateApples();
// 登录成功,进入 apple 页面,并展示 apples
ModelAndView modelAndView = new ModelAndView("/apple");
modelAndView.addObject("apples", apples);
return modelAndView;
}
return new ModelAndView("redirect:/user");
}
}

类中已作了简单的解释,所以不再赘述,如果有疑问的,可以自己搜索相关资料,或者留言。

创建并访问资源文件

在控制器中,我们的两个方法都响应了不同的页面,那么现在就需要创建对应的页面。

在 Spring Boot 中,应用的资源文件默认处于 resources 资源文件夹下,其中静态文件默认在 resources/static 目录下,模板文件在 resources/templates 目录下,我们创建对应的目录结构

利用Spring boot如何创建简单的web交互应用

按照图示创建好之后,再在对应的目录中添加 css、js 文件。

然后创建 HTML 文件,这里由于代码量太多,就不展示了,有兴趣的可以点击链接下载

apple.html

login.html

layout.html

接下来在 resources 根目录下创建 Spring Boot 的配置文件 application.yml

推荐使用 yml 格式作为配置文件格式,看上去很直观

application.yml


server:
# 指定服务器端口号
port: 8088
spring:
thymeleaf:
# 禁止浏览器缓存
cache: false
mode: HTML5

启动项目

一切准备就绪,接下来我们启动项目,和上一章不同的是,这次我们把启动类单独移出,以免和业务类混在一起。

在控制器所在包的上一层,我们创建

Application.java


@SpringBootApplication
public class Application extends WebMvcConfigurerAdapter {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}

效果预览

运行 main 方法,在浏览器中访问

http://localhost:8088/user

利用Spring boot如何创建简单的web交互应用

当用户名少于 5 位,密码少于 6 位时

利用Spring boot如何创建简单的web交互应用

当用户名密码不正确时

利用Spring boot如何创建简单的web交互应用

最后,登录成功

利用Spring boot如何创建简单的web交互应用

至此,一个简单的 web 交互做好了,当然这里面肯定存在些问题,我也是第一次接触 Spring ,也是第一次以非 JSON 的格式传递数据,在实现这个的过程中,让我觉得还是提供接口简单方便点,哈哈。

接下来要了解的

本章我们快速了解了下 Spring Boot 创建 web 应用。

但是在我们实现的过程中,每当改了类或者资源文件的时候,要想看到效果,只得重新启动项目,这太麻烦了,下一节了解下 Spring Boot 热部署。

并且在本章中,对于用户的验证,我们是写死了的,下一章将整合 Mybatis。

代码已同步到 GitHub, 项目地址 github:sboot-learn,大家也可以通过本地进行下载,点击这里下载

来源:https://huanxi.pub/2016/12/25/Springboot%20创建简单的%20web%20交互应用/

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com