一、新建一个maven工程(不会建的小伙伴可以参考Idea引入maven工程依赖(保姆级)-CSDN博客),工程目录如图
js文件可以上up网盘提取
链接:https://pan.baidu.com/s/1yOFtiZBWGJY64fa2tM9CYg?pwd=5555
提取码:5555
二、配置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 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.zl</groupId><artifactId>project01</artifactId><version>1.0-SNAPSHOT</version><packaging>war</packaging><name>project01 Maven Webapp</name><!-- FIXME change it to the project's website --><url>http://www.example.com</url><properties><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><maven.compiler.source>1.7</maven.compiler.source><maven.compiler.target>1.7</maven.compiler.target></properties><dependencies><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.11</version><scope>test</scope></dependency><!--Jackson转换核心包依赖--><dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-core</artifactId><version>2.9.2</version></dependency><!--Jackson转换的数据绑定包依赖--><dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-databind</artifactId><version>2.9.2</version></dependency><!--Jackson JSON转换注解包--><dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-annotations</artifactId><version>2.9.0</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-webmvc</artifactId><version>5.3.26</version></dependency><dependency><groupId>javax.servlet</groupId><artifactId>javax.servlet-api</artifactId><version>3.1.0</version><scope>provided</scope></dependency><dependency><groupId>ch.qos.logback</groupId><artifactId>logback-classic</artifactId><version>1.2.3</version></dependency></dependencies><build><finalName>project01</finalName><pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) --><plugins><plugin><artifactId>maven-clean-plugin</artifactId><version>3.1.0</version></plugin><!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging --><plugin><artifactId>maven-resources-plugin</artifactId><version>3.0.2</version></plugin><plugin><artifactId>maven-compiler-plugin</artifactId><version>3.8.0</version></plugin><plugin><artifactId>maven-surefire-plugin</artifactId><version>2.22.1</version></plugin><plugin><artifactId>maven-war-plugin</artifactId><version>3.2.2</version></plugin><plugin><artifactId>maven-install-plugin</artifactId><version>2.5.2</version></plugin><plugin><artifactId>maven-deploy-plugin</artifactId><version>2.8.2</version></plugin></plugins></pluginManagement></build> </project>
三、配置web.xml文件
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"version="4.0"><servlet><servlet-name>SpringMVC</servlet-name><servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class><init-param><param-name>contextConfigLocation</param-name><param-value>classpath:springMVC.xml</param-value></init-param><load-on-startup>1</load-on-startup></servlet><servlet-mapping><servlet-name>SpringMVC</servlet-name><url-pattern>/</url-pattern></servlet-mapping><!-- 配置编码过滤器 --><filter><filter-name>CharacterEncodingFilter</filter-name><filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class><init-param><param-name>encoding</param-name><param-value>UTF-8</param-value></init-param></filter><filter-mapping><filter-name>CharacterEncodingFilter</filter-name><url-pattern>/*</url-pattern></filter-mapping> </web-app>
四、配置springMVC.xml文件
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans"xmlns:context="http://www.springframework.org/schema/context"xmlns:mvc="http://www.springframework.org/schema/mvc"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/mvchttp://www.springframework.org/schema/mvc/spring-mvc.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context.xsd"><!-- 配置创建 spring 容器要扫描的包 --><context:component-scan base-package="com.zl.controller"/><!-- 配置视图解析器 --><bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"><property name="prefix" value="/WEB-INF/pages/"/><property name="suffix" value=".jsp"/></bean><mvc:annotation-driven /><mvc:default-servlet-handler></mvc:default-servlet-handler></beans>
五、编写LoginController.java类
package com.zl.controller;import com.zl.pojo.User; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody;import javax.servlet.http.HttpSession; import java.util.HashMap; import java.util.Map;@Controller public class LoginController {//主页@RequestMapping("/main")public String main(){return "main";}//登录页@RequestMapping("/ajaxlogin")public String hello(){return "Ajax_login";}/*** Ajax --- 登录验证*/@RequestMapping("/loginAjax")@ResponseBodypublic String loginAjax(User user, Model model, HttpSession session){Map<String,String> resultMap = new HashMap<>();String username = user.getUsername();String password = user.getPassword();if ( null!= username && username.equals("user01")&& null!= password && password.equals("123456")){session.setAttribute("USER_SESSION",user);return "main";}model.addAttribute("msg","用户名或密码错误!");return "error";}}
六、编写LoginInterceptor.java类
package com.zl.interceptor;import org.springframework.web.servlet.HandlerInterceptor;import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession;public class LoginInterceptor implements HandlerInterceptor {@Overridepublic boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {HttpSession session = request.getSession();if (null!= session.getAttribute("USER_SESSION") ){return true;}request.getRequestDispatcher("/WEB-INF/pages/Ajax_login.jsp").forward(request,response);return false;} }
七、Ajax_login.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head><title>Title</title><link rel="stylesheet" href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/3.4.1/css/bootstrap.min.css"><script type="text/javascript"src="${pageContext.request.contextPath }/js/jquery-3.6.0.js"></script> </head> <body> <div><div style="margin: 100px auto;"><div style="width: 600px"><h3>Ajax登录</h3><div style="color: red">${msg}</div>用户名: <input id="username" type="text" name="username" value=""> <br><br>密码: <input id="password" type="password" name="password" value=""> <br><br><button οnclick="login()">提交登录</button></div></div></div><hr/> <br><br><br><br><script type="text/javascript">function login() {var username = $("#username").val();var password = $("#password").val();$.ajax({url: "${pageContext.request.contextPath }/loginAjax",type: "post",data: {username: username, password: password},success: function (response) {console.log(response)if (response=="main"){window.location.href="http://localhost:8080/project01_war_exploded/main";}else {alert("用户名或密码错误!")}}});} </script></body> </html>
注意更改自己tomcat的访问路径
八、编写main.jsp和error.jsp文件
main.jsp:
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head><title>Title</title> </head> <body> <h1>主页</h1><h1>当前用户:${USER_SESSION.username}</h1><br><br></body> </html>
error.jsp:
<%--Created by IntelliJ IDEA.User: 86158Date: 2024/4/4Time: 23:07To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head><title>Title</title> </head> <body> ...error </body> </html>
九、配置tomcat(不会配置的小伙伴可参考Idea添加tomcat-CSDN博客),直接启动
启动成功
这样就成功啦!小伙伴们赶紧run起来吧!欢迎留言和私信up哦!制作不易,给个赞吧!嘻嘻