SSM整合

SSM整合

整合说明:SSM整合可以使用多种方式,咱们会选择XML(第三方对象) + 注解(自己new的对象)的方式

1562512046083

整合的思路

  • (1):先搭建整合的环境

  • (2):先把Spring的配置搭建完成

  • (3):再使用Spring整合SpringMVC框架

  • (4):最后使用Spring整合MyBatis框架

数据源:

  1. create database itcastspringmvc;
  2. use itcastspringmvc;
  3. create table account(
  4. id int primary key auto_increment,
  5. name varchar(20),
  6. money double
  7. );

POM.XML整合环境:

  1. <properties>
  2. <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  3. <maven.compiler.source>1.8</maven.compiler.source>
  4. <maven.compiler.target>1.8</maven.compiler.target>
  5. <spring.version>5.0.2.RELEASE</spring.version>
  6. <slf4j.version>1.6.6</slf4j.version>
  7. <log4j.version>1.2.12</log4j.version>
  8. <mysql.version>5.1.6</mysql.version>
  9. <mybatis.version>3.4.5</mybatis.version>
  10. </properties>
  11. <dependencies>
  12. <!-- spring -->
  13. <dependency>
  14. <groupId>org.aspectj</groupId>
  15. <artifactId>aspectjweaver</artifactId>
  16. <version>1.6.8</version>
  17. </dependency>
  18. <dependency>
  19. <groupId>org.springframework</groupId>
  20. <artifactId>spring-aop</artifactId>
  21. <version>${spring.version}</version>
  22. </dependency>
  23. <dependency>
  24. <groupId>org.springframework</groupId>
  25. <artifactId>spring-context</artifactId>
  26. <version>${spring.version}</version>
  27. </dependency>
  28. <dependency>
  29. <groupId>org.springframework</groupId>
  30. <artifactId>spring-web</artifactId>
  31. <version>${spring.version}</version>
  32. </dependency>
  33. <dependency>
  34. <groupId>org.springframework</groupId>
  35. <artifactId>spring-webmvc</artifactId>
  36. <version>${spring.version}</version>
  37. </dependency>
  38. <dependency>
  39. <groupId>org.springframework</groupId>
  40. <artifactId>spring-test</artifactId>
  41. <version>${spring.version}</version>
  42. </dependency>
  43. <dependency>
  44. <groupId>org.springframework</groupId>
  45. <artifactId>spring-tx</artifactId>
  46. <version>${spring.version}</version>
  47. </dependency>
  48. <dependency>
  49. <groupId>org.springframework</groupId>
  50. <artifactId>spring-jdbc</artifactId>
  51. <version>${spring.version}</version>
  52. </dependency>
  53. <dependency>
  54. <groupId>junit</groupId>
  55. <artifactId>junit</artifactId>
  56. <version>4.12</version>
  57. <scope>test</scope>
  58. </dependency>
  59. <dependency>
  60. <groupId>mysql</groupId>
  61. <artifactId>mysql-connector-java</artifactId>
  62. <version>${mysql.version}</version>
  63. </dependency>
  64. <dependency>
  65. <groupId>javax.servlet</groupId>
  66. <artifactId>servlet-api</artifactId>
  67. <version>2.5</version>
  68. <scope>provided</scope>
  69. </dependency>
  70. <dependency>
  71. <groupId>javax.servlet.jsp</groupId>
  72. <artifactId>jsp-api</artifactId>
  73. <version>2.0</version>
  74. <scope>provided</scope>
  75. </dependency>
  76. <dependency>
  77. <groupId>jstl</groupId>
  78. <artifactId>jstl</artifactId>
  79. <version>1.2</version>
  80. </dependency>
  81. <!-- log start -->
  82. <dependency>
  83. <groupId>log4j</groupId>
  84. <artifactId>log4j</artifactId>
  85. <version>${log4j.version}</version>
  86. </dependency>
  87. <dependency>
  88. <groupId>org.slf4j</groupId>
  89. <artifactId>slf4j-api</artifactId>
  90. <version>${slf4j.version}</version>
  91. </dependency>
  92. <dependency>
  93. <groupId>org.slf4j</groupId>
  94. <artifactId>slf4j-log4j12</artifactId>
  95. <version>${slf4j.version}</version>
  96. </dependency>
  97. <!-- log end -->
  98. <dependency>
  99. <groupId>org.mybatis</groupId>
  100. <artifactId>mybatis</artifactId>
  101. <version>${mybatis.version}</version>
  102. </dependency>
  103. <dependency>
  104. <groupId>org.mybatis</groupId>
  105. <artifactId>mybatis-spring</artifactId>
  106. <version>1.3.0</version>
  107. </dependency>
  108. <dependency>
  109. <groupId>c3p0</groupId>
  110. <artifactId>c3p0</artifactId>
  111. <version>0.9.1.2</version>
  112. <type>jar</type>
  113. <scope>compile</scope>
  114. </dependency>
  115. </dependencies>
  116. <build>
  117. <finalName>ssm</finalName>
  118. <plugins>
  119. <plugin>
  120. <groupId>org.apache.maven.plugins</groupId>
  121. <artifactId>maven-compiler-plugin</artifactId>
  122. <version>3.2</version>
  123. <configuration>
  124. <source>1.8</source>
  125. <target>1.8</target>
  126. <encoding>UTF-8</encoding>
  127. <showWarnings>true</showWarnings>
  128. </configuration>
  129. </plugin>
  130. </plugins>
  131. </build>

创建包com.le.ssm.domain,创建类Account.java

  1. public class Account implements Serializable {
  2. private Integer id;
  3. private String name;
  4. private Double money;
  5. }

DAO

创建包com.le.ssm.dao,创建类AccountDao.java

  1. /**
  2. * AccountMapper接口,不用编写实现类,框架生成代理对象
  3. */
  4. public interface AccountDao {
  5. public List<Account> findAll();
  6. public void saveAccount(Account account);
  7. }

Service

创建包com.le.ssm.service,创建接口AccountService.java

  1. public interface AccountService {
  2. public List<Account> findAll();
  3. public void saveAccount(Account account);
  4. }

创建类AccountServiceImpl,实现接口

  1. /**
  2. * 账号的实现类
  3. */
  4. public class AccountServiceImpl implements AccountService {
  5. private AccountDao accountDao;
  6. public List<Account> findAll() {
  7. System.out.println("业务层:查询所有的帐户...");
  8. return accountDao.findAll();
  9. }
  10. public void saveAccount(Account account) {
  11. System.out.println("业务层:保存帐户...");
  12. accountDao.saveAccount(account);
  13. }
  14. }

创建包com.le.ssm.controller,创建类AccountController.java

  1. /**
  2. * 帐户
  3. */
  4. public class AccountController {
  5. private AccountService accountService;
  6. /**
  7. * 查询所有
  8. * @return
  9. */
  10. public String findAll() {
  11. System.out.println("表现层:查询所有账户...");
  12. List<Account> list = accountService.findAll();
  13. for (Account account : list) {
  14. System.out.println(account);
  15. }
  16. return "success";
  17. }
  18. /**
  19. * 保存
  20. * @return
  21. */
  22. public String saveAccount(Account account) {
  23. System.out.println("表现层:保存账户...");
  24. accountService.saveAccount(account);
  25. return "success";
  26. }
  27. }

1562512430210


Spring的环境

在项目中的resources文件夹下创建applicationContext.xml的配置文件,编写具体的配置信息。

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xmlns:context="http://www.springframework.org/schema/context"
  5. xmlns:aop="http://www.springframework.org/schema/aop"
  6. xmlns:tx="http://www.springframework.org/schema/tx"
  7. xsi:schemaLocation="http://www.springframework.org/schema/beans
  8. http://www.springframework.org/schema/beans/spring-beans.xsd
  9. http://www.springframework.org/schema/context
  10. http://www.springframework.org/schema/context/spring-context.xsd
  11. http://www.springframework.org/schema/aop
  12. http://www.springframework.org/schema/aop/spring-aop.xsd
  13. http://www.springframework.org/schema/tx
  14. http://www.springframework.org/schema/tx/spring-tx.xsd">
  15. <!-- 开启注解扫描 -->当只使用SpringMVC的注解管理全部的时候,这里就不需要开启注解了
  16. <!--<context:component-scan base-package="com.le.ssm">
  17. <!-- 忽略某些注解,把Controller给忽略了 -->
  18. <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
  19. </context:component-scan>-->
  20. </beans>

AccountService.java

  1. /**
  2. * 账号的实现类
  3. */
  4. @Service("accountService")
  5. public class AccountServiceImpl implements AccountService {
  6. }

在项目中编写测试方法,进行测试

创建测试类:com.le.test.TestService.java

  1. public class TestService {
  2. /**
  3. * 测试Service层
  4. */
  5. @Test
  6. public void testService(){
  7. ApplicationContext ac = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
  8. AccountService as = (AccountService) ac.getBean("accountService");
  9. as.findAll();
  10. }
  11. }

1562512663707


SpringMVC框架

web.xml

在web.xml中配置DispatcherServlet前端控制器

  1. <!-- 配置前端控制器:服务器启动必须加载,需要加载springmvc.xml配置文件 -->
  2. <servlet>
  3. <servlet-name>dispatcherServlet</servlet-name>
  4. <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  5. <!-- 配置初始化参数,创建完DispatcherServlet对象,加载springmvc.xml配置文件 -->
  6. <init-param>
  7. <param-name>contextConfigLocation</param-name>
  8. <param-value>classpath:springmvc.xml</param-value>
  9. </init-param>
  10. <!-- 服务器启动的时候,让DispatcherServlet对象创建 -->
  11. <load-on-startup>1</load-on-startup>
  12. </servlet>
  13. <servlet-mapping>
  14. <servlet-name>dispatcherServlet</servlet-name>
  15. <url-pattern>/</url-pattern>
  16. </servlet-mapping>
  17. <!-- 在web.xml中配置CharacterEncodingFilter过滤器解决post请求中文乱码
  18. 配置解决中文乱码的过滤器 -->
  19. <filter>
  20. <filter-name>characterEncodingFilter</filter-name>
  21. <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
  22. <init-param>
  23. <param-name>encoding</param-name>
  24. <param-value>UTF-8</param-value>
  25. </init-param>
  26. </filter>
  27. <filter-mapping>
  28. <filter-name>characterEncodingFilter</filter-name>
  29. <url-pattern>/*</url-pattern>
  30. </filter-mapping>

springmvc.xml

在resources下,创建springmvc.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context"
  4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  5. xsi:schemaLocation="
  6. http://www.springframework.org/schema/beans
  7. http://www.springframework.org/schema/beans/spring-beans.xsd
  8. http://www.springframework.org/schema/mvc
  9. http://www.springframework.org/schema/mvc/spring-mvc.xsd
  10. http://www.springframework.org/schema/context
  11. http://www.springframework.org/schema/context/spring-context.xsd">
  12. <!-- 扫描controller的注解,别的不扫描 -->
  13. <context:component-scan base-package="com.le.ssm">
  14. <!--<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
  15. 排除Service注解的扫描,让spring扫描,否则事务可能会失效
  16. <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Service"></context:exclude-filter> -->
  17. </context:component-scan><!-- 当使用下面这一句整合了APP的注解后,就不需要配上面两句了 -->
  18. <import resource="applicationContext.xml"></import>
  19. <!-- 配置视图解析器 -->
  20. <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  21. <!-- JSP文件所在的目录 -->
  22. <property name="prefix" value="/WEB-INF/pages/" />
  23. <!-- 文件的后缀名 -->
  24. <property name="suffix" value=".jsp" />
  25. </bean>
  26. <!-- 设置静态资源不过滤,可以使用:-->
  27. <mvc:default-servlet-handler></mvc:default-servlet-handler>
  28. <!--
  29. <mvc:resources location="/css/" mapping="/css/**" />
  30. <mvc:resources location="/images/" mapping="/images/**" />
  31. <mvc:resources location="/js/" mapping="/js/**" />
  32. -->
  33. <!-- 开启对SpringMVC注解的支持 -->
  34. <mvc:annotation-driven />
  35. </beans>

其中:

表示springmvc的注解包含@Controller的注解。

为什么要包含@Controller注解呢?

1)SpringMVC IOC容器 存在Controller的实例对象

2)Spring IOC容器 存在Controller的实例和Service层实例以及Dao层实例

重叠会引发一些问题:

​ 例如:事务失效、相关注解失效

​ 解决方案一:

​ SpringMVC只扫描 @Controller 注解、不扫描@Service注解

​ Spring不扫描 @Controller 注解

​ 解决方案二:(建议使用)

​ 只让SpringMVC扫描,不让Spring扫描

​ 在springMVC的配置中添加


AccountController.java

  1. /**
  2. * 帐户
  3. */
  4. @Controller
  5. @RequestMapping(path = "account")
  6. public class AccountController {
  7. @Autowired
  8. private AccountService accountService;
  9. /**
  10. * 查询所有
  11. * @return
  12. */
  13. @RequestMapping(path = "/findAll")
  14. public String findAll() {
  15. System.out.println("表现层:查询所有账户...");
  16. return "success";
  17. }
  18. }

index.jsp

  1. <body>
  2. <h3>账号操作</h3>
  3. <a href="account/findAll">查询所有账号</a>
  4. </body>

success.jsp(WEB-INF/pages/success.jsp)

  1. <body>
  2. <h1>访问成功</h1>
  3. </body>

1562513043709


Spring整合SpringMVC框架

目的:在controller中能成功的调用service对象中的方法。(由spring创建对象,注入到Action中使用)

在项目启动的时候,就去加载applicationContext.xml的配置文件,在web.xml中配置ContextLoaderListener监听器(默认该监听器只能加载WEB-INF目录下的applicationContext.xml的配置文件)。使用contextConfigLocation的属性让它加载类路径下的applicationContext.xml。

web.xml

  1. <!-- 配置Spring的监听器,默认加载WEB-INF下的applicationContext.xml -->
  2. <listener>
  3. <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  4. </listener>
  5. <!-- 该监听器默认只加载WEB-INF下的applicationContext.xml配置文件,通过contextConfigLocation改变位置 -->
  6. <context-param>
  7. <param-name>contextConfigLocation</param-name>
  8. <param-value>classpath:applicationContext.xml</param-value>
  9. </context-param>

AccountController.java

  1. @Controller
  2. @RequestMapping(path = "account")
  3. public class AccountController {
  4. @Autowired
  5. private AccountService accountService;
  6. /**
  7. * 查询所有
  8. * @return
  9. */
  10. @RequestMapping(path = "/findAll")
  11. public String findAll() {
  12. System.out.println("表现层:查询所有账户...");
  13. List<Account> list = accountService.findAll();
  14. System.out.println(list);
  15. return "success";
  16. }
  17. }

1562513174789


Mybatis框架

SqlMapConfig.xml

在web项目中编写SqlMapConfig.xml的配置文件,放置到resources下,编写核心配置文件

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE configuration
  3. PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  4. "http://mybatis.org/dtd/mybatis-3-config.dtd">
  5. <configuration>
  6. <environments default="mysql">
  7. <environment id="mysql">
  8. <transactionManager type="JDBC"/>
  9. <dataSource type="POOLED">
  10. <property name="driver" value="com.mysql.jdbc.Driver"/>
  11. <property name="url" value="jdbc:mysql:///itcastspringmvc"/>
  12. <property name="username" value="root"/>
  13. <property name="password" value="root"/>
  14. </dataSource>
  15. </environment>
  16. </environments>
  17. <!-- 使用的是注解 -->
  18. <mappers>
  19. <!-- <mapper class="com.le.ssm.dao.AccountDao"/> -->
  20. <!-- 该包下所有的dao接口都可以使用 -->
  21. <package name="com.le.ssm.dao"/>
  22. </mappers>
  23. </configuration>

Xml的回顾:我们采用的是注解

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE mapper
  3. PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  4. "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  5. <mapper namespace="com.le.ssm.dao.AccountDao">
  6. <!--查询所有-->
  7. <select id="findAll" resultType="com.le.ssm.domain.Account">
  8. select * from account
  9. </select>
  10. <!--保存-->
  11. <insert id="save" parameterType="com.le.ssm.domain.Account">
  12. insert into account(name,money) values (#{name},#{money})
  13. </insert>
  14. </mapper>

AccountDao.java

在AccountDao接口的方法上添加注解,编写SQL语句

  1. /**
  2. * AccountDao接口,不用编写实现类,框架生成代理对象
  3. */
  4. public interface AccountDao {
  5. @Select(value = "select * from account")
  6. public List<Account> findAll();
  7. @Insert(value = "insert into account (name,money) values (#{name},#{money})")
  8. public void saveAccount(Account account);
  9. }

在测试环境下,com.le.test中,编写测试方法

  1. public class TestMybatis {
  2. @Test
  3. public void testFindAll() throws Exception {
  4. // 加载配置文件
  5. InputStream in = Resources.getResourceAsStream("sqlMapConfig.xml");
  6. // 创建工厂
  7. SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(in);
  8. // 创建sqlSession对象
  9. SqlSession sqlSession = sessionFactory.openSession();
  10. // 获取代理对象
  11. AccountDao accountDao = sqlSession.getMapper(AccountDao.class);
  12. // 获取查询所有的方法
  13. List<Account> list = accountDao.findAll();
  14. for(Account account:list){
  15. System.out.println(account);
  16. }
  17. // 释放资源
  18. sqlSession.close();
  19. in.close();
  20. }
  21. @Test
  22. public void testSave() throws Exception {
  23. Account account = new Account();
  24. account.setName("小菲");
  25. account.setMoney(400d);
  26. // 加载配置文件
  27. InputStream in = Resources.getResourceAsStream("sqlMapConfig.xml");
  28. // 创建工厂
  29. SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(in);
  30. // 创建sqlSession对象
  31. SqlSession sqlSession = sessionFactory.openSession();
  32. // 获取代理对象
  33. AccountDao accountDao = sqlSession.getMapper(AccountDao.class);
  34. accountDao.saveAccount(account);
  35. // 提交事务
  36. sqlSession.commit();
  37. // 释放资源
  38. sqlSession.close();
  39. in.close();
  40. }
  41. }

Spring整合MyBatis框架

applicationContext.xml

目的:把SqlMapConfig.xml配置文件中的内容配置到applicationContext.xml配置文件中

  1. <!-- 配置C3P0的连接池对象 -->
  2. <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
  3. <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
  4. <property name="jdbcUrl" value="jdbc:mysql:///itcastspringmvc" />
  5. <property name="user" value="root" />
  6. <property name="password" value="root" />
  7. </bean>
  8. <!-- 配置SqlSession的工厂 -->
  9. <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
  10. <property name="dataSource" ref="dataSource" />
  11. </bean>
  12. <!-- 配置扫描dao的包 -->
  13. <bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
  14. <property name="basePackage" value="com.le.ssm.dao"/>
  15. </bean>

SqlMapConfig.xml配置文件可以删除。

AccountDao.java

在AccountDao接口中添加@Repository注解,也可以不填加。

  1. @Repository
  2. public interface AccountDao {
  3. @Select(value = "select * from account")
  4. public List<Account> findAll();
  5. @Insert(value = "insert into account (name,money) values (#{name},#{money})")
  6. public void saveAccount(Account account);
  7. }

TestSpringMybatis

  1. @Test
  2. public void testFindAllSpring() throws Exception {
  3. ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
  4. AccountDao accountDao = ac.getBean(AccountDao.class);
  5. List<Account> list = accountDao.findAll();
  6. for(Account account:list){
  7. System.out.println(account);
  8. }
  9. }

AccountServiceImpl.java

在service中注入dao对象

  1. /**
  2. * 账号的实现类
  3. */
  4. @Service("accountService")
  5. public class AccountServiceImpl implements AccountService {
  6. @Autowired
  7. private AccountDao accountDao;
  8. public List<Account> findAll() {
  9. System.out.println("业务层:查询所有的帐户...");
  10. return accountDao.findAll();
  11. }
  12. public void saveAccount(Account account) {
  13. accountDao.saveAccount(account);
  14. }
  15. }

AccountController.java

  1. @Controller
  2. @RequestMapping(path = "account")
  3. public class AccountController {
  4. @Autowired
  5. private AccountService accountService;
  6. /**
  7. * 查询所有
  8. * @return
  9. */
  10. @RequestMapping(path = "/findAll")
  11. public String findAll(Model model) {
  12. System.out.println("表现层:查询所有账户...");
  13. List<Account> list = accountService.findAll();
  14. System.out.println(list);
  15. model.addAttribute("list",list);
  16. return "success";
  17. }
  18. /**
  19. * 保存
  20. * @return
  21. */
  22. @RequestMapping(path = "/save")
  23. public String saveAccount(Account account) {
  24. accountService.saveAccount(account);
  25. return "success";
  26. }
  27. }

success.jsp

  1. <%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
  2. <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
  3. <html>
  4. <head>
  5. <title>Title</title>
  6. </head>
  7. <body>
  8. <h1>访问成功</h1>
  9. <c:forEach items="${list}" var="account">
  10. ${account.id}---
  11. ${account.name}---
  12. ${account.money}<br>
  13. </c:forEach>
  14. </body>
  15. </html>

配置Spring的声明式事务管理

applicationContext.xml

  1. <!-- 配置事务管理器 -->
  2. <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
  3. <property name="dataSource" ref="dataSource"/>
  4. </bean>
  5. <!-- 配置事务通知 -->
  6. <tx:advice id="txAdvice" transaction-manager="transactionManager">
  7. <tx:attributes>
  8. <tx:method name="*" read-only="true"/>
  9. <tx:method name="save*" isolation="DEFAULT" propagation="REQUIRED" read-only="false"/>
  10. <tx:method name="update*" isolation="DEFAULT" propagation="REQUIRED" read-only="false"/>
  11. <tx:method name="delete*" isolation="DEFAULT" propagation="REQUIRED" read-only="false"/>
  12. </tx:attributes>
  13. </tx:advice>
  14. <!-- 配置AOP增强事务 -->
  15. <aop:config>
  16. <aop:advisor advice-ref="txAdvice" pointcut="execution(* com.le.ssm.service..*.*(..))"/>
  17. </aop:config>

Spring的声明式事务处理(注解方式)

  1. <!--使用注解的方式,配置spring的声明式事务处理-->
  2. <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
  3. <property name="dataSource" ref="dataSource"></property>
  4. </bean>
  5. <!--开启注解的方式使用事务-->
  6. <tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven>

在Service的类上,配置@Transactional

  1. @Service
  2. @Transactional
  3. public class AccountServiceImpl implements AccountService {

index.jsp

  1. <hr>
  2. <form action="account/save" method="post">
  3. 姓名:<input type="text" name="name"/><br/>
  4. 金额:<input type="text" name="money"/><br/>
  5. <input type="submit" value="保存"/><br/>
  6. </form>

AccountController.java

  1. /**
  2. * 保存
  3. * @return
  4. */
  5. @RequestMapping(path = "/save")
  6. public void saveAccount(Account account, HttpServletRequest request, HttpServletResponse response) throws Exception {
  7. System.out.println("表现层:保存账户...");
  8. accountService.saveAccount(account);
  9. response.sendRedirect(request.getContextPath()+"/account/findAll");
  10. return;
  11. }

建议使用redirect关键字

  1. @RequestMapping(path = "/save")
  2. public String saveAccount(Account account) throws Exception {
  3. System.out.println("表现层:保存账户...");
  4. accountService.saveAccount(account);
  5. return "redirect:/account/findAll";
  6. }

让SpringMVC扫描,不让Spring扫描

配置springmvc.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context"
  4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  5. xsi:schemaLocation="
  6. http://www.springframework.org/schema/beans
  7. http://www.springframework.org/schema/beans/spring-beans.xsd
  8. http://www.springframework.org/schema/mvc
  9. http://www.springframework.org/schema/mvc/spring-mvc.xsd
  10. http://www.springframework.org/schema/context
  11. http://www.springframework.org/schema/context/spring-context.xsd">
  12. <!-- 开启注解扫描 -->
  13. <context:component-scan base-package="com.le.ssm">
  14. </context:component-scan>
  15. <!-- 配置视图解析器 -->
  16. <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  17. <!-- JSP文件所在的目录 -->
  18. <property name="prefix" value="/WEB-INF/pages/" />
  19. <!-- 文件的后缀名 -->
  20. <property name="suffix" value=".jsp" />
  21. </bean>
  22. <!-- 设置静态资源不过滤 -->
  23. <mvc:resources location="/css/" mapping="/css/**" />
  24. <mvc:resources location="/images/" mapping="/images/**" />
  25. <mvc:resources location="/js/" mapping="/js/**" />
  26. <!-- 开启对SpringMVC注解的支持 -->
  27. <mvc:annotation-driven />
  28. <!-- 加载springMVC的同时,同时加载spring -->
  29. <import resource="applicationContext.xml"></import>
  30. </beans>

applicationContext.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xmlns:context="http://www.springframework.org/schema/context"
  5. xmlns:aop="http://www.springframework.org/schema/aop"
  6. xmlns:tx="http://www.springframework.org/schema/tx"
  7. xsi:schemaLocation="http://www.springframework.org/schema/beans
  8. http://www.springframework.org/schema/beans/spring-beans.xsd
  9. http://www.springframework.org/schema/context
  10. http://www.springframework.org/schema/context/spring-context.xsd
  11. http://www.springframework.org/schema/aop
  12. http://www.springframework.org/schema/aop/spring-aop.xsd
  13. http://www.springframework.org/schema/tx
  14. http://www.springframework.org/schema/tx/spring-tx.xsd">
  15. <!-- 删除组件扫描的配置 -->
  16. <!-- 配置C3P0的连接池对象 -->
  17. <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
  18. <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
  19. <property name="jdbcUrl" value="jdbc:mysql:///itcastspringmvc" />
  20. <property name="user" value="root" />
  21. <property name="password" value="root" />
  22. </bean>
  23. <!-- 配置SqlSession的工厂 -->
  24. <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
  25. <property name="dataSource" ref="dataSource" />
  26. </bean>
  27. <!-- 配置扫描dao的包 -->
  28. <bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
  29. <property name="basePackage" value="com.le.ssm.dao"/>
  30. </bean>
  31. <!-- 配置事务管理器 -->
  32. <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
  33. <property name="dataSource" ref="dataSource"/>
  34. </bean>
  35. <!-- 配置事务通知 -->
  36. <tx:advice id="txAdvice" transaction-manager="transactionManager">
  37. <tx:attributes>
  38. <tx:method name="find*" read-only="true"/>
  39. <tx:method name="save*" isolation="DEFAULT" propagation="REQUIRED" read-only="false"/>
  40. <tx:method name="update*" isolation="DEFAULT" propagation="REQUIRED" read-only="false"/>
  41. <tx:method name="delete*" isolation="DEFAULT" propagation="REQUIRED" read-only="false"/>
  42. </tx:attributes>
  43. </tx:advice>
  44. <!-- 配置AOP增强事务 -->
  45. <aop:config>
  46. <aop:advisor advice-ref="txAdvice" pointcut="execution(* com.le.service..*.*(..))"/>
  47. </aop:config>
  48. </beans>

去掉web.xml中的监听器

  1. <!-- 配置Spring的监听器,默认加载WEB-INF下的applicationContext.xml
  2. <listener>
  3. <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  4. </listener>
  5. 该监听器默认只加载WEB-INF下的applicationContext.xml配置文件,通过contextConfigLocation改变位置
  6. <context-param>
  7. <param-name>contextConfigLocation</param-name>
  8. <param-value>classpath:applicationContext.xml</param-value>
  9. </context-param> -->

SSM用户注册登录案例

web.xml

  1. <!-- 配置前端控制器:服务器启动必须加载,需要加载springmvc.xml配置文件 -->
  2. <servlet>
  3. <servlet-name>dispatcherServlet</servlet-name>
  4. <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  5. <!-- 配置初始化参数,创建完DispatcherServlet对象,加载springmvc.xml配置文件 -->
  6. <init-param>
  7. <param-name>contextConfigLocation</param-name>
  8. <param-value>classpath:springmvc.xml</param-value>
  9. </init-param>
  10. <!-- 服务器启动的时候,让DispatcherServlet对象创建 -->
  11. <load-on-startup>1</load-on-startup>
  12. </servlet>
  13. <servlet-mapping>
  14. <servlet-name>dispatcherServlet</servlet-name>
  15. <url-pattern>/</url-pattern>
  16. </servlet-mapping>
  17. <!-- 配置解决中文乱码的过滤器 -->
  18. <filter>
  19. <filter-name>characterEncodingFilter</filter-name>
  20. <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
  21. <init-param>
  22. <param-name>encoding</param-name>
  23. <param-value>UTF-8</param-value>
  24. </init-param>
  25. </filter>
  26. <filter-mapping>
  27. <filter-name>characterEncodingFilter</filter-name>
  28. <url-pattern>/*</url-pattern>
  29. </filter-mapping>

applicationContext.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xmlns:context="http://www.springframework.org/schema/context"
  5. xmlns:aop="http://www.springframework.org/schema/aop"
  6. xmlns:tx="http://www.springframework.org/schema/tx"
  7. xsi:schemaLocation="http://www.springframework.org/schema/beans
  8. http://www.springframework.org/schema/beans/spring-beans.xsd
  9. http://www.springframework.org/schema/context
  10. http://www.springframework.org/schema/context/spring-context.xsd
  11. http://www.springframework.org/schema/aop
  12. http://www.springframework.org/schema/aop/spring-aop.xsd
  13. http://www.springframework.org/schema/tx
  14. http://www.springframework.org/schema/tx/spring-tx.xsd">
  15. <!-- Spring整合Mybatis -->
  16. <!-- 配置C3P0的连接池对象 -->
  17. <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
  18. <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
  19. <property name="jdbcUrl" value="jdbc:mysql:///itcastspringmvc" />
  20. <property name="user" value="root" />
  21. <property name="password" value="root" />
  22. </bean>
  23. <!-- 配置SqlSession的工厂 -->
  24. <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
  25. <property name="dataSource" ref="dataSource" />
  26. </bean>
  27. <!-- 配置扫描dao的包 -->
  28. <bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
  29. <property name="basePackage" value="com.le.ssm.dao"/>
  30. </bean>
  31. <!-- spring的声明式事务处理 -->
  32. <!-- 配置事务管理器 -->
  33. <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
  34. <property name="dataSource" ref="dataSource"/>
  35. </bean>
  36. <!-- 配置事务通知 -->
  37. <tx:advice id="txAdvice" transaction-manager="transactionManager">
  38. <tx:attributes>
  39. <tx:method name="find*" read-only="true"/>
  40. <tx:method name="save*" isolation="DEFAULT" propagation="REQUIRED" read-only="false"/>
  41. <tx:method name="update*" isolation="DEFAULT" propagation="REQUIRED" read-only="false"/>
  42. <tx:method name="delete*" isolation="DEFAULT" propagation="REQUIRED" read-only="false"/>
  43. </tx:attributes>
  44. </tx:advice>
  45. <!-- 配置AOP增强事务 -->
  46. <aop:config>
  47. <aop:advisor advice-ref="txAdvice" pointcut="execution(* com.le.ssm.service..*.*(..))"/>
  48. </aop:config>
  49. </beans>

springmvc.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context"
  4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  5. xsi:schemaLocation="
  6. http://www.springframework.org/schema/beans
  7. http://www.springframework.org/schema/beans/spring-beans.xsd
  8. http://www.springframework.org/schema/mvc
  9. http://www.springframework.org/schema/mvc/spring-mvc.xsd
  10. http://www.springframework.org/schema/context
  11. http://www.springframework.org/schema/context/spring-context.xsd">
  12. <!-- 开启注解扫描 -->
  13. <context:component-scan base-package="com.le.ssm"></context:component-scan>
  14. <!-- 配置视图解析器 -->
  15. <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  16. <!-- JSP文件所在的目录 -->
  17. <property name="prefix" value="/WEB-INF/pages/" />
  18. <!-- 文件的后缀名 -->
  19. <property name="suffix" value=".jsp" />
  20. </bean>
  21. <!-- 设置静态资源不过滤 -->
  22. <!--<mvc:resources location="/css/" mapping="/css/**" />-->
  23. <!--<mvc:resources location="/img/" mapping="/img/**" />-->
  24. <!--<mvc:resources location="/plugins/" mapping="/plugins/**" />-->
  25. <!--静态资源一律不拦截,包括html-->
  26. <mvc:default-servlet-handler />
  27. <!-- 开启对SpringMVC注解的支持 -->
  28. <mvc:annotation-driven />
  29. <import resource="applicationContext.xml"></import>
  30. </beans>

用户注册

表结构:

​ number varchar // 登录名

​ name varchar

​ password varchar // 密码

​ mobile varchar

​ qq varchar

​ email varchar

  1. create table `user` (
  2. `number` varchar(40) not null,
  3. `name` VARCHAR(20) DEFAULT NULL,
  4. `password` VARCHAR(60) DEFAULT NULL,
  5. `mobile` VARCHAR(11) DEFAULT NULL,
  6. `qq` VARCHAR(11) DEFAULT NULL,
  7. `email` VARCHAR(60) DEFAULT NULL,
  8. primary key (`number`)
  9. ) ENGINE=INNODB DEFAULT CHARSET = utf8;

pom.xml

  1. <properties>
  2. <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  3. <maven.compiler.source>1.8</maven.compiler.source>
  4. <maven.compiler.target>1.8</maven.compiler.target>
  5. <spring.version>5.0.2.RELEASE</spring.version>
  6. <slf4j.version>1.6.6</slf4j.version>
  7. <log4j.version>1.2.12</log4j.version>
  8. <mysql.version>5.1.6</mysql.version>
  9. <mybatis.version>3.4.5</mybatis.version>
  10. </properties>
  11. <dependencies>
  12. <!-- spring -->
  13. <dependency>
  14. <groupId>org.aspectj</groupId>
  15. <artifactId>aspectjweaver</artifactId>
  16. <version>1.6.8</version>
  17. </dependency>
  18. <dependency>
  19. <groupId>org.springframework</groupId>
  20. <artifactId>spring-aop</artifactId>
  21. <version>${spring.version}</version>
  22. </dependency>
  23. <dependency>
  24. <groupId>org.springframework</groupId>
  25. <artifactId>spring-context</artifactId>
  26. <version>${spring.version}</version>
  27. </dependency>
  28. <dependency>
  29. <groupId>org.springframework</groupId>
  30. <artifactId>spring-web</artifactId>
  31. <version>${spring.version}</version>
  32. </dependency>
  33. <dependency>
  34. <groupId>org.springframework</groupId>
  35. <artifactId>spring-webmvc</artifactId>
  36. <version>${spring.version}</version>
  37. </dependency>
  38. <dependency>
  39. <groupId>org.springframework</groupId>
  40. <artifactId>spring-test</artifactId>
  41. <version>${spring.version}</version>
  42. </dependency>
  43. <dependency>
  44. <groupId>org.springframework</groupId>
  45. <artifactId>spring-tx</artifactId>
  46. <version>${spring.version}</version>
  47. </dependency>
  48. <dependency>
  49. <groupId>org.springframework</groupId>
  50. <artifactId>spring-jdbc</artifactId>
  51. <version>${spring.version}</version>
  52. </dependency>
  53. <dependency>
  54. <groupId>junit</groupId>
  55. <artifactId>junit</artifactId>
  56. <version>4.12</version>
  57. <scope>compile</scope>
  58. </dependency>
  59. <dependency>
  60. <groupId>mysql</groupId>
  61. <artifactId>mysql-connector-java</artifactId>
  62. <version>${mysql.version}</version>
  63. </dependency>
  64. <dependency>
  65. <groupId>javax.servlet</groupId>
  66. <artifactId>servlet-api</artifactId>
  67. <version>2.5</version>
  68. <scope>provided</scope>
  69. </dependency>
  70. <dependency>
  71. <groupId>javax.servlet.jsp</groupId>
  72. <artifactId>jsp-api</artifactId>
  73. <version>2.0</version>
  74. <scope>provided</scope>
  75. </dependency>
  76. <dependency>
  77. <groupId>jstl</groupId>
  78. <artifactId>jstl</artifactId>
  79. <version>1.2</version>
  80. </dependency>
  81. <!-- log start -->
  82. <dependency>
  83. <groupId>log4j</groupId>
  84. <artifactId>log4j</artifactId>
  85. <version>${log4j.version}</version>
  86. </dependency>
  87. <dependency>
  88. <groupId>org.slf4j</groupId>
  89. <artifactId>slf4j-api</artifactId>
  90. <version>${slf4j.version}</version>
  91. </dependency>
  92. <dependency>
  93. <groupId>org.slf4j</groupId>
  94. <artifactId>slf4j-log4j12</artifactId>
  95. <version>${slf4j.version}</version>
  96. </dependency>
  97. <!-- log end -->
  98. <dependency>
  99. <groupId>org.mybatis</groupId>
  100. <artifactId>mybatis</artifactId>
  101. <version>${mybatis.version}</version>
  102. </dependency>
  103. <dependency>
  104. <groupId>org.mybatis</groupId>
  105. <artifactId>mybatis-spring</artifactId>
  106. <version>1.3.0</version>
  107. </dependency>
  108. <dependency>
  109. <groupId>c3p0</groupId>
  110. <artifactId>c3p0</artifactId>
  111. <version>0.9.1.2</version>
  112. <type>jar</type>
  113. <scope>compile</scope>
  114. </dependency>
  115. </dependencies>
  116. <build>
  117. <finalName>ssm</finalName>
  118. <plugins>
  119. <plugin>
  120. <groupId>org.apache.maven.plugins</groupId>
  121. <artifactId>maven-compiler-plugin</artifactId>
  122. <version>3.2</version>
  123. <configuration>
  124. <source>1.8</source>
  125. <target>1.8</target>
  126. <encoding>UTF-8</encoding>
  127. <showWarnings>true</showWarnings>
  128. </configuration>
  129. </plugin>
  130. <plugin>
  131. <groupId>org.apache.tomcat.maven</groupId>
  132. <artifactId>tomcat7-maven-plugin</artifactId>
  133. <version>2.2</version>
  134. <!--插件使用的相关配置-->
  135. <configuration>
  136. <!--端口号-->
  137. <port>18881</port>
  138. <!--写当前项目的名字(虚拟路径),如果写/,那么每次访问项目就不需要加项目名字了-->
  139. <path>/</path>
  140. <!--解决get请求乱码-->
  141. <uriEncoding>UTF-8</uriEncoding>
  142. </configuration>
  143. </plugin>
  144. </plugins>
  145. </build>

实体类User

  1. public class User implements Serializable {
  2. private String number;
  3. private String name;
  4. private String password;
  5. private String mobile;
  6. private String qq;
  7. private String email;
  8. }

拷贝页面到项目

创建UserController.java

页面数据发送到Controller,创建Controller

  1. @Controller
  2. @RequestMapping(value = "/user")
  3. public class UserController {
  4. @Autowired
  5. private UserService userService;
  6. /***
  7. * 增加用户
  8. * @param user
  9. * @return
  10. */
  11. @RequestMapping(value = "/save")
  12. public String save(User user){
  13. //增加
  14. int acount = userService.saveUser(user);
  15. if(acount>0){
  16. //新增成功,返回登录页面
  17. return "redirect:/login.html";
  18. }else{
  19. //新增失败,返回注册页面
  20. return "redirect:/register.html";
  21. }
  22. }
  23. }

创建接口UserService.java和实现类UserServiceImpl.java

  1. public interface UserService {
  2. /***
  3. * 增加用户
  4. * @param user
  5. * @return
  6. */
  7. int saveUser(User user);
  8. }
  1. @Service
  2. public class UserServiceImpl implements UserService {
  3. @Autowired
  4. private UserDao userDao;
  5. public int saveUser(User user) {
  6. return userDao.save(user);
  7. }
  8. }

如果是注解的方式配置声明式事务处理,需要添加在UserServiceImpl的类上添加:@Transactional

创建接口UserDao.java

  1. //@Repository
  2. public interface UserDao {
  3. /***
  4. * 增加操作
  5. * @param user
  6. * @return
  7. */
  8. @Insert("insert into user(number,password,mobile)values(#{number},#{password},#{mobile})")
  9. int save(User user);
  10. }

修改页面

  1. <form id="subform" action="/user/save" method="post" class="sui-form form-horizontal">
  2. <div class="control-group">
  3. <label class="control-label">用户名:</label>
  4. <div class="controls">
  5. <input type="text" name="number" placeholder="请输入你的用户名" class="input-xfat input-xlarge">
  6. </div>
  7. </div>
  8. <div class="control-group">
  9. <label for="inputPassword" class="control-label">登录密码:</label>
  10. <div class="controls">
  11. <input type="password" id="pwd" name="password" placeholder="设置登录密码" class="input-xfat input-xlarge">
  12. </div>
  13. </div>
  14. <div class="control-group">
  15. <label for="inputPassword" class="control-label">确认密码:</label>
  16. <div class="controls">
  17. <input type="password" id="rpwd" placeholder="再次确认密码" class="input-xfat input-xlarge">
  18. </div>
  19. </div>
  20. <div class="control-group">
  21. <label class="control-label">手机号:</label>
  22. <div class="controls">
  23. <input type="text" name="mobile" placeholder="请输入你的手机号" class="input-xfat input-xlarge">
  24. </div>
  25. </div>
  26. <div class="control-group">
  27. <label for="inputPassword" class="control-label">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</label>
  28. <div class="controls">
  29. <input name="m1" type="checkbox" value="2" checked=""><span>同意协议并注册《品优购用户协议》</span>
  30. </div>
  31. </div>
  32. <div class="control-group">
  33. <label class="control-label"></label>
  34. <div class="controls btn-reg">
  35. <button class="sui-btn btn-block btn-xlarge btn-danger" type="button" id="btn">完成注册</button>
  36. </div>
  37. </div>
  38. </form>
  1. <script src="plugins/jQuery/jquery-2.2.3.min.js"></script>
  2. <script>
  3. $(function () {
  4. /*
  5. * 点击注册按钮
  6. * 判断2次密码是否一致
  7. * 如果一致,提交到后台,否则提示错误
  8. * */
  9. $('#btn').click(function () {
  10. //获取2次密码
  11. var pwd = $('#pwd').val();
  12. var rpwd=$('#rpwd').val();
  13. if(pwd==rpwd){
  14. //提交到后台
  15. $('#subform').submit();
  16. }else{
  17. //提示
  18. alert("2次密码输入有误")
  19. }
  20. });
  21. });
  22. </script>

1562514308085


用户登录

login.html登录页面

  1. <form class="sui-form" action="/user/login" method="post">
  2. <div class="input-prepend"><span class="add-on loginname"></span>
  3. <input id="prependedInput" type="text" name="number" placeholder="邮箱/用户名/手机号" class="span2 input-xfat">
  4. </div>
  5. <div class="input-prepend"><span class="add-on loginpwd"></span>
  6. <input id="prependedInput" type="password" name="password" placeholder="请输入密码" class="span2 input-xfat">
  7. </div>
  8. <div class="setting">
  9. <label class="checkbox inline"><input name="m1" type="checkbox" value="2" checked="">自动登录</label>
  10. <span class="forget">忘记密码?</span>
  11. </div>
  12. <div class="logined">
  13. <button class="sui-btn btn-block btn-xlarge btn-danger" type="submit">登&nbsp;&nbsp;录</button>
  14. </div>
  15. </form>

UserController.java

  1. /***
  2. * 用户登录
  3. * @return
  4. */
  5. @RequestMapping(value = "/login")
  6. public String login(User user, HttpSession session){
  7. //数据库查询登录
  8. User loginUser = userService.findByNumberAndPassword(user);
  9. //判断loginUser是否为空
  10. if(loginUser!=null){
  11. //登录成功跳转到欢迎页
  12. session.setAttribute("loginUser",user);
  13. return "redirect:/index/welcome";
  14. }else{
  15. //为空,登录失败,继续登录
  16. return "redirect:/login.html";
  17. }
  18. }

UserServiceImpl.java

  1. public User findByNumberAndPassword(User user) {
  2. return userDao.findByNumberAndPassword(user);
  3. }

UserDao.java

  1. /****
  2. * 登录
  3. * @param user
  4. * @return
  5. */
  6. @Select("select * from user where number=#{number} and password=#{password}")
  7. User findByNumberAndPassword(User user);
  8. //@Select(value = "select * from user where number = #{number} and password=#{password}")
  9. //User findByNumberAndPassword(@Param("number") String number, @Param("password") String password);

登录成功--->重定向到欢迎页WelcomeController.java

  1. @Controller
  2. @RequestMapping(value = "/index")
  3. public class WelcomeController {
  4. /***
  5. * 欢迎页
  6. * @return
  7. */
  8. @RequestMapping(value = "/welcome")
  9. public String welcome(){
  10. return "index";
  11. }
  12. }

将admin下的index.html拷贝到WEB-INF\pages下

同时创建index.jsp,将index.html的内容放置到index.jsp

img

img

在index.jsp中获取登录信息

  1. <!-- Sidebar toggle button-->
  2. <a href="#" class="sidebar-toggle" data-toggle="offcanvas" role="button">
  3. <span class="sr-only">Toggle navigation</span>
  4. </a>
  5. 欢迎你:${sessionScope.loginUser.number}

整合拦截器

【需求】:用户如果已经登录

​ 用户如果没有登录,则不能访问欢迎页

LoginInterceptor.java

声明拦截器

创建包com.le.ssm.interceptor

创建类LoginInterceptor.java

  1. public class LoginInterceptor implements HandlerInterceptor {
  2. @Override
  3. public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
  4. /****
  5. * 用户是否在线
  6. * 如果不在线,不允许访问欢迎页
  7. */
  8. Object loginUser = request.getSession().getAttribute("loginUser");
  9. if(loginUser==null){
  10. response.sendRedirect(request.getContextPath()+"/login.html");
  11. return false;
  12. }
  13. return true;
  14. }
  15. }

springmvc.xml

  1. <!--配置拦截器-->
  2. <mvc:interceptors>
  3. <mvc:interceptor>
  4. <!--拦截 的url,所有拦截-->
  5. <mvc:mapping path="/**"/>
  6. <!--排除-->
  7. <mvc:exclude-mapping path="/*.html"></mvc:exclude-mapping>
  8. <mvc:exclude-mapping path="/js/**"></mvc:exclude-mapping>
  9. <mvc:exclude-mapping path="/css/**"></mvc:exclude-mapping>
  10. <mvc:exclude-mapping path="/img/**"></mvc:exclude-mapping>
  11. <mvc:exclude-mapping path="/plugins/**"></mvc:exclude-mapping>
  12. <mvc:exclude-mapping path="/user/save"></mvc:exclude-mapping>
  13. <mvc:exclude-mapping path="/user/login"></mvc:exclude-mapping>
  14. <bean class="com.le.ssm.interceptor.SessionInterceptor"></bean>
  15. </mvc:interceptor>
  16. </mvc:interceptors>

【测试】重新启动,在没有Session的情况下,访问/index/welcome,此时重定向到登录页面。

posted @ 2019-07-07 23:56  不穿格子衫的徍爺  阅读(262)  评论(0编辑  收藏  举报