SSM(Spring、Spring MVC、MyBatis)框架,是一种 Java Web 应用程序开发框架的集合,可以帮助开发者快速搭建 Java Web 应用程序。想要使用 SSM 框架搭建一个简单的登录框架,可以有以下步骤实现:
下面是根据以上步骤创建的一个简单的登录框架实现,在代码实现前,请确保本地创建好 SSM 框架,并且目录层级已创建完成,示例代码中的层级结构包括控制层(controller)、业务层(service、serviceImpl)、实体对象(entity)、持久层(dao、mapper)。具体的代码示例如下:
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-webmvcartifactId>
<version>5.2.2.RELEASEversion>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>8.0.18version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-jdbcartifactId>
<version>5.2.2.RELEASEversion>
dependency>
<dependency>
<groupId>commons-dbcpgroupId>
<artifactId>commons-dbcpartifactId>
<version>1.4version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>3.5.3version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatis-springartifactId>
<version>2.0.3version>
dependency>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>4.12version>
<scope>testscope>
dependency>
<dependency>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
<version>1.18.0version>
<scope>providedscope>
dependency>
以上是 SSM 项目需要添加的部分依赖,可根据实际需求修改添加。applicationContext.xml
应用上下文配置:
<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>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="mapper" />
bean>
<bean class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="mapperLocations" value="classpath:mappers/*.xml" />
<property name="dataSource" ref="dataSource" />
bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.ssm.dao">property>
bean>
beans>
springmvc.xml
SSM 项目相关组件和配置
<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">
<context:component-scan base-package="com.ssm.controller"/>
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/>
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"/>
<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
配置
<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 Applicationdisplay-name>
<filter>
<filter-name>characterEncodingFilterfilter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
<init-param>
<param-name>encodingparam-name>
<param-value>UTF-8param-value>
init-param>
filter>
<filter-mapping>
<filter-name>characterEncodingFilterfilter-name>
<url-pattern>/*url-pattern>
filter-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
listener>
<context-param>
<param-name>contextConfigLocationparam-name>
<param-value>classpath:applicationContext.xmlparam-value>
context-param>
<servlet>
<servlet-name>dispatcherServletservlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
<init-param>
<param-name>contextConfigLocationparam-name>
<param-value>classpath:springmvc.xmlparam-value>
init-param>
<load-on-startup>1load-on-startup>
servlet>
<servlet-mapping>
<servlet-name>dispatcherServletservlet-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 + "]";
}
}
import com.ssm.entity.User;
public interface UserDao {
public User login(User user);
}
mapper 层代码实现:
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>
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
修改为实际的项目登录接口地址。