专注Java教育14年 全国咨询/投诉热线:444-1124-454
赢咖4LOGO图
始于2009,口口相传的Java黄埔军校
首页 hot资讯 Spring集成SSM框架注解

Spring集成SSM框架注解

更新时间:2021-10-27 08:52:22 来源:赢咖4 浏览724次

和 XML 版本类似,但是创建对象的方式是 Spring 自动扫描,然后命名空间是 Application.XML 中的多行 CONTEXT 代码,然后通过注解创建和注入每个对象:

直接代码:

1.userDao

package cn.mr.li.dao;
import java.util.List;
import cn.mr.li.entity.User;
public interface UserDao {
    List<User> getUser();
}

2.userDaoImpl

package cn.mr.li.dao.impl;
import java.util.List;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.support.SqlSessionDaoSupport;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import cn.mr.li.dao.UserDao;
import cn.mr.li.entity.User;
/**
   * Because the direct call is the type of service interface, it does not directly inject the IMPL implementation class, so don't write @Repository ("Uservice") @ service ("UserService")
 * @author Administrator
 *
 */
@Repository()
public class UserDaoImpl extends SqlSessionDaoSupport implements UserDao {    
    @Autowired
    @Override
    public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) {
        super.setSqlSessionFactory(sqlSessionFactory);
    }    
    @Override
    public List<User> getUser() {
        return this.getSqlSession().selectList("cn.mr.li.entity.user.mapper.getAll");
    }
}

3.用户服务

package cn.mr.li.service;
import java.util.List;
import cn.mr.li.entity.User;
public interface UserService {
    List<User> getAll();
}

4.userServiceImpl

package cn.mr.li.service.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import cn.mr.li.dao.UserDao;
import cn.mr.li.entity.User;
import cn.mr.li.service.UserService;
@Service()
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDao userDao;    
    @Override
    public List<User> getAll() {
        return userDao.getUser();
    }
    public UserDao getUserDao() {
        return userDao;
    }
    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }
}

5.用户对象

package cn.mr.li.entity;
public class User {
    private int id;   
    private String name;    
    private int age;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public User(int id, String name, int age) {
        super();
        this.id = id;
        this.name = name;
        this.age = age;
    }
    
    public User() {
    }
}

6.user.mapper.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="cn.mr.li.entity.user.mapper">
    <select id="getAll" resultType="User">
        select * from user
    </select>
</mapper>

7.userAction

package cn.mr.li.action;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import cn.mr.li.entity.User;
import cn.mr.li.service.UserService;
/**
   * @ Scope annotation means that it is not a single case for configuring the ACTION that is accessed, otherwise this time I am accessing next time, the last data will still exist.
 * @author Administrator
 *
 */
@Controller()
@Scope("prototype")
public class UserAction {
    private List<User> list;   
    @Autowired
    private UserService userService;    
    /**
           * Here you must return to Success, because the time is judged back, if not success, the data is not solid, the page will be 404
     * @return
     */
    public String list(){
        list = userService.getAll();
        return "success";
    }    
    public List<User> getList() {
        return list;
    }    
}

8.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:tx="http://www.springframework.org/schema/tx"
    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/aop http://www.springframework.org/schema/aop/spring-aop.xsd 
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">        
    <!--  Configuring data sources -->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/test"/>
        <property name="username" value="root"/>
        <property name="password" value="123456"/>
    </bean>
    <!--  Declarative transaction configuration -->
    <!--  Configure transaction manager -->
    <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>
    <!--  Configuration transaction notification -->
    <tx:advice id="txAdvice" transaction-manager="txManager">
        <tx:attributes>
            <!--  What ways are configured, what kind of transaction is used to configure transaction propagation features -->
            <tx:method name="add" propagation="REQUIRED"/>
            <tx:method name="insert" propagation="REQUIRED"/>
            <tx:method name="update" propagation="REQUIRED"/>
            <tx:method name="delete" propagation="REQUIRED"/>
            <tx:method name="remove*" propagation="REQUIRED"/>
            <tx:method name="get" read-only="true"/>
            <tx:method name="*" propagation="REQUIRED"/>
        </tx:attributes>
    </tx:advice>
    <aop:config>
        <aop:pointcut expression="execution(* cn.mr.li.service.impl.*.*(..))" id="pointcut"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="pointcut"/>
    </aop:config>
    <!--  Declarative transaction configuration end -->
    <!--  Configure SQLSessionFactory -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="configLocation" value="classpath:mybatis.cfg.xml"></property>
    </bean>    
    <!--  Spring starts automatically scan all kinds of files under this package -->
    <context:component-scan base-package="cn.mr.li"/>
</beans>

9.mybatis.cfg.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="cn.mr.li.entity"/>
    </typeAliases>
    <mappers>
        <mapper resource="cn/mr/li/entity/user.mapper.xml"/>
    </mappers> 
</configuration>s

10.struts.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
    "http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
    <package name="user" namespace="/" extends="struts-default">
        <!--  The name = "list" configured here means that it can be accessed by List when access is accessed, what is in web.xml
                 In the Struts configuration, this project is configured * .act, so if you want to access the list.jsp page under this item.
                 Just directly in the parent path (default is the project name), follow /List.Action -->
        <action name="list" class="userAction" method="list">
            <result>/list.jsp</result>
        </action>
    </package>
</struts>

11.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" 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">
     <!--  Configure Spring: Cooperate with global variables, will read the Spring to read ContextConfigLocation, not need to read in the program. -->
     <context-param>
         <param-name>contextConfigLocation</param-name>
         <param-value>classpath:applicationContext.xml</param-value>
     </context-param>
     <!--  Configure the listener: This listener initializes the global context in its constructor when starting initialization.
           Therefore, you need to load the Spring configuration, because there is an object instance in Spring. -->
     <listener>
         <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
     </listener>     
     <!--  Configuring struts2: You need to configure filter, and its URL, access style -->
     <filter>
         <filter-name>struts2</filter-name>
         <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
     </filter>
     <filter-mapping>
         <filter-name>struts2</filter-name>
         <!--  The suffix name when visiting is set here. -->
        <url-pattern>*.action</url-pattern>
     </filter-mapping>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
</web-app>

12.list.jsp

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">   
    <title>My JSP 'index.jsp' starting page</title>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->
  </head>  
  <body>
    <table width="80%" align="center">
        <tr>
            <td>Numbering</td>
            <td>Name</td>
            <td>password</td>
        </tr>
        <c:forEach items="${list }" var="bean">
        <tr>
            <td>${bean.id }</td>
            <td>${bean.name }</td>
            <td>${bean.age }</td>
        </tr>
        </c:forEach>
    </table>
  </body>
</html>

我的访问路径:http://localhost:8080/Spring001/List.Action

项目目录结构:

如果您想了解更多相关信息,可以来关注一下赢咖4的SSM整合视频教程,里面的内容详细,适合没有基础的小伙伴学习,希望对大家能够有所帮助。

提交申请后,顾问老师会电话与您沟通安排学习

免费课程推荐 >>
技术文档推荐 >>