Spring入门IOC(控制反转)与三层架构的简单登录小例子

1.创建基于web的maven项目(编辑器推荐使用intellij idea)

2.导入spring需要的依赖(包括spring的基本包和web包)

2.1 为了方便管理依赖的版本,引入properties

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <!-- spring版本号 -->
    <spring.version>4.1.3.RELEASE</spring.version>
</properties>

2.2添加需要依赖的坐标

<dependencies>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>3.8.1</version>
        <scope>test</scope>
    </dependency>
    <!-- 添加spring核心依赖 -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <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>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context-support</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-web</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>3.1.0</version>
        <scope>provided</scope>
    </dependency>
</dependencies>

3.建立基本的目录结构

      Action是管理业务(Service)调度和管理跳转的。

      Service是管理具体的功能的。

      Action只负责管理,而Service负责实施。

      DAO只完成增删改查,虽然可以1-n,n-n,1-1关联,模糊、动态、子查询都可以。但是无论多么复杂的查询,dao只是封装增删改查。至于增删查改如何去实现一个功能,dao是不管的。

      总结这三者,通过例子来解释:

      Action像是服务员,顾客点什么菜,菜上给几号桌,都是ta的职责;

      Service是厨师,action送来的菜单上的菜全是ta做的;

      Dao是厨房的小工,和原材料打交道的事情全是ta管。

      相互关系是,小工(dao)的工作是要满足厨师(service)的要求,厨师要满足服务员(action)转达的客户(页面用户)的要求,服务员自然就是为客户服务喽。

4.view登录视图

5.dao层

5.1 userdao接口

public interface UserDao {
    /**
     * 根据用户名查找是否存在此用户
     * @param username
     * @return
     */
    public Boolean findUser(String username);
}

5.2 实现类

@Repository
public class UserDaoImpl implements UserDao {
    /**
     * 根据用户名查找是否存在此用户
     * @param username
     * @return
     */
    @Override
    public Boolean findUser(String username) {
        if ("zty".equals(username)){
            return true;
        }
        else return false;
    }
}
@Repository代表dao层spring管理的bean
@Service代表service层spring管理的bean
@Controller代表action层spring管理的bean(三层地位)

6.service层

6.1 service接口

public interface UserService {
    /**
     * 业务层功能:登录
     * @param username
     */
    public Boolean login(String username);
}

6.2实现类

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDao userDao;

    /**
     * 业务层功能:登录
     *
     * @param username
     * @return
     */
    @Override
    public Boolean login(String username) {
        if (userDao.findUser(username))
            return true;
        else
            return false;
    }
}

7.action(暂时用servlet代替)

public class UserServlet extends HttpServlet {
    @Autowired
    private UserService userService;
    private WebApplicationContext springContext;

    /**
     * 原始servlet不支持spring管理bean,需要手动初始化容器
     * @param config
     * @throws ServletException
     */
    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init();
        springContext= WebApplicationContextUtils.getRequiredWebApplicationContext(config.getServletContext());
        final AutowireCapableBeanFactory beanFactory=springContext.getAutowireCapableBeanFactory();
        beanFactory.autowireBean(this);
    }

    /**
     * 如果用户名存在,跳转到百度
     * 若不正确,跳转到网易
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username=req.getParameter("username");
        if (userService.login(username)){
            //网址前需要http://
            resp.sendRedirect("http://www.baidu.com");
        }
        else
            resp.sendRedirect("http://www.163.com");
    }
}

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

 <context:component-scan base-package="edu.cn.*"></context:component-scan>
</beans>

9.在web.xml文件中添加spring容器和servlet映射

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
 <display-name>Archetype Created Web Application</display-name>
 <context-param>
 <param-name>contextConfigLocation</param-name>
 <param-value>classpath:applicationContext.xml</param-value>
 </context-param>
 <listener>
 <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
 </listener>
 <servlet>
 <servlet-name>UserServlet</servlet-name>
 <servlet-class>edu.cn.action.UserServlet</servlet-class>
 </servlet>
 <servlet-mapping>
 <servlet-name>UserServlet</servlet-name>
 <url-pattern>/userServlet</url-pattern>
 </servlet-mapping>
</web-app>

10.当@Autowired注入的接口存在多个实现类该怎么办?

第一种方式是:
@Autowired(required = true)
@Qualifier("smsWaitingDaoHibernate")
private SmsWaitingDao smsWaitingDaoHibernate;
spring创建对象的名称为类名第一个字母小写,所以@Qualifier("")中的参数填类名第一个字母小写即可,此时注入的对象为按名称注入,@Autowired默认按类型注入。

第二种方式是:
@Resource注解,需要用哪个具体实现类,就用它的BeanName,例如: @Resource(name="oneService") 
private IShopService userService;
@Resource(name="twoService")
private IShopService userService。
这种注解实际上就是在实例化具体对象。

11.至今为止,完成该项目的代码工作,这是第一篇正式上线的博客,之后会有更多精彩。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值