在pom.xml文件里添加相关依赖
<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
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0modelVersion>
<groupId>net.hf.springgroupId>
<artifactId>SpringMvcDemo02artifactId>
<version>1.0-SNAPSHOTversion>
<properties>
<spring.version>5.3.25spring.version>
properties>
<dependencies>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-coreartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-beansartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-contextartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-testartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-jdbcartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>5.1.49version>
dependency>
<dependency>
<groupId>com.alibabagroupId>
<artifactId>druidartifactId>
<version>1.1.24version>
dependency>
<dependency>
<groupId>log4jgroupId>
<artifactId>log4jartifactId>
<version>1.2.17version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-aopartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>aspectjgroupId>
<artifactId>aspectjrtartifactId>
<version>1.5.4version>
dependency>
<dependency>
<groupId>org.aspectjgroupId>
<artifactId>aspectjweaverartifactId>
<version>1.9.6version>
<scope>runtimescope>
dependency>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>4.13version>
<scope>testscope>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-webartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-webmvcartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>javax.servletgroupId>
<artifactId>jstlartifactId>
<version>1.2version>
dependency>
<dependency>
<groupId>javax.servletgroupId>
<artifactId>javax.servlet-apiartifactId>
<version>3.1.0version>
<scope>providedscope>
dependency>
<dependency>
<groupId>com.fasterxml.jackson.coregroupId>
<artifactId>jackson-coreartifactId>
<version>2.9.7version>
dependency>
<dependency>
<groupId>com.fasterxml.jackson.coregroupId>
<artifactId>jackson-databindartifactId>
<version>2.9.7version>
dependency>
<dependency>
<groupId>com.fasterxml.jackson.coregroupId>
<artifactId>jackson-annotationsartifactId>
<version>2.9.7version>
dependency>
<dependency>
<groupId>com.fasterxml.jackson.dataformatgroupId>
<artifactId>jackson-dataformat-xmlartifactId>
<version>2.5.3version>
dependency>
dependencies>
project>
在resources目录里创建log4j.properties
log4j.rootLogger=WARN, stdout, logfile
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m%n
log4j.appender.logfile=org.apache.log4j.FileAppender
log4j.appender.logfile.File=target/springmvc.log
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
log4j.appender.logfile.layout.ConversionPattern=%d %p [%c] - %m%n
在resources里创建templates子目录,然后在里面创建index.jsp
<%@ page import="java.util.Date" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>首页</title>
</head>
<body>
<h1 style="text-align: center">Welcome to Spring MVC World~</h1>
<h3 style="text-align: center"><%= new Date() %></h3> <!--JSP表达式元素-->
</body>
</html>
创建net.hf.spring.config包,然后在里面创建SpringMvcConfig类
package net.hf.spring.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;
/**
* 功能:Spring MVC配置类
* 作者:hf
* 日期:2023年03月22日
*/
@Configuration // 表明当前类是配置类
@EnableWebMvc // 启用Web MVC功能
@ComponentScan("net.hf.spring") // 组件扫描
public class SpringMvcConfig {
// 定义内部资源视图解析器
@Bean
public InternalResourceViewResolver viewResolver() {
// 创建内部资源视图解析器对象
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
// 设置内部资源视图解析器对象属性
viewResolver.setViewClass(JstlView.class); // 设置视图类
viewResolver.setPrefix("/WEB-INF/classes/templates/"); // 设置前缀
viewResolver.setSuffix(".jsp"); // 设置后缀
// 返回内部资源视图解析器对象
return viewResolver;
}
}
在net.hf.spring.config包里里创建MyWebAppInitializer类
package net.hf.spring.config;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
/**
* 功能:Web应用初始化配置类
* 作者:hf
* 日期:2023年03月22日
*/
public class MyWebAppInitializer implements WebApplicationInitializer {
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
// 创建Web应用容器(基于注解配置类的Web应用容器)
AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
// 注册配置类
context.register(SpringMvcConfig.class); // 对应先前的spring-mvc-config.xml文件
// 绑定当前的ServletContext对象 - 方法的参数(servletContext)
context.setServletContext(servletContext);
// 注册Spring MVC的前端控制器(DispatcherServlet)
ServletRegistration.Dynamic servlet = servletContext.addServlet("dispatcher", new DispatcherServlet(context));
// 过滤一切资源请求
servlet.addMapping("/");
// 设置启动加载顺序
servlet.setLoadOnStartup(1);
}
}
创建net.hf.spring.controller子包,然后在里面创建DemoController类
package net.hf.spring.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
/**
* 功能:演示控制器
* 作者:hf
* 日期:2023年03月22日
*/
@Controller
public class DemoController {
@GetMapping("/index")
public String index() {
// 返回逻辑视图名
return "index";
}
}
单击【OK】按钮,可以看到SpringMvcDemo02就已经部署到服务器上了
访问http://localhost:8080/SpringMvcDemo02/index
重启服务器,访问http://localhost:8080/SpringMvcDemo02/
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>用户登录</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" >
<!--脚本文件采用的是虚拟路径-->
<script src="js/check.js" type="text/javascript"></script>
<!--脚本文件采用的是虚拟路径-->
<link href="css/login.css" rel="stylesheet" type="text/css">
</head>
<body>
<h3 style="text-align: center">用户登录</h3>
<form id="frmLogin" action="login" method="post">
<table class="tb" border="1" cellpadding="10" style="margin: 0px auto">
<tr>
<td align="center">账号</td>
<td><input id="username" type="text" name="username"/></td>
</tr>
<tr>
<td align="center">密码</td>
<td><input id="password" type="password" name="password"/></td>
</tr>
<tr align="center">
<td colspan="2">
<input type="submit" value="登录" onclick="return checkLoginForm()"/>
<input type="reset" value="重置"/>
</td>
</tr>
</table>
</form>
</body>
</html>
登录成功页面 - success.jsp(必须是动态页面,因为要获取会话对象中的数据)
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>登录成功</title>
</head>
<body>
<h1 style="text-align: center">${username},登录成功!</h1>
</body>
</html>
如果不用JSP的标签库,要获取会话中的数据,要复杂一点
<h1 style="text-align: center">${username},登录成功!</h1>
<h1 style="text-align: center"><%= request.getSession().getAttribute("username")%>,登录成功!</h1>
登录失败页面 - failure.jsp(必须是动态页面,因为要获取会话对象中的数据)
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>登录失败</title>
</head>
<body>
<h1 style="text-align: center">${username},登录失败!</h1>
</body>
</html>
<%@ page import="java.util.Date" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>首页</title>
</head>
<body style="text-align: center">
<h1>Welcome to Spring MVC World~</h1>
<h3><%= new Date() %></h3> <!--JSP表达式元素-->
<a href="toLogin">跳转到登录页面</a>
</body>
</html>
package net.hf.spring.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;
/**
* 功能:Spring MVC配置类
* 作者:hf
* 日期:2023年03月22日
*/
@Configuration // 表明当前类是配置类
@EnableWebMvc // 启用Web MVC功能
@ComponentScan("net.hf.spring") // 组件扫描
public class SpringMvcConfig implements WebMvcConfigurer {
// 定义内部资源视图解析器
@Bean
public InternalResourceViewResolver viewResolver() {
// 创建内部资源视图解析器对象
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
// 设置内部资源视图解析器对象属性
viewResolver.setViewClass(JstlView.class); // 设置视图类
viewResolver.setPrefix("/WEB-INF/classes/templates/"); // 设置前缀
viewResolver.setSuffix(".jsp"); // 设置后缀
// 返回内部资源视图解析器对象
return viewResolver;
}
// 添加视图控制器,实现纯粹的页面跳转
@Override
public void addViewControllers(ViewControllerRegistry registry) {
// addViewController的参数是请求路径,setViewName的参数是逻辑视图名
registry.addViewController("/toLogin").setViewName("login");
}
}
在net.hf.spring.controller包里创建LoginController类
package net.hf.spring.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import javax.servlet.http.HttpSession;
/**
* 功能:登录控制器
* 作者:hf
* 日期:2023年03月28日
*/
@Controller
public class LoginController {
@RequestMapping("/login") // 必须加"/"
public String login(@RequestParam("username") String username,
@RequestParam("password") String password,
HttpSession session,
HttpSession response) throws Exception{
// 对用户名编码
String uname = new String(username.getBytes("ISO-8859-1"),"utf-8");
// 将登陆用户名写入会话对象
session.setAttribute("username", uname);
// 直接判断用户是否登录成功
if (uname.equals("橙子") && password.equals("123456")) {
// 通过逻辑视图名'success'跳转到成功页面
return "success"; // 逻辑视图名
} else {
// 通过逻辑视图名'failure'跳转到失败页面
return "failure"; // 逻辑视图名
}
}
}
启动服务器,显示首页
在resources里创建static目录,在static里创建images、css和js目录
/* 登录页面样式 */
body {
margin: 0px;
text-align: center;
background: cornsilk;
}
/**
* 检验登录表单
*
* @returns {Boolean}
*/
function checkLoginForm() {
// 获取用户名文本框
var username = document.getElementById("username");
// 获取密码文本框
var password = document.getElementById("password");
// 非空校验
if (username.value == "") {
alert("用户名不能为空!");
// 让用户名文本框获得焦点
username.focus();
return false;
}
if (password.value == "") {
alert("密码不能为空!");
// 让密码文本框获得焦点
password.focus();
return false;
}
return true; // 表明可以提交数据到服务器端
}
Spring MVC配置类 - SpringMvcConfig
package net.hf.spring.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;
/**
* 功能:Spring MVC配置类
* 作者:hf
* 日期:2023年03月22日
*/
@Configuration // 表明当前类是配置类
@EnableWebMvc // 启用Web MVC功能
@ComponentScan("net.hf.spring") // 组件扫描
public class SpringMvcConfig implements WebMvcConfigurer {
// 定义内部资源视图解析器
@Bean
public InternalResourceViewResolver viewResolver() {
// 创建内部资源视图解析器对象
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
// 设置内部资源视图解析器对象属性
viewResolver.setViewClass(JstlView.class); // 设置视图类
viewResolver.setPrefix("/WEB-INF/classes/templates/"); // 设置前缀
viewResolver.setSuffix(".jsp"); // 设置后缀
// 返回内部资源视图解析器对象
return viewResolver;
}
// 添加视图控制器,实现纯粹的页面跳转
@Override
public void addViewControllers(ViewControllerRegistry registry) {
// addViewController的参数是请求路径,setViewName的参数是逻辑视图名
registry.addViewController("/toLogin").setViewName("login");
}
// 添加资源处理器,实现静态资源的映射
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
// 处理图片静态资源(第一个参数是虚拟路径,第二个参数是物理路径)
registry.addResourceHandler("/images/**")
.addResourceLocations("classpath:/static/images/");
// 处理样式静态资源(第一个参数是虚拟路径,第二个参数是物理路径)
registry.addResourceHandler("/css/**")
.addResourceLocations("classpath:/static/css/");
// 处理脚本静态资源(第一个参数是虚拟路径,第二个参数是物理路径)
registry.addResourceHandler("/js/**")
.addResourceLocations("classpath:/static/js/");
}
}
单击【跳转到登录页面】超链接,背景色改了,说明登录样式导入成功,起作用了