ssm登录

Posted 冷血~多好

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ssm登录相关的知识,希望对你有一定的参考价值。

明晚一定早点睡----------

 

项目目录

首先配置xml文件(spring的配置文件可以全部整合到一起,但是为了区分)

spring-dao.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: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
       https://www.springframework.org/schema/context/spring-context.xsd">

    <!-- 配置整合mybatis -->
    <!-- 1.关联数据库文件 -->
    <context:property-placeholder location="classpath:database.properties"/>

    <!-- 2.数据库连接池 -->
    <!--数据库连接池
        dbcp 半自动化操作 不能自动连接
        c3p0 自动化操作(自动的加载配置文件 并且设置到对象里面)
    -->

    <!-- <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
         <property name="driverClassName" value="${jdbc.driver}"/>
         <property name="url" value="${jdbc.url}"/>
         <property name="username" value="${jdbc.username}"/>
         <property name="password" value="${jdbc.password}"/>
     </bean>-->

    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <!--  配置连接池属性-->
        <property name="driverClass" value="${jdbc.driver}"/>
        <property name="jdbcUrl" value="${jdbc.url}"/>
        <property name="user" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>

        <!--c3p0连接池的私有属性-->
        <property name="maxPoolSize" value="30"/>
        <property name="minPoolSize" value="10"/>
        <!-- 关闭连接后不自动commit-->
        <property name="autoCommitOnClose" value="false"/>
        <!-- 获取连接超时时间-->
        <property name="checkoutTimeout" value="10000"/>
        <!--  当获取连接失败重试次数-->
        <property name="acquireRetryAttempts" value="2"/>
    </bean>


    <!-- 3.配置SqlSessionFactory对象 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 注入数据库连接池 -->
        <property name="dataSource" ref="dataSource"/>
        <!-- 配置MyBaties全局配置文件:mybatis-config.xml -->
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
    </bean>

    <!-- 4.配置扫描Dao接口包,动态实现Dao接口注入到spring容器中 -->
    <!--解释 :https://www.cnblogs.com/jpfss/p/7799806.html-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!-- 注入sqlSessionFactory -->
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
        <!-- 给出需要扫描Dao接口包 -->
        <property name="basePackage" value="com.chen.dao"/>
    </bean>


</beans>

spring-mvc.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:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       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
   http://www.springframework.org/schema/mvc
   https://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <!-- 配置SpringMVC -->
    <!-- 1.开启SpringMVC注解驱动 -->
    <mvc:annotation-driven />
    <!-- 2.静态资源默认servlet配置-->
    <mvc:default-servlet-handler/>

    <!--配置静态资源的访问映射,此设置中的文件,将不被前端控制器拦截-->
   <!-- <mvc:resources mapping="/statics/js/**" location="statics/js/"/>
    <mvc:resources mapping="/statics/css/**" location="statics/css/"/>
    <mvc:resources mapping="/statics/js/**" location="statics/images/"/>
-->
    <!-- 3.配置jsp 显示ViewResolver视图解析器 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
       <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
        <property name="prefix" value="/WEB-INF/view/" />
        <property name="suffix" value=".jsp" />
    </bean>

    <!--解决json返回数据乱码-->
    <mvc:annotation-driven>
        <mvc:message-converters register-defaults="true">
            <bean class="org.springframework.http.converter.StringHttpMessageConverter">
                <constructor-arg value="UTF-8"/>
            </bean>
            <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
                <property name="objectMapper">
                    <bean class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean">
                        <property name="failOnEmptyBeans" value="false"/>
                    </bean>
                </property>
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>


    <!--关于拦截器的配置-->
   <mvc:interceptors>
        <mvc:interceptor>
            <!--/** 包括路径及其子路径-->
            <!--/admin/* 拦截的是/admin/add等等这种 , /admin/add/user不会被拦截-->
            <!--/admin/** 拦截的是/admin/下的所有-->
         <mvc:mapping path="/**"/>
            <!--不拦截静态资源-->
            <mvc:exclude-mapping path="/statics/**"/>
            <!--bean配置的就是拦截器-->
            <bean  class="com.chen.interceptor.LoginInterceptor"/>
        </mvc:interceptor>
    </mvc:interceptors>



    <!-- 4.扫描web相关的bean -->
    <context:component-scan base-package="com.chen.controller" />
</beans>

spring-service.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:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       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
   http://www.springframework.org/schema/mvc
   https://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <!-- 配置SpringMVC -->
    <!-- 1.开启SpringMVC注解驱动 -->
    <mvc:annotation-driven />
    <!-- 2.静态资源默认servlet配置-->
    <mvc:default-servlet-handler/>

    <!--配置静态资源的访问映射,此设置中的文件,将不被前端控制器拦截-->
   <!-- <mvc:resources mapping="/statics/js/**" location="statics/js/"/>
    <mvc:resources mapping="/statics/css/**" location="statics/css/"/>
    <mvc:resources mapping="/statics/js/**" location="statics/images/"/>
-->
    <!-- 3.配置jsp 显示ViewResolver视图解析器 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
       <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
        <property name="prefix" value="/WEB-INF/view/" />
        <property name="suffix" value=".jsp" />
    </bean>

    <!--解决json返回数据乱码-->
    <mvc:annotation-driven>
        <mvc:message-converters register-defaults="true">
            <bean class="org.springframework.http.converter.StringHttpMessageConverter">
                <constructor-arg value="UTF-8"/>
            </bean>
            <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
                <property name="objectMapper">
                    <bean class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean">
                        <property name="failOnEmptyBeans" value="false"/>
                    </bean>
                </property>
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>


    <!--关于拦截器的配置-->
   <mvc:interceptors>
        <mvc:interceptor>
            <!--/** 包括路径及其子路径-->
            <!--/admin/* 拦截的是/admin/add等等这种 , /admin/add/user不会被拦截-->
            <!--/admin/** 拦截的是/admin/下的所有-->
         <mvc:mapping path="/**"/>
            <!--不拦截静态资源-->
            <mvc:exclude-mapping path="/statics/**"/>
            <!--bean配置的就是拦截器-->
            <bean  class="com.chen.interceptor.LoginInterceptor"/>
        </mvc:interceptor>
    </mvc:interceptors>



    <!-- 4.扫描web相关的bean -->
    <context:component-scan base-package="com.chen.controller" />
</beans>

 

applicationContext.xml(合并spring 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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd">

    <import resource="spring/spring-dao.xml"/>
    <import resource="spring/spring-service.xml"/>
    <import resource="spring/spring-mvc.xml"/>
</beans>

database.properties

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd">

    <import resource="spring/spring-dao.xml"/>
    <import resource="spring/spring-service.xml"/>
    <import resource="spring/spring-mvc.xml"/>
</beans>

mybatis-config.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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd">

    <import resource="spring/spring-dao.xml"/>
    <import resource="spring/spring-service.xml"/>
    <import resource="spring/spring-mvc.xml"/>
</beans>

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">

    <!--DispatcherServlet-->
    <servlet>
        <servlet-name>DispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <!--一定要注意:我们这里加载的是总的配置文件,之前被这里坑了!-->
            <param-value>classpath:applicationContext.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>

    <!--encodingFilter-->
    <filter>
        <filter-name>encodingFilter</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>encodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <!--Session过期时间-->
    <session-config>
        <session-timeout>35</session-timeout>
    </session-config>



</web-app>

 

ok,到这里已完成了一半工作了,配置地狱不是说着玩的--

 

然后开始写业务

LoginController.java
package com.chen.controller;

import com.chen.pojo.Administrator;
import com.chen.service.LoginService;
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 org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

@Controller
public class LoginController {

    @Resource(name="LoginServiceImpl")
    private LoginService loginService;

    //跳转到登陆页面
    @RequestMapping("/jumplogin")
    public String jumpLogin() throws Exception {
        return "sucessful";
    }

    //跳转到成功页面
    @RequestMapping("/jumpSuccess")
    public String jumpSuccess() throws Exception {
        System.out.println("xxx");
        return "sucessful";
    }



    //登陆提交
    @RequestMapping("/login")
    @ResponseBody
    public String login(HttpSession session, Administrator administrator) throws Exception {
        // 向session记录用户身份信息
        System.out.println("接收前端===" + administrator.getAccount());
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("account", administrator.getAccount());
        map.put("password", administrator.getPassword());
        Administrator administrator2 = loginService.queryAdministrator(map);
        System.out.println(administrator);
        session.setAttribute("user", administrator2);
        if (administrator2!=null) {
            return "成功1";

        }
        else {
            return "失败1";

        }
    }

    //退出登陆
    @RequestMapping("logout")
    public String logout(HttpSession session) throws Exception {
        // session 过期
        session.invalidate();
        return "login";
    }


}

 

LoginMapper.java
package com.chen.dao;

import com.chen.pojo.Administrator;

import java.util.Map;

public interface LoginMapper {



    Administrator queryAdministrator(Map<String,Object> map);//万能的Map
}

 

LoginMapper.xml

<?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.chen.dao.LoginMapper">

    <!--id为方法名,parameterType为传参类型,resultType为结果返回类型-->
    <select id="queryAdministrator" parameterType="map" resultType="Administrator">
        select *from website.administrator where account =#{account} and password =#{password}
    </select>



</mapper>

 

LoginInterceptor.java
package com.chen.interceptor;


import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class LoginInterceptor implements HandlerInterceptor {

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws ServletException, IOException {
        // 如果是登陆页面则放行
        System.out.println("uri: " + request.getRequestURI());
        HttpSession session = request.getSession();
        if(request.getRequestURI().contains("/login")) {
            System.out.println("11111111111111111111");
            return true;
        }

        // 如果用户已登陆也放行
       else if(session.getAttribute("user") != null){
            System.out.println("22222222222");
            return true;
        }

        // 用户没有登陆跳转到登陆页面
        else{
            System.out.println("333333333333");
            request.getRequestDispatcher("/WEB-INF/view/login.jsp").forward(request, response);
        }
        return false;
    }

    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
        System.out.println("------------处理后------------");

    }

    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
        System.out.println("------------清理------------");

    }
}

 

Administrator.java(这里使用了Lombok,没有用的小伙伴注意了,可以自己手动生成getter和setter,构造方法等)
package com.chen.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Administrator {
    private int id;
    private String name;
    private int account;
    private String password;
    private String logintime;
    private String outtime;
    private int frequency;
}
LoginService.java
package com.chen.service;

import com.chen.pojo.Administrator;

import java.util.Map;

public interface LoginService {


    Administrator queryAdministrator(Map<String,Object> map);//万能的Map
}

LoginServiceImpl.java
package com.chen.service;

import com.chen.dao.LoginMapper;
import com.chen.pojo.Administrator;
import org.springframework.stereotype.Repository;

import java.util.Map;

@Repository
public class LoginServiceImpl implements LoginService{
    //调用dao层的操作,设置一个set接口,方便Spring管理
   private LoginMapper loginMapper;

    public void setLoginMapper(LoginMapper loginMapper) {
        this.loginMapper = loginMapper;
    }



    public Administrator queryAdministrator(Map<String, Object> map) {
        return loginMapper.queryAdministrator( map);
    }
}

数据库

 

然后接下来写前端页面

login.jsp

<%--
  Created by IntelliJ IDEA.
  User: 86151
  Date: 2021/5/17
  Time: 16:42
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>博客后台</title>
    <link rel="stylesheet" type="text/css" href="..${pageContext.request.contextPath}/statics/css/style.css">
<%--
    <script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
--%>
   <script src="../statics/js/jquery-3.6.0.js"></script>

    <script>
        function login(){

            $.post("${pageContext.request.contextPath}/login",
                {
                    account:$("#account").val(),
                    password:$("#password").val()
                },
                function(data,status){
                    alert("数据: \\n" + data + "\\n状态: " + status);
                });
        }
    </script>
</head>
<body>
<div class="zxcf_nav_wper">
    <div class="zxcf_nav clearfix px1000">
        <div class="zxcf_nav_l fl"><img src="../statics/images/zxcf_logo.png" alt=""></div>
        <div class="zxcf_nav_r fr">
            <img src="../statics/images/lg_pic01.png" alt="">


        </div>
    </div>
</div>
<!-- end  -->
<div class="login_con_wper">
    <div class="login_con px1000 ">
        <div class="lg_section clearfix">
            <div class="lg_section_l fl">
                <img src="../statics/images/lg_bg02.png">
            </div>
            <!-- end l -->
            <div class="lg_section_r fl">
                <h2 class="lg_sec_tit clearfix">
                    <span class="fl">登录</span>
                </h2>
                <form >
                    <fieldset>
                        <p class="mt20">
                            <input type="text" placeholder="用户名/手机" class="lg_input01 lg_input" name="account" id="account">
                        </p>
                        <p class="mt20">
                            <input type="text" placeholder="密码" class="lg_input02 lg_input" name="password" id="password">
                        </p>
                        <p class="clearfix lg_check"><span class="fl"><input type="checkbox">记住用户名</span><a href="#" class="fr">忘记密码?找回</a></p>
                  <%--      <p><a href="${pageContext.request.contextPath}/login" class="lg_btn">立即登陆</a></p>--%>

                    </fieldset>
                </form>
                <button type="submit" onclick="login()"><a  class="lg_btn">立即登陆</a></button>
            </div>
        </div>
    </div>
</div>
<div class="zscf_bottom_wper">
    <div class="zscf_bottom px1000 clearfix">
        <p class="fl">© 2020 </p>
        <p class="fr">

        </p>
    </div>
</div>




</body>
</html>

 

sucessful.jsp

<%--
  Created by IntelliJ IDEA.
  User: 86151
  Date: 2021/5/17
  Time: 18:24
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<h1>登陆成功</h1>
</body>
</html>

 

index.jsp

<%--
  Created by IntelliJ IDEA.
  User: 86151
  Date: 2021/5/16
  Time: 20:22
  To change this template use File | Settings | File Templates.
--%>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<!DOCTYPE HTML>
<html>
<head>
  <title>首页</title>
  <style type="text/css">
    a {
      text-decoration: none;
      color: black;
      font-size: 18px;
    }
    h3 {
      width: 180px;
      height: 38px;
      margin: 100px auto;
      text-align: center;
      line-height: 38px;
      background: deepskyblue;
      border-radius: 4px;
    }
  </style>
</head>
<body>

<h3>
  <a href="${pageContext.request.contextPath}/jumplogin">点击进入登录页</a>
</h3>
</body>
</html>

上图(但是你们没有css的样式代码,所以可能会有点丑陋o)

以上是关于ssm登录的主要内容,如果未能解决你的问题,请参考以下文章

Java使用SSM框架实现登录页面的验证码功能

Java使用SSM框架实现登录页面记住密码功能

ssm框架实现登录退出学到了啥

Element ui+Vue+SSM-简易学生信息管理系统-前端登录页面

ssm框架实现登录退出学到了啥

pbootcms对接微信扫码登录代码核心片段和步骤(前后端)