SSM框架整合&&实现用户登录

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_34802416/article/details/81535839

目录

SSM

1 开发环境准备

IDE使用的是eclipse(虽然IDEA更好用,但eclipse可能在工作中更通用,还是得用熟才行),搭建SSM项目之前,需要配置好如下环境:

  • JDK
  • Tomcat
  • Maven
    • 帮助我们管理项目所需的jar包(ssm框架所需的jar包有20~30个)

以及eclipse的插件:

  • Spring Tools

2 开始整合

2.1 创建项目

2.1.1 创建Maven Project

当你配置好Maven环境后,就可以在eclipse中直接创建Maven项目。

File->New->Other->【Maven Project】->不勾选Create a simple project

(图2.1.1 创建Maven Project)

点击Next->选择webapp

输入Group Id(组织名)与Artifact Id(项目名),然后它就会帮我们自动生成好一个包名。

点击Finish,这样就创建好了一个Maven工程,以下是目录结构。

可以看到项目现在是报错了,那是因为还没有引入所需要的jar包,接下来是要导入项目所需要的包。

2.1.2 导入jar包

Tomcat库支持

创建好项目后,先加入Tomact库,项目->右键菜单->BuildPath->Configure Build Path->Libraries->Add Library->选中Server Runtime->Next->选中你的Tomcat版本->Finish。

pom.xml文件

打开项目下的pom.xml文件(所有jar包依赖都写在这个文件中,进行统一管理),并将以下内容复制粘贴到\标签之后即可,使用Ctrl+S保存xml文件。

导入的依赖如下所示:

<properties>
    <!-- spring版本号 -->
    <spring.version>4.3.5.RELEASE</spring.version>
    <!-- mybatis版本号 -->
    <mybatis.version>3.2.7</mybatis.version>
    <!-- log4j日志文件管理包版本 -->
    <slf4j.version>1.7.7</slf4j.version>
    <log4j.version>1.2.17</log4j.version>
    <!-- junit测试包版本 -->
    <junit.version>4.9</junit.version>
    </properties>

    <dependencies>
        <!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-validator -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
            <version>5.4.0.Final</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/javax.validation/validation-api -->
        <dependency>
            <groupId>javax.validation</groupId>
            <artifactId>validation-api</artifactId>
            <version>2.0.1.Final</version>
        </dependency>

        <!-- junit测试包 -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>${junit.version}</version>
            <!-- scope表示"域" 表示开发的时候引入,发布的时候不会加载此包 -->
            <scope>test</scope>
        </dependency>

        <!-- spring核心包 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <!-- springweb支持包 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <!-- oxm支持包 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-oxm</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <!-- 事务支持包 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <!-- jdbc支持包 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <!-- 与springmvc整合支持包 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <!-- aop支持包 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/aopalliance/aopalliance -->
        <dependency>
            <groupId>aopalliance</groupId>
            <artifactId>aopalliance</artifactId>
            <version>1.0</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.ow2.asm/asm -->
        <dependency>
            <groupId>org.ow2.asm</groupId>
            <artifactId>asm</artifactId>
            <version>4.2</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
        <!-- 面向切面支持包 -->
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.8.13</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/cglib/cglib -->
        <!-- spring中动态代理支持包 -->
        <dependency>
            <groupId>cglib</groupId>
            <artifactId>cglib</artifactId>
            <version>2.2.2</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
        <!-- apache支持通用工具包 -->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.7</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/dom4j/dom4j -->
        <!-- 文档解析工具 -->
        <dependency>
            <groupId>dom4j</groupId>
            <artifactId>dom4j</artifactId>
            <version>1.6.1</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
        <!-- json数据处理 -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.9.6</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-annotations -->
        <!-- json注解支持 -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>2.9.6</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/javax.servlet.jsp.jstl/jstl -->
        <!-- 核心标签库支持 -->
        <dependency>
            <groupId>javax.servlet.jsp.jstl</groupId>
            <artifactId>jstl-api</artifactId>
            <version>1.2</version>
            <exclusions>
                <exclusion>
                    <groupId>javax.servlet</groupId>
                    <artifactId>servlet-api</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>javax.servlet.jsp</groupId>
                    <artifactId>jsp-api</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.glassfish.web</groupId>
            <artifactId>jstl-impl</artifactId>
            <version>1.2</version>
            <exclusions>
                <exclusion>
                    <groupId>javax.servlet</groupId>
                    <artifactId>servlet-api</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>javax.servlet.jsp</groupId>
                    <artifactId>jsp-api</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>javax.servlet.jsp.jstl</groupId>
                    <artifactId>jstl-api</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.apache.taglibs/taglibs-standard-impl -->
        <!-- 与jstl包合用 -->
        <dependency>
            <groupId>org.apache.taglibs</groupId>
            <artifactId>taglibs-standard-impl</artifactId>
            <version>1.2.5</version>
        </dependency>


        <!-- 上下文支持包 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <!-- 测试支持包 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <!-- mybatis核心包 -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>${mybatis.version}</version>
        </dependency>

        <!-- mybatis整合spring包 -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.2.2</version>
        </dependency>


        <!-- 导入Mysql数据库链接jar包 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.36</version>
        </dependency>

        <!-- 导入c3p0工具包 <dependency> <groupId>c3p0</groupId> <artifactId>c3p0</artifactId> 
      <version>0.9.1.2</version> </dependency> -->


        <!-- 导入dbcp的jar包,用来在applicationContext.xml中配置数据库 -->
        <dependency>
            <groupId>commons-dbcp</groupId>
            <artifactId>commons-dbcp</artifactId>
            <version>1.2.2</version>
        </dependency>

        <!-- JSTL标签类 -->
        <dependency>
            <groupId>jstl</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>

        <!-- 日志文件管理包 -->
        <!-- log start -->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>${log4j.version}</version>
        </dependency>


        <!-- 格式化对象,方便输出日志 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.1.41</version>
        </dependency>


        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>${slf4j.version}</version>
        </dependency>

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>${slf4j.version}</version>
        </dependency>

        <!-- 映入JSON -->
        <dependency>
            <groupId>org.codehaus.jackson</groupId>
            <artifactId>jackson-mapper-asl</artifactId>
            <version>1.9.13</version>
        </dependency>

        <!-- 上传组件包 -->
        <!-- 文件上传下载 -->
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3.1</version>
        </dependency>
        <!-- io流支持 -->
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.4</version>
        </dependency>
        <!-- 通用代码支持 -->
        <dependency>
            <groupId>commons-codec</groupId>
            <artifactId>commons-codec</artifactId>
            <version>1.9</version>
        </dependency>
    </dependencies>

      <build>
        <!-- 指定JRE版本为1.8 -->
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
        </plugins>
      </build>

(注意\标签下的JRE版本与你的Java环境是否一致,不一致需要进行修改)

写入了pom.xml文件后,我们还需要更新Maven项目,选中项目->右键菜单->Maven->Update Project->选择ok,此时eclips开始自动下载pom.xml中所指定的jar包。

2.2 配置文件

如果你是第一次整合ssm,我强烈建议你就按照以下的文件命名方式。

ssm框架的需要配置的文件如下:

  • web.xml
    • 配置spring
    • 配置spring mvc
    • 设置字符过滤器
  • db.properties
    • 设置数据库连接属性
  • applicationContext
    • 配置DataSource
    • 配置sqlSessionFactory工厂
    • 配置mapper接口
    • 配置事务
    • 设置注解扫描器
  • springmvc-servlet
    • 设置注解扫描器
    • mvc注解驱动
    • 视图解析器
    • 文件上传解析器
  • SqlMapConfig:
    • 配置typeAliases

创建好如下的文件目录结构(包名、文件名可以自己进行修改),文件目录如下:

创建好文件目录之后,我们就可以开始写配置文件了,注意按照自己的目录结构修改每个xml文件中的包名。

2.2.1 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"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    version="3.0">

  <display-name>Archetype Created Web Application</display-name>

  <!--1 配置spring -->
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:applicationContext.xml</param-value>
  </context-param>


  <!--2 配置spring mvc -->
  <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-servlet.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>
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>

  <!--3 Spring MVC字符过滤器配置 -->
  <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>
    <init-param>
      <param-name>forceEncoding</param-name>
      <param-value>true</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>characterEncodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
</web-app>

2.2.2 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:aop="http://www.springframework.org/schema/aop"
    xmlns:c="http://www.springframework.org/schema/c"
    xmlns:cache="http://www.springframework.org/schema/cache"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:jdbc="http://www.springframework.org/schema/jdbc"
    xmlns:jee="http://www.springframework.org/schema/jee"
    xmlns:lang="http://www.springframework.org/schema/lang"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:mybatis-spring="http://mybatis.org/schema/mybatis-spring"
    xmlns:oxm="http://www.springframework.org/schema/oxm"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:task="http://www.springframework.org/schema/task"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:util="http://www.springframework.org/schema/util"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
        http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-4.3.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
        http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.3.xsd
        http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.3.xsd
        http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang-4.3.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
        http://mybatis.org/schema/mybatis-spring http://mybatis.org/schema/mybatis-spring-1.2.xsd
        http://www.springframework.org/schema/oxm http://www.springframework.org/schema/oxm/spring-oxm-4.3.xsd
        http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.3.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.3.xsd">

    <!--1 读取数据库配置属性文件  -->
    <context:property-placeholder location="classpath:db.properties"/>

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

    <!--3 配置工厂 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"></property>
        <!-- 自动扫描mapping.xml文件 -->  
        <property name="mapperLocations" value="classpath:/com/rhine/studySSM/mapper/*.xml"></property>
        <property name="configLocation" value="classpath:SqlMapConfig.xml"></property>
    </bean>

    <!-- DAO(mapper)接口所在包名,Spring会自动查找其下的类 -->  
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">  
        <property name="basePackage" value="com.rhine.studySSM.mapper" />  
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>  
    </bean>  

    <!--4 配置事务 -->
    <!-- 事务管理器 -->
    <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>
    <tx:advice id="txAdvice" transaction-manager="txManager">
        <tx:attributes>
            <tx:method name="save" propagation="REQUIRED"/>
            <tx:method name="get" read-only="true"/>
            <tx:method name="*" propagation="REQUIRED"/>
        </tx:attributes>
    </tx:advice>
    <aop:config>
        <aop:pointcut expression="execution(* com.rhine.studySSM.service.impl.*.*(..))" id="pointcut"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="pointcut"/>
    </aop:config>

    <!--5 注解扫描器 -->
    <context:component-scan base-package="com.rhine.studySSM.service"/>
</beans>

2.2.3 db.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql:///testconn
jdbc.username=root
jdbc.password=abc123456

最好加上jdbc前缀,以防止命名冲突,使得spring创建DataSource的bean失败。

2.2.4 springmvc-servlet.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:mvc="http://www.springframework.org/schema/mvc"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
            http://www.springframework.org/schema/beans/spring-beans-4.3.xsd 
            http://www.springframework.org/schema/mvc 
            http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd 
            http://www.springframework.org/schema/context 
            http://www.springframework.org/schema/context/spring-context-4.3.xsd">

    <!-- 扫描controller注解、,多个包中间使用半角逗号分隔 -->
    <context:component-scan base-package="com.rhine.studySSM.controller" />
    <!-- 支持mvc注解驱动 -->
    <mvc:annotation-driven enable-matrix-variables="true" />
    <!-- Spring MVC不处理静态资源 -->
    <mvc:default-servlet-handler />
    <!-- 视图解析器 -->
    <bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver"
        id="internalResourceViewResolver">
        <!-- 前缀 -->
        <property name="prefix" value="/" />
        <!-- 后缀 -->
        <property name="suffix" value=".jsp" />
    </bean>

    <!--文件上传解析器 -->
    <!--Spring MVC默认不能识别multipart格式的文件内容 -->
    <bean id="multipartResolver"
        class="org.springframework.web.multipart.support.StandardServletMultipartResolver">
    </bean>
</beans>

2.2.5 SqlMapConfig.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
 "http://mybatis.org/dtd/mybatis-3-config.dtd">  
<configuration>
    <typeAliases>
        <package name="com.rhine.studySSM.domain"/>
    </typeAliases>
</configuration>  

3 Demo(用户登录)

以上,我们就完成了SSM(spring+spring mvc+mybatis)的整合,接下来,就以一个用户登录的例子,完成一次前端与后台的请求和响应。

为了之后查阅每一层中的代码格式方便,所以特意在文章中贴上了几乎所有的代码。如果你不想在文章中查看具体的代码细节,可直接在文末查看代码的下载地址。

3.1 创建user表

字段名 类型 主键 Not NULL
id int
name varchar
password varchar

sql脚本如下:

-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) NOT NULL,
  `password` varchar(255) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES ('1', 'rhine', 'abc123');
INSERT INTO `user` VALUES ('2', 'cyy', 'abc123');

3.2 前端页面

所有的前端页面都防止在webapp文件夹中。

  • login.jsp(登录页面)
    • 登录成功则跳转到homepage/index.jsp页面中,并显示用户名
    • 登录失败则跳转到fail.jsp页面
  • fail.jsp(登录失败页面)
  • index.jsp(首页)

文件目录结构如下所示:

3.2.1 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>
    <h1>用户登录</h1>
    <hr/>
    <form action="${pageContext.request.contextPath }/user/login" method="POST">
        用户名:<input type="text" name="name"><br>
        密&emsp;码:<input type="password" name="password"><br>
        <input type="submit" value="登录">
    </form>
</body>
</html>

注意\标签中的name属性必须与User类中的字段名一一对应。

3.2.2 fail.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>Index</title>
</head>
<body>
    <h1>登录失败!请重新登录!</h1>
</body>
</html>

3.2.3 index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!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>Index</title>
</head>
<body>
    <h1>你好<c:out value="${sessionScope.user.name }"/>, 早上好!</h1>
</body>
</html>

通过session获取到用户名,并使用jstl标签打印在页面上。

3.3 后台代码

你如果学习过ssm框架,那你对后台代码的结构应该完全不陌生。

3.3.1 domain层

User.java
package com.rhine.studySSM.domain;

import java.io.Serializable;

@SuppressWarnings("serial")
public class User implements Serializable{

    private Integer id;
    private String name;
    private String password;

    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
}

与数据库中的字段名一一对应,如果不同,则需要设置别名。

3.3.2 Dao(mapper)层

UserMaperr.java
package com.rhine.studySSM.mapper;

import org.springframework.stereotype.Repository;
import com.rhine.studySSM.domain.User;

@Repository
public interface UserMapper {

    User userlogin(User user);
}
UserMapper.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.rhine.studySSM.mapper.UserMapper">
  <resultMap id="BaseResultMap" type="com.rhine.studySSM.domain.User">
    <id column="id" jdbcType="INTEGER" property="id"/>
    <result column="name" jdbcType="VARCHAR" property="name"/>
    <result column="passsword" jdbcType="VARCHAR" property="password"/>     
  </resultMap>
  <select id="userlogin" parameterType="com.rhine.studySSM.domain.User" resultType="com.rhine.studySSM.domain.User">
    SELECT * FROM user WHERE name=#{name} AND password=#{password}
  </select>
</mapper>

3.3.3 service层

IUserService.java
package com.rhine.studySSM.service;

import com.rhine.studySSM.domain.User;

public interface IUserService {
    User userlogin(User user);
}
UserService.java
package com.rhine.studySSM.service.impl;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.rhine.studySSM.domain.User;
import com.rhine.studySSM.mapper.UserMapper;
import com.rhine.studySSM.service.IUserService;


@Service
public class UserService implements IUserService{

    @Resource
    UserMapper userMapper;

    @Override
    public User userlogin(User user) {
        return userMapper.userlogin(user);
    }
}

3.3.4 controller层

UserController.java
package com.rhine.studySSM.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.rhine.studySSM.domain.User;
import com.rhine.studySSM.service.IUserService;


@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    IUserService userService;

    @RequestMapping("/login")
    public String login(User user, Model model, HttpServletRequest req) {
        HttpSession session = req.getSession();
        if(user != null) {
            User loginUser = userService.userlogin(user);
            if(loginUser != null) {
                System.out.println("登录成功");
                session.setAttribute("user", loginUser);
                return "homepage/index";
            }else {
                System.out.println("登录失败");
                return "fail";
            } 
        }
        return "fail";
    }
}

3.4 运行程序

在tomcat中运行程序,并根据数据库user表中的已有数据,进行登录,效果如下:

(早上开始写的,写完都中午了,还早上好…哈哈。写博客还是挺花时间的,不过后面回顾起来更省时间!)

4 项目下载地址

SSM就已经整合完成了,现在有了这个模板,就不需要每次都去重复的配置项目了,省去了很多事情。

gitee地址:https://gitee.com/Rhine/StudySSM

没有更多推荐了,返回首页