1. 程式人生 > >SSM框架整合(實現從數據庫到頁面展示)

SSM框架整合(實現從數據庫到頁面展示)

patch beans response 由於 spring容器 void 不用 html show

        SSM框架整合(實現從數據庫到頁面展示)

    首先創建一個spring-web項目,然後需要配置環境dtd文件的引入,環境配置,jar包引入。

首先讓我來看一下ssm的基本項目配件。(代碼實現)

    技術分享圖片

1.首先編寫web.xml文件。

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://xmlns.jcp.org/xml/ns/javaee"
    xsi:schemaLocation
="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1"> <display-name>ssmdemo</display-name> <!-- 創建spring容器:為了查找spring容器要管理的所有bean --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring/application*.xml</param-value> </context-param> <!-- g該類在web.jar的context包下的ContextLoaderListener,該類實現了監聽器接口 --> <listener> <listener-class
>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- 創建前端控制器 --> <servlet> <servlet-name>ssm</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring/spring-mvc.xml</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>ssm</servlet-name> <url-pattern>*.action</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.html</welcome-file> </welcome-file-list> </web-app>

2.建mybatis-config.xml和spring-mvc.xml文建的配置。

    1.myatis-config.xml  

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "http://mybatis.org/dtd/mybatis-3-config.dtd" "mybatis-3-config.dtd" >
<configuration>
    <typeAliases>
        <package name="com.bean.*" />
    </typeAliases>
</configuration>

    2.spring-mvc.xml(使用註解掃描@Controller,@ResquestMapping(“指定路徑”))

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:tx="http://www.springframework.org/schema/tx" xmlns:xsd="http://www.w3.org/2001/XMLSchema"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 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/aop 
    http://www.springframework.org/schema/aop/spring-aop.xsd 
    http://www.springframework.org/schema/context 
    http://www.springframework.org/schema/context/spring-context.xsd
     http://www.springframework.org/schema/tx 
     http://www.springframework.org/schema/tx/spring-tx.xsd 
     http://www.springframework.org/schema/mvc 
     http://www.springframework.org/schema/mvc/spring-mvc.xsd ">
    <!-- 開啟註解掃描 -->
    <context:component-scan base-package="com.controller,com.service.impl" />
    <!-- 開啟處理器 -->
    <mvc:annotation-driven />
    <bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/pages/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>
</beans>

3.application-dao.xml,application-tx,application-service配置

     1)application-dao.xml和IUsersDao.xml的配置以及IUsersDao.java類的實現。

    1.application-dao.xml:IUsersDao.java的配置(數據庫查詢數據)

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:tx="http://www.springframework.org/schema/tx" xmlns:xsd="http://www.w3.org/2001/XMLSchema"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 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/aop 
    http://www.springframework.org/schema/aop/spring-aop.xsd 
    http://www.springframework.org/schema/context 
    http://www.springframework.org/schema/context/spring-context.xsd
     http://www.springframework.org/schema/tx 
     http://www.springframework.org/schema/tx/spring-tx.xsd 
     http://www.springframework.org/schema/mvc 
     http://www.springframework.org/schema/mvc/spring-mvc.xsd ">
    <!-- 配置數據源 c3p0數據庫連接池。到對應的連接池jar中找 -->
    <context:property-placeholder location="classpath:db.properties" />
    <bean id="ds" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="DriverClass" value="${Adirver}"></property>
        <property name="JdbcUrl" value="${Aurl}"></property>
        <property name="User" value="${Ausername}"></property>
        <property name="Password" value="${Apassword}"></property>
    </bean>
    <!-- factory:mybatis-spring整合包中找。 -->
    <bean id="factory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="configLocation" value="classpath:mybatis/mybatis-config.xml"></property>
        <property name="dataSource" ref="ds"></property>
    </bean>
    <!-- 批量創建dao代理類對象:符合mybatis的mapper代理方式規範 -->
    

     2.IUsersDao.java類

package com.dao;

import java.util.List;
import com.bean.UsersBean;

public interface IUsersDao {

    /**
     * 過去所有用戶
     * @return
     */
    public List<UsersBean> getAllUser();
}

    3.IUsersDao.xml:Mapper映射。

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "http://mybatis.org/dtd/mybatis-3-mapper.dtd" "mybatis-3-mapper.dtd" >
<mapper namespace="com.dao.IUsersDao">
    <select id="getAllUser" resultType="com.bean.UsersBean">
        select * from users
    </select>
</mapper>

    2)application-service.xml和UsersService.java

     1.application-service.xml:業務層的xml配置,創建bean是IUsersBean與UsersService關聯。

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:tx="http://www.springframework.org/schema/tx" xmlns:xsd="http://www.w3.org/2001/XMLSchema"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 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/aop 
    http://www.springframework.org/schema/aop/spring-aop.xsd 
    http://www.springframework.org/schema/context 
    http://www.springframework.org/schema/context/spring-context.xsd
     http://www.springframework.org/schema/tx 
     http://www.springframework.org/schema/tx/spring-tx.xsd 
     http://www.springframework.org/schema/mvc 
     http://www.springframework.org/schema/mvc/spring-mvc.xsd ">
    <bean id="usersService" class="com.service.impl.UsersServiceImpl" />
</beans>

    2.UsersSerivce.java類

package com.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import com.bean.UsersBean;
import com.dao.IUsersDao;
import com.service.IUsersService;

public class UsersServiceImpl implements IUsersService {

    @Autowired
    private IUsersDao userDao;

    @Override
    public List<UsersBean> findAllUser() {
        // TODO Auto-generated method stub
        return userDao.getAllUser();
    }

}

  3)application-tr.xml配置

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:tx="http://www.springframework.org/schema/tx" xmlns:xsd="http://www.w3.org/2001/XMLSchema"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 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/aop 
    http://www.springframework.org/schema/aop/spring-aop.xsd 
    http://www.springframework.org/schema/context 
    http://www.springframework.org/schema/context/spring-context.xsd
     http://www.springframework.org/schema/tx 
     http://www.springframework.org/schema/tx/spring-tx.xsd 
     http://www.springframework.org/schema/mvc 
     http://www.springframework.org/schema/mvc/spring-mvc.xsd ">

    <!-- 事務配置管理器 :jdbc->jdbc.datasource -->
    <bean id="transactionManager"
        class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="ds"></property>
    </bean>
    <!-- 增強,通知 -->
    <tx:advice id="advice" transaction-manager="transactionManager">
        <tx:attributes>
            <!-- 此處規定開發的方法前綴規範: -->
            <!-- 增刪 改的方法REQUIRED(required) -->
            <!-- 查詢所有方法是SUPPORTS,read-only -->
            <tx:method name="add*" propagation="REQUIRED" />
            <tx:method name="delete*" propagation="REQUIRED" />
            <tx:method name="update*" propagation="REQUIRED" />
            <tx:method name="find*" propagation="SUPPORTS" read-only="true" />
            <tx:method name="get*" propagation="SUPPORTS" read-only="true" />
        </tx:attributes>
    </tx:advice>
    <!-- 定義aop -->
    <aop:config>
        <aop:pointcut expression="execution(* com.service.impl.*.*(..))"
            id="pcut" />
        <aop:advisor advice-ref="advice" pointcut-ref="pcut" />
    </aop:config>
</beans>

4.Controller類的配置(註解配置)

  1.返回路徑相當於地址欄。

package com.controller;

import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.bean.UsersBean;
import com.service.IUsersService;

/**
 * Handler
 * 
 * @author Ya
 *
 */
@Controller
public class UsersController {

    @Resource(name = "usersService")
    private IUsersService usersService;

    /**
     * 返回相等路徑
     * 
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping("/showAll")
    public String showAll(Model model) {
        // 調用業務方法
        List<UsersBean> list = usersService.findAllUser();
        // 將list返回
        model.addAttribute("USER", list);
        // 跳轉到pages/users/showUsers.jsp頁面,轉發或者重定向
        // return "forward:pages/users/showUsers.jsp";
        return "users/showUsers";
    }
}

  2.返回 累行為ModelAndView

package com.controller;

import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.bean.UsersBean;
import com.service.IUsersService;

/**
 * Handler
 * 
 * @author Ya
 *
 */
@Controller
public class UsersController {

    @Resource(name = "usersService")
    private IUsersService usersService;

    /**
     * ModelAndView
     * 
     * @return
     */
    @RequestMapping("/showAll")
    public ModelAndView showAll() {
        // 獲取業務的查詢結果
        List<UsersBean> list = usersService.findAllUser();
        // 將查詢的結果集合顯示到pages/showUsers.jsp
        ModelAndView m = new ModelAndView();
        // 存儲list
        m.addObject("USER", list);
        // 指定試圖資源:
        // 由於spring-mvc.xml文件中配置了試圖解析器的前綴和後綴 m.setViewName("users/showUsers");
        return m;
    }

}

  3.返回forward轉發

package com.controller;

import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.bean.UsersBean;
import com.service.IUsersService;

/**
 * Handler
 * 
 * @author Ya
 *
 */
@Controller
public class UsersController {

    @Resource(name = "usersService")
    private IUsersService usersService;

    /**
     * 轉發
     * 
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping("/showAll")
    public void showAll(HttpServletRequest request, HttpServletResponse response) throws Exception {
        // 調用業務方法
        List<UsersBean> list = usersService.findAllUser();
        // 將list返回
        request.setAttribute("USER", list);
        // 跳轉到pages/users/showUsers.jsp頁面,轉發或者重定向
        // request.getRequestDispatcher("pages/users/showUsers.jsp").forward(request,
        // response);
        response.sendRedirect("pages/users/showUsers.jsp");
    }

   4.返回為重定向。

package com.controller;

import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.bean.UsersBean;
import com.service.IUsersService;

/**
 * Handler
 * 
 * @author Ya
 *
 */
@Controller
public class UsersController {

    @Resource(name = "usersService")
    private IUsersService usersService;

    /**
     * 重定向
     * 
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping("/showAll")
    public void showAll1(HttpServletRequest request, HttpServletResponse response) throws Exception {
        // 調用業務方法
        List<UsersBean> list = usersService.findAllUser();
        // 將list返回
        HttpSession session = request.getSession();
        session.setAttribute("USER", list);
        // 跳轉到pages/users/showUsers.jsp頁面,轉發或者重定向
        response.sendRedirect("pages/users/showUsers.jsp");
    }

    5.直接return “redirect:pages/users/showUsers.jsp”

package com.controller;

import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.bean.UsersBean;
import com.service.IUsersService;

/**
 * Handler
 * 
 * @author Ya
 *
 */
@Controller
public class UsersController {

    @Resource(name = "usersService")
    private IUsersService usersService;

    /**
     * 返回值為String
     * 
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping("/showAll")
    public String showAll(HttpServletRequest request) throws Exception {
        // 調用業務方法
        List<UsersBean> list = usersService.findAllUser();
        // 將list返回
         HttpSession session=request.getSession();
        session.setAttribute("USER", list);
        // 跳轉到pages/users/showUsers.jsp頁面,轉發或者重定向
        return "forward:pages/users/showUsers.jsp";
        // return "redirect:pages/users/showUsers.jsp";
    }

  7.直接return“forward:pages/users/showUsers.jsp”;

package com.controller;

import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.bean.UsersBean;
import com.service.IUsersService;

/**
 * Handler
 * 
 * @author Ya
 *
 */
@Controller
public class UsersController {

    @Resource(name = "usersService")
    private IUsersService usersService;

    /**
     * 返回值為String
     * 
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping("/showAll")
    public String showAll(HttpServletRequest request) throws Exception {
        // 調用業務方法
        List<UsersBean> list = usersService.findAllUser();
        // 將list返回
        request.setAttribute("USER", list);
        // 跳轉到pages/users/showUsers.jsp頁面,轉發或者重定向
        return "forward:pages/users/showUsers.jsp";
    }

以上隨便一種方式都是可以的。

    總結:

      1.我們主要是學習了ssm整合,把數據庫的數據的數據展示到網頁中。主要分為

      dao-->service-->controller-->jsp

      2.

        1)dao主要是輔助取出數據庫的數據,dao到daoMapper批量映射。獲取數據,鏈接數據庫是又application-dao.xml文件來集成配置管理。

        2)service 為業務層,由application-service.xml文件管理。主要是配置IUsersDao,使service中不用newIUsersDao。

        3)controller主要是將業務層取來數據傳遞到jsp頁面中,然後將數據攜帶到要跳轉的jsp頁面中。

        4)jsp接受並展示數據controller中傳遞來的參數。

      3.spring中的application*.xml和spring-mvc.xml的xml文件在WEB-INF/web.xml中進行解析;

       mybatis中的mybatis-config.xml中的xml文件在application-dao.xml文件中被解析。

      

    有問題請留言!!

         

SSM框架整合(實現從數據庫到頁面展示)