zoukankan      html  css  js  c++  java
  • SSM

    • u  三大框架基本概念

                     spring、SpringMVC、Mybatis

    • u  整合思路
    • u  环境准备
    • u  工程结构
    • u  SPRING + SPING MVC + MYBATIS 三大框架整合
      • ü  Mybatis和spring进行整合
      • ü  Spring整合service
      • ü  整合springMVC
      • ü  配置前端控制器
      • ü  编写登录页面
      • ü  数据库配置和日志配置
      • ü  项目部署

    1      三大框架基本概念

    • spring:

    Spring是一个开源框架,Spring是于2003 年兴起的一个轻量级的Java 开发框架,由Rod Johnson 在其著作Expert One-On-One J2EE Development and Design中阐述的部分理念和原型衍生而来。它是为了解决企业应用开发的复杂性而创建的。Spring使用基本的JavaBean来完成以前只可能由EJB完成的事情。然而,Spring的用途不仅限于服务器端的开发。从简单性、可测试性和松耦合的角度而言,任何Java应用都可以从Spring中受益。 简单来说,Spring是一个轻量级的控制反转(IoC)和面向切面(AOP)的容器框架。

    • SpringMVC:

    Spring MVC属于SpringFrameWork的后续产品,已经融合在Spring Web Flow里面。Spring MVC 分离了控制器、模型对象、分派器以及处理程序对象的角色,这种分离让它们更容易进行定制。

    • Mybatis:

    MyBatis 本是apache的一个开源项目iBatis, 2010年这个项目由apache software foundation 迁移到了google code,并且改名为MyBatis 。MyBatis是一个基于Java的持久层框架。iBATIS提供的持久层框架包括SQL Maps和Data Access Objects(DAO)MyBatis 消除了几乎所有的JDBC代码和参数的手工设置以及结果集的检索。MyBatis 使用简单的 XML或注解用于配置和原始映射,将接口和Java的POJOs(Plain Old Java Objects,普通的 Java对象)映射成数据库中的记录。

    2      整合思路

    SSM系统架构 :

     

    spring将各层进行整合

    • 通过spring管理持久层的mapper(相当于dao接口)
    • 通过spring管理业务层service,service中可以调用mapper接口。
    • spring进行事务控制。
    • 通过spring管理表现层Handler,Handler中可以调用service接口。

    mapper、service、Handler都是javabean。

    第一步:整合dao层

    ü     mybatis和spring整合,通过spring管理mapper接口。

    ü     使用mapper的扫描器自动扫描mapper接口在spring中进行注册。

    第二步:整合service层

    ü     通过spring管理service接口。

    ü     使用配置方式将service接口配置在spring配置文件中。

    ü     实现事务控制。

    第三步:整合springMVC

    ü     由于springMVC是spring的模块,不需要和spring整合,直接把springMVC加入到项目中即可。

     3.      示例:

    1.

    2. login.jsp

    <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
    <%
    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 'login.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>
           <form action="<%=path %>/login.action" method="post">
               用户名:<input type="text" name="username" ><br/>
               密码:<input type="text" name="password"><br/>
               <input type="submit" value="提交">
           </form>
           ${message }
      </body>
    </html>

    3. success.jsp 

    <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
    <%
    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 'sucess.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>
        id:${user.id }<br>
        username:${user.username }<br/>
        password:${user.password }<br/>
      </body>
    </html>

    4. web.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <web-app version="3.0" 
        xmlns="http://java.sun.com/xml/ns/javaee" 
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
        xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
        http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
      <display-name></display-name>    
      
      <!-- 加载Spring容器 -->
      <context-param>
          <param-name>contextConfigLocation</param-name>
          <param-value>classpath:/spring/applicationContext-*.xml</param-value>
      </context-param>
      <listener>
          <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
      </listener>
      
      <!-- springmvc前端控制器 -->
      <servlet>
          <servlet-name>springmvc_rest</servlet-name>
          <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!-- 初始化时加载配置文件 -->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:/spring/springmvc.xml</param-value>
        </init-param>
        <!-- 表示容器在启动时立即加载Servlet -->
        <load-on-startup>1</load-on-startup>
      </servlet>
      <servlet-mapping>
          <servlet-name>springmvc_rest</servlet-name>
          <url-pattern>/</url-pattern>
      </servlet-mapping>
      
      <!-- 解决post请求的中文乱码问题 -->
      <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>
      </filter>
      <filter-mapping>
              <filter-name>CharacterEncodingFilter</filter-name>
              <url-pattern>/*</url-pattern>
      </filter-mapping>
      
      <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
      </welcome-file-list>
    </web-app>

    5. springmvc.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:p="http://www.springframework.org/schema/p"
        xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context"
        xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
        xsi:schemaLocation="http://www.springframework.org/schema/beans  
                            http://www.springframework.org/schema/beans/spring-beans.xsd  
                            http://www.springframework.org/schema/mvc  
                            http://www.springframework.org/schema/mvc/spring-mvc.xsd  
                            http://www.springframework.org/schema/context  
                            http://www.springframework.org/schema/context/spring-context.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">
        <!-- 指定需要扫描的包 -->
        <context:component-scan base-package="com.inspur.ssm.*"></context:component-scan>
    
        <!-- 使用mvc注解驱动,代替注解映射器和注解适配器配置 -->
        <mvc:annotation-driven></mvc:annotation-driven>
        
        
        <!-- 视图解析器  -->
        <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
            <property name="prefix" value="/"></property>
            <property name="suffix" value=".jsp"></property>
        </bean>
    
    </beans>

    6. (1)applicationContext-dao.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:p="http://www.springframework.org/schema/p"  
        xmlns:mvc="http://www.springframework.org/schema/mvc"  
        xmlns:context="http://www.springframework.org/schema/context"
        xmlns:aop="http://www.springframework.org/schema/aop" 
        xmlns:tx="http://www.springframework.org/schema/tx"   
        xsi:schemaLocation="http://www.springframework.org/schema/beans  
                            http://www.springframework.org/schema/beans/spring-beans.xsd  
                            http://www.springframework.org/schema/mvc  
                            http://www.springframework.org/schema/mvc/spring-mvc.xsd  
                            http://www.springframework.org/schema/context  
                            http://www.springframework.org/schema/context/spring-context.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"> 
        <!-- 加载配置文件db.properties中的内容,db.properties文件中key命名要有一定命名规则 -->
        <context:property-placeholder location="classpath:db.properties"></context:property-placeholder>
        
        <!-- 配置数据源 -->
        <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
            <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>
        
        <!-- 配置Mybatis工厂:sqlSessionFactory -->
        <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
            <!-- 注入数据源 -->
            <property name="dataSource" ref="dataSource"></property>
            <!-- 指定核心配置文件位置:加载mybatis的配置文件 -->
            <property name="configLocation" value="classpath:mybatis/sqlMapConfig.xml"></property>
        </bean>
        
        <!-- Mapper代理开发(基于MapperScannerConfigurer):mapper批量扫描 -->
        <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
            <property name="basePackage" value="com.inspur.ssm.mapper"></property>
            <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
        </bean>
    
        
    
    </beans>

     (2)applicationContext-transaction.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:p="http://www.springframework.org/schema/p"
        xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context"
        xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
        xsi:schemaLocation="http://www.springframework.org/schema/beans  
                            http://www.springframework.org/schema/beans/spring-beans.xsd  
                            http://www.springframework.org/schema/mvc  
                            http://www.springframework.org/schema/mvc/spring-mvc.xsd  
                            http://www.springframework.org/schema/context  
                            http://www.springframework.org/schema/context/spring-context.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">
          <!-- 事务管理器,依赖于数据源:事务管理器,对mybatis操作数据库的事务控制,spring使用jdbc的事务控制类 -->
          <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
                  <!-- 数据源dataSource在 applictaionContext-dao.xml配置了 -->
                  <property name="dataSource" ref="dataSource"></property>
          </bean>                   
                            
    </beans>

    7. 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.inspur.ssm.pojo"/>
        </typeAliases>
    </configuration>

    8. LoginController.java

    package com.inspur.ssm.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.web.bind.annotation.RequestMapping;
    
    import com.inspur.ssm.pojo.Userssm;
    import com.inspur.ssm.service.LoginService;
    
    
    @Controller
    public class LoginController {
        @Autowired
        private LoginService loginService;
        //登录
        @RequestMapping("/login")
        public String login(HttpServletRequest request,Userssm userssm) throws Exception{
            Userssm user=null;
            try {
                user=loginService.findUser(userssm);
                
            } catch (Exception e) {
                // TODO: handle exception
                e.printStackTrace();
                request.setAttribute("message", e.getMessage());
            }
            if(user!=null){
                HttpSession session = request.getSession();
                //在session中保存用户信息
                session.setAttribute("user", user);
                //重定向到登录成功页面
                return "success";
            }
            return "login";
            
        }
    
    }

    9. UserssmMapper.java

    package com.inspur.ssm.mapper;
    
    import com.inspur.ssm.pojo.Userssm;
    
    public interface UserssmMapper {
        Userssm findUser(Userssm userssmQuery);
    
    }

    10. UsessmrMapper.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.inspur.ssm.mapper.UserssmMapper">
        <select id="findUser" resultType="userssm" parameterType="userssm">
            select * from userssm where username=#{username} and password=#{password}
        </select>
    </mapper>

    11. Userssm.java

    package com.inspur.ssm.pojo;
    
    public class Userssm {
        private String id;
        private String username;
        public String getId() {
            return id;
        }
        public void setId(String id) {
            this.id = id;
        }
        public String getUsername() {
            return username;
        }
        public void setUsername(String username) {
            this.username = username;
        }
        public String getPassword() {
            return password;
        }
        public void setPassword(String password) {
            this.password = password;
        }
        private String password;
        
    
    }

    12. LoginService.java

    package com.inspur.ssm.service;
    
    import javax.annotation.Resource;
    
    import com.inspur.ssm.pojo.Userssm;
    
    @Resource
    public interface LoginService {
        //查询用户列表
        public Userssm findUser(Userssm userssm) throws Exception;
    
    }

    13. LoginServiceImpl.java

    package com.inspur.ssm.serviceImpl;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    
    import com.inspur.ssm.mapper.UserssmMapper;
    import com.inspur.ssm.pojo.Userssm;
    import com.inspur.ssm.service.LoginService;
    
    @Service("loginService")
    public class LoginServiceImpl implements LoginService {
        @Autowired
        private UserssmMapper userssmMapper;
        @Override
        public Userssm findUser(Userssm userssmQuery) throws Exception {
            // TODO Auto-generated method stub
            Userssm userssm = userssmMapper.findUser(userssmQuery);
            if(userssm==null){
                throw new Exception("用户信息不存在");
            }else{
                return userssm;
            }
        }
    
    }

    14.  db.properties

    jdbc.driver=oracle.jdbc.driver.OracleDriver
    jdbc.url=jdbc:oracle:thin:@localhost:1521:inspur
    jdbc.username=scott
    jdbc.password=tiger

    15. log4j.properties

    log4j.appender.stdout=org.apache.log4j.ConsoleAppender
    log4j.appender.stdout.Target=System.out
    log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
    log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p [%t] %c{1}:%L - %m%n
    #在开发环境下日志级别要设置成DEBUG,生产环境设置成info或error
    log4j.rootLogger=DEBUG, stdout

    4.     对应数据库语言

    create table USERSSM
    (
      ID   NUMBER(6) not null,
      userNAME VARCHAR2(100) not null,
      role VARCHAR2(10),
      realname VARCHAR2(10),
      password VARCHAR2(10)
    
    )
    select * from userssm for update

     5.        浏览器运行结果

    查询成功:

    查询失败:

     

  • 相关阅读:
    Oracle 常用的V$ 视图脚本
    Oracle11g新特性
    深入浅出Oracle:Redo的作用
    oracle表空间操作详解
    Oracle Directory
    linux下手动删除数据库实例
    Oracle OS认证以及口令文件
    监控Oracle数据库的常用shell脚本
    Oracle 帐号基本管理
    Oracle小知识
  • 原文地址:https://www.cnblogs.com/sunxiaoyan/p/9227425.html
Copyright © 2011-2022 走看看