简单搭建 SSM 项目实现登录

目录

    • 项目简介
    • 项目层级介绍,导入依赖
    • 添加配置
    • 业务逻辑实现
    • 前端 JSP 页面实现

项目简介

SSM(Spring、Spring MVC、MyBatis)框架,是一种 Java Web 应用程序开发框架的集合,可以帮助开发者快速搭建 Java Web 应用程序。想要使用 SSM 框架搭建一个简单的登录框架,可以有以下步骤实现:

  1. 创建项目,并引入基础依赖包。
  2. 搭建项目层级目录。
  3. 添加 SSM 基础配置信息。
  4. 后端登录业务逻辑代码实现。
  5. 前端 JSP 页面代码逻辑实现。
  6. 启动项目,访问登录页面,实现登录操作,登录成功则重定向到首页,如果登录失败,则重定向到登录页面。

项目层级介绍,导入依赖

下面是根据以上步骤创建的一个简单的登录框架实现,在代码实现前,请确保本地创建好 SSM 框架,并且目录层级已创建完成,示例代码中的层级结构包括控制层(controller)、业务层(service、serviceImpl)、实体对象(entity)、持久层(dao、mapper)。具体的代码示例如下:

  1. 引入依赖
    
    <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 项目需要添加的部分依赖,可根据实际需求修改添加。

添加配置

  1. 添加配置信息
    • 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>
    

业务逻辑实现

  1. 后端业务代码实现
    • 控制层代码实现
    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 层接口实现:
    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>
    

前端 JSP 页面实现

  1. 前端 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 用于服务运行。

请注意:

  1. 以上示例只是一个简单的登录实现,没有做复杂的业务逻辑实现,密码都是明文实现,并没有做加密处理,在实际使用中请根据实际需求进行修改。
  2. 示例中的框架层级是示例配置,在实际使用中可根据实际需求进行修改。
  3. 示例中的配置文件、数据库连接信息都是本地环境实现,实际使用中可根据实际环境做适配修改。
  4. 请根据实际项目地址将http://yourProjectPath/login修改为实际的项目登录接口地址。

你可能感兴趣的:(Java,java)