红茶的个人站点

  • 首页
  • 专栏
  • 开发工具
  • 其它
  • 隐私政策
Awalon
Talk is cheap,show me the code.
  1. 首页
  2. 其它
  3. 正文

Spring Boot 学习笔记4:JSP

2023年9月21日 1039点热度 0人点赞 0条评论

1.准备工作

创建一个 SpringBoot 项目,并勾选必要的依赖。

因为要使用 JSP 作为前端页面,所以这里需要将打包方式修改为war:

<packaging>war</packaging>

添加 JSTL 依赖:

<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>jstl</artifactId>
    <version>1.2</version>
</dependency>

添加解析 JSP 页面的依赖:

<!--用于解析jsp页面-->
<dependency>
    <groupId>org.apache.tomcat.embed</groupId>
    <artifactId>tomcat-embed-jasper</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-tomcat</artifactId>
    <scope>provided</scope>
</dependency>

现在直接访问 http://localhost/jsp/user/login.jsp 就可以看到 JSP 页面。

2.案例:登录

SpringBoot 使用内置的 Web 服务器软件,一般是 Tomcat,也可以换成 Jetty 或其它。这些 Web 服务器软件是基于 JavaEE 的,所以支持 Servlet/JSP/Filter/Listener 这些技术。

2.1.Filter

因此在 SpringBoot 中我们依然可以使用 Filter 对请求进行过滤,以实现一些特殊用途,比如登录检查。

默认 SpringBoot 是不会扫描并注册 Servlet 组件到 Web 服务器的,如果要开启扫描,需要在配置类添加@ServletComponentScan注解:

@ServletComponentScan
@SpringBootApplication
public class JspDemoApplication {
​
    public static void main(String[] args) {
        SpringApplication.run(JspDemoApplication.class, args);
    }
​
}

定义一个过滤器:

@WebFilter("/*")
public class LoginFilter implements Filter {
​
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        // 不需要登录也能访问的 url
        String[] noLoginUrls = {"/static/", "/jsp/user/login.jsp", "/user/login"};
        if (!(request instanceof HttpServletRequest) ||
                !(response instanceof HttpServletResponse)) {
            throw new RuntimeException("这不是一个 HTTP 请求");
        }
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        String uri = httpServletRequest.getRequestURI();
        for(String u :noLoginUrls){
            if (uri.indexOf(u) == 0){
                // 当前请求路径与不需要登录的路径匹配,直接放行
                chain.doFilter(httpServletRequest, httpServletResponse);
                return;
            }
        }
        // 检查是否已经登录
        HttpSession session = httpServletRequest.getSession();
        String username = (String) session.getAttribute("username");
        if (username == null){
            // 需要登录,跳转到登录页
            httpServletResponse.sendRedirect("/jsp/user/login.jsp");
            return;
        }
        // 已经登录,放行
        chain.doFilter(httpServletRequest, httpServletResponse);
    }
}

2.2.Controller

在 Controller 中实现相应的登录功能:

@Controller
@RequestMapping("/user")
public class UserController {
    private static final String LOGIN_URL = "/jsp/user/login.jsp";
    private static Map<String, String> users = new HashMap<>();
​
    static {
        users.put("icexmoon", "123");
    }
​
    /**
     * 登录
     *
     * @return
     */
    @PostMapping("/login")
    public String login(@RequestParam("username") String username,
                        @RequestParam("password") String password,
                        Model model,
                        HttpServletRequest httpServletRequest) {
        String correctPassword = users.get(username);
        if (correctPassword == null || correctPassword.isEmpty()) {
            // 帐号不存在
            model.addAttribute("errorMsg", "帐号不存在");
            // 加载登录页
            return LOGIN_URL;
        }
        // 检查密码是否正确
        if (!correctPassword.equals(password)) {
            // 密码不正确
            model.addAttribute("errorMsg", "密码不正确");
            // 加载登录页
            return LOGIN_URL;
        }
        // 密码正确,将登录凭证写入 session
        HttpSession session = httpServletRequest.getSession();
        session.setAttribute("username", username);
        // 跳转到用户主页
        return "redirect:/jsp/user/home.jsp";
    }
​
    /**
     * 加载用户主页
     *
     * @return
     */
    @GetMapping("/home")
    public String homePage(Model model, HttpServletRequest request) {
        String username = (String) request.getSession().getAttribute("username");
        model.addAttribute("username", username);
        return "/jsp/user/home.jsp";
    }
​
    /**
     * 注销用户
     *
     * @return
     */
    @GetMapping("/logout")
    public String logout(HttpServletRequest request) {
        request.getSession().invalidate();
        return "redirect:" + LOGIN_URL;
    }
}

这里没有使用数据库,只是简单使用一个内存中的 Map 作为用户账户信息。

数据传输和页面加载及跳转,是 SpringMVC 的功能,这里不再赘述。

The End,谢谢阅读。

本文的完整示例代码可以从这里获取。

本作品采用 知识共享署名 4.0 国际许可协议 进行许可
标签: jsp spring
最后更新:2023年9月21日

魔芋红茶

加一点PHP,加一点Go,加一点Python......

点赞
< 上一篇
下一篇 >

文章评论

razz evil exclaim smile redface biggrin eek confused idea lol mad twisted rolleyes wink cool arrow neutral cry mrgreen drooling persevering
取消回复

COPYRIGHT © 2021 icexmoon.cn. ALL RIGHTS RESERVED.
本网站由提供CDN加速/云存储服务

Theme Kratos Made By Seaton Jiang

宁ICP备2021001508号

宁公网安备64040202000141号