Spring MVC 是 Spring 提供的一个基于 MVC 设计模式的轻量级 Web 开发框架。
JSTL(Java server pages standarded tag library,即JSP标准标签库)是由JCP(Java community Proces)所制定的标准规范,它主要提供给Java Web开发人员一个标准通用的标签库。
Springmvc: https://docs.spring.io/spring-framework/docs/current/reference/html/web.html
JSTL: https://tomcat.apache.org/taglibs/standard/
1. 开发环境
系统:Windows 10 Home
开发工具:IntelliJ IDEA 2020.1.4 (Community Edition)
Java, Maven 和 IDEA 的安装配置过程,见IDEA创建Maven Quickstart项目
2. 在 IDEA上创建项目
Name: SpringmvcLogin
GroupId: com.example
ArtifactId: SpringmvcLogin
项目目录结构、如何添加 tomcat7-maven-plugin,参考 IDEA创建Maven Webapp项目
3. 导入 spring-webmvc, servlet, jstl
访问 http://www.mvnrepository.com/,查询 ...
修改 pom.xml
...
...
...
...
在IDE中项目列表 -> 点击鼠标右键 -> Maven -> Reload Project
4. 支持 SpringMVC
1) 修改 src/main/webapp/WEB-INF/web.xml
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
...
...
2) 添加 src/main/resources/springmvc-beans.xml (中间目录如果不存在,新建目录,下同)
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd" default-init-method="init" default-destroy-method="destroy">
5. 支持静态资源 (html/js/css/images)
1) 修改 src/main/resources/springmvc-beans.xml
...
...
新建目录 src/main/webapp/static
2) 添加 jQuery
从 https://jquery.com/ 下载 JQuery 包,添加到:
src/main/webapp/static/js/jquery-1.12.2.min.js
* jQuery版本根据项目需要,这里用1.12.2, CSS和图片也是放到static目录下
3) 添加 src/main/webapp/static/test.html
Static HTML Page
$(document).ready(function() {
console.log("Static HTML Page");
$("#message").html("JQuery is ready");
});
http://localhost:9090/static/test.html
6. 添加 Login 拦截器
1)添加 src/main/java/com/example/interceptor/LoginInterceptor.java
package com.example.interceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
public class LoginInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response, Object handler) throws Exception {
// Session
if (request.getSession().getAttribute("logged_user") != null)
return true;
// 请求转发
//request.getRequestDispatcher(request.getContextPath() + "/login").forward(request, response);
// 重定向
response.sendRedirect(request.getContextPath() + "/login");
return false;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response,
Object handler, ModelAndView modelAndView) throws Exception {
// TODO Auto-generated method stub
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception exception) throws Exception {
// TODO Auto-generated method stub
}
}
2) 修改 src/main/resources/springmvc-beans.xml
...
...
7. 视图和控制器
1) 添加 src/main/webapp/WEB-INF/jsp/home.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" isELIgnored="false" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
Home Page
Welcome ${sessionScope.logged_user}, Logout
${message}
$(document).ready(function() {
console.log("Home Page");
});
2) 添加 src/main/webapp/WEB-INF/jsp/login.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" isELIgnored="false" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
Login Page
${message}
$(document).ready(function() {
console.log("Login Page");
});
function login() {
var username = $("#username").val();
if (username == '') {
alert("Please enter username");
$("#username").focus();
return;
}
var password = $("#password").val();
if (password == '') {
alert("Please enter password");
$("#password").focus();
return;
}
$("#loginForm").submit();
}
3) 添加 src/main/java/com/example/controller/IndexController.java
package com.example.controller;
import javax.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.ui.ModelMap;
@Controller
@RequestMapping("/")
public class IndexController {
@RequestMapping(method = RequestMethod.GET)
public String home(ModelMap modelMap) {
modelMap.addAttribute("message", "Springmvc Login Demo");
return "home";
}
@RequestMapping(value="/login", method = RequestMethod.GET)
public String login() {
return "login";
}
@RequestMapping(value="/login/post", method = RequestMethod.POST)
public String loginPost(String username, String password, HttpSession session, ModelMap modelMap) {
if ("admin".equals(username) && "123456".equals(password)) {
session.setAttribute("logged_user", username);
return "redirect:/";
}
modelMap.addAttribute("message", "Invalid username or password");
return "login";
}
@RequestMapping(value = "/logout", method = RequestMethod.GET)
public String logout(HttpSession session) {
session.invalidate();
return "redirect:/login";
}
}
8. 运行
跳转到第 2 步,在IDEA里用 tomcat7-maven-plugin 运行 (参考 IDEA创建Maven Webapp项) 。
Tomcat 环境下,注解里的 “/” 和 src/main/webapp/index.jsp 会有冲突,可以删除 index.jsp, 或在 WEB-INF/web.xml 添加:
访问 http://localhost:9090 会自动跳转到 http://localhost:9090/login
Username: admin
Password: 123456