项目简介
项目使用 SSM 搭建,SSM(Spring、Spring MVC、MyBatis)框架,是一种 Java Web 应用程序开发框架的集合,可以帮助开发者快速搭建 Java Web 应用程序。想要使用 SSM 框架搭建一个简单的登录框架,可以有以下步骤实现:
- 创建项目,并引入基础依赖包。
- 搭建项目层级目录。
- 添加 SSM 基础配置信息。
- 后端登录业务逻辑代码实现。
- 前端 JSP 页面代码逻辑实现。
- 启动项目,访问登录页面,实现登录操作,登录成功则重定向到首页,如果登录失败,则重定向到登录页面。
项目层级介绍,导入依赖
下面是根据以上步骤创建的一个简单的登录框架实现,在代码实现前,请确保本地创建好 SSM 框架,并且目录层级已创建完成,示例代码中的层级结构包括控制层(controller)、业务层(service、serviceImpl)、实体对象(entity)、持久层(dao、mapper)。具体的代码示例如下:
- 引入依赖
以上是 SSM 项目需要添加的部分依赖,可根据实际需求修改添加。<!--SpringMVC的jar包--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.2.2.RELEASE</version> </dependency> <!--mysql连接的jar包--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.18</version> </dependency> <!-- SpringJDBC --> <!-- 注意:与当前项目使用的其它spring依赖保持相同的版本号 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>5.2.2.RELEASE</version> </dependency> <!--数据库连接池dbcp的jar包--> <dependency> <groupId>commons-dbcp</groupId> <artifactId>commons-dbcp</artifactId> <version>1.4</version> </dependency> <!--MyBatis的jar包--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.3</version> </dependency> <!--Spring整合MyBatis的jar包--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>2.0.3</version> </dependency> <!--测试包--> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.0</version> <scope>provided</scope> </dependency>
添加配置
添加配置信息
applicationContext.xml
应用上下文配置:<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:util="http://www.springframework.org/schema/util" 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/util http://www.springframework.org/schema/util/spring-util.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd"> <!-- 自动扫描,扫描包路径可根据实际项目包路径修改 --> <context:component-scan base-package="com.ssm.dao"></context:component-scan> <context:component-scan base-package="com.ssm.service"></context:component-scan> <context:component-scan base-package="com.ssm.service.impl"></context:component-scan> <util:properties id="properties" location="classpath:jdbc.properties"/> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"> <property name="url" value="#{properties.url}"/> <property name="driverClassName" value="#{properties.driver}" /> <property name="username" value="#{properties.username}" /> <property name="password" value="#{properties.password}" /> <property name="initialSize" value="#{properties.initialSize}" /> <property name="maxActive" value="#{properties.maxActive}" /> </bean> <!-- 配置MapperScannerConfigurer --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <!-- 配置接口文件位置 --> <property name="basePackage" value="mapper" /> </bean> <!-- 配置SqlSessionFactoryBean,可根据实际需求修改 --> <bean class="org.mybatis.spring.SqlSessionFactoryBean"> <!-- 配置XML文件在哪里 --> <property name="mapperLocations" value="classpath:mappers/*.xml" /> <!-- 配置使用哪个数据源连接数据库 --> <property name="dataSource" ref="dataSource" /> </bean> <!-- spring自动查找其下的类,可根据实际需求修改 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.ssm.dao"></property> </bean> </beans>
springmvc.xml
SSM 项目相关组件和配置<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 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"> <!--配置包扫描,扫描到加注解的类自动创建bean组件--> <context:component-scan base-package="com.ssm.controller"/> <!-- 2.配置映射处理和适配器--> <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/> <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"/> <!-- 3.视图的解析器--> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/" /> <property name="suffix" value=".jsp" /> </bean> </beans>
jdbc.properties
数据库配置文件
以上配置是数据库的连接信息,包括数据库账号、密码、连接驱动等信息。# 数据库连接地址 url=jdbc:mysql://localhost:3306/ssm?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai # 数据库连接驱动 driver=com.mysql.cj.jdbc.Driver # 数据库连接账号 username=username # 数据库连接密码 password=password # 连接池的初始大小 initialSize=2 # 连接池的最大活动连接数 maxActive=10
web.xml
配置<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <display-name>Archetype Created Web Application</display-name> <!--配置过滤器,解决中文乱码 --> <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> <!--配置spring监听器,默认只加载WEB-INF文件下面的applicationContext.xml配置文件 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!--改变默认配置文件路径 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param> <!--前端控制器 --> <servlet> <servlet-name>dispatcherServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!--servlet加载springmvc配置文件 --> <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>dispatcherServlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
业务逻辑实现
后端业务代码实现
- 控制层代码实现
import com.ssm.entity.User; import com.ssm.service.UserService; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import javax.annotation.Resource; import java.util.ArrayList; import java.util.List; import java.util.Map; @Controller public class UserController { @Resource UserService userService; @ResponseBody @RequestMapping(value = "/login", method = RequestMethod.POST, produces = "application/json;charset=UTF-8") public String login(User user){ List<Map<String, Object>> list = new ArrayList<Map<String,Object>>(); try { Map<String, Object> map = userService.login(user); list.add(map); return "登录成功!"; } catch (Exception e) { e.printStackTrace(); return "登录失败!"; } } }
- 业务层代码实现
业务层接口代码:
业务层接口实现代码:import com.ssm.entity.User; import java.util.Map; public interface UserService { public Map<String, Object> login(User user); }
import com.ssm.dao.UserDao; import com.ssm.entity.User; import com.ssm.service.UserService; import org.springframework.stereotype.Service; import javax.annotation.Resource; import java.util.HashMap; import java.util.Map; @Service public class UserServiceImpl implements UserService { @Resource UserDao userDao; @Override public Map<String, Object> login(User user) { Map<String, Object> map = new HashMap<String, Object>(); map.put("data", userDao.login(user)); return map; } }
- 实体对象代码实现
import lombok.Data; import java.io.Serializable; @Data public class User implements Serializable { private static final long serialVersionUID = 1L; public int id; public String userNo; public String userName; public String pwd; public String sex; public int age; public String job; public String phone; @Override public String toString() { return "User [id=" + id + ", userNo=" + userNo + ", userName=" + userName + ", pwd=" + pwd + ", sex=" + sex + ", age=" + age + ", job=" + job + ", phone=" + phone + "]"; } }
- 持久层代码实现
dao 层接口实现:
mapper 层代码实现:import com.ssm.entity.User; public interface UserDao { public User login(User user); }
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.ssm.dao.UserDao"> <resultMap type="com.ssm.entity.User" id="UserResult"> <id property="id" column="id"></id> <result property="userName" column="user_name"></result> <result property="pwd" column="password"></result> </resultMap> <select id="login" parameterType="com.ssm.entity.User" resultMap="UserResult"> select * from user where user_name=#{userName} and password=#{pwd} </select> </mapper>
前端 JSP 页面实现
前端 JSP 页面实现
login.jsp
页面<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>用户登录页面</title> </head> <body> <form id="loginForm" action="requestParam.jsp" method="post"> 用户名:<input type="text" name="userName" value="${userName}"/><br/> 密码:<input type="password" name="pwd" value="${pwd}"/><br/> <input type="submit" value="登录"/><br/> <font color="red">${errorMsg}</font> </form> </body> </html>
requestParam.jsp
登录页面发送请求页面<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ page import="com.ssm.entity.User" %> <%@ page import="java.io.OutputStream" %> <%@ page import="java.io.OutputStreamWriter" %> <%@ page import="com.google.gson.Gson" %> <%@ page import="java.net.URLEncoder" %> <%@ page import="java.net.HttpURLConnection" %> <%@ page import="java.io.IOException" %> <% // 获取表单提交的参数 User user = new User(); user.setUserName(request.getParameter("userName")); user.setPwd(request.getParameter("pwd")); // 构造请求参数 String requestData = "myParams=" + URLEncoder.encode(new Gson().toJson(user), "UTF-8"); // 请求的URL String requestUrl = "http://yourProjectPath/login"; OutputStreamWriter outWriter = null; try { // 创建连接 HttpURLConnection connection = (HttpURLConnection) new java.net.URL(requestUrl).openConnection(); // 设置请求方法为POST connection.setRequestMethod("POST"); // 设置请求头 connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); // 发送请求参数 connection.setDoOutput(true); OutputStream outputStream = connection.getOutputStream(); outputStream.write(requestData.getBytes("UTF-8")); outputStream.flush(); outputStream.close(); // 获取响应码 int responseCode = connection.getResponseCode(); // 判断请求是否成功 if (responseCode == HttpURLConnection.HTTP_OK) { // 请求成功,重定向到指定页面 response.sendRedirect("index.jsp"); } else { // 请求失败,重定向到登录页面重新登录 response.sendRedirect("login.jsp"); } } catch (IOException e) { e.printStackTrace(); } %>
index.jsp
页面<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>首页面</title> </head> <body> <div> <h1>登录成功!</h1> </div> </body> </html>
以上示例使用 SSM 搭建了一个简单的登录实现,需要注意的是,Java Web 项目需要依赖 Tomcat 环境运行,所以需要本地安装 Tomcat 用于服务运行。
请注意:
- 以上示例只是一个简单的登录实现,没有做复杂的业务逻辑实现,密码都是明文实现,并没有做加密处理,在实际使用中请根据实际需求进行修改。
- 示例中的框架层级是示例配置,在实际使用中可根据实际需求进行修改。
- 示例中的配置文件、数据库连接信息都是本地环境实现,实际使用中可根据实际环境做适配修改。
- 请根据实际项目地址将
http://yourProjectPath/login
修改为实际的项目登录接口地址。