SSM框架总结

直接以json方式返回服务器对象

案例:在welcome页面增加图书查询的功能!

1.生成数据库表,添加数据

DROP TABLE IF EXISTS `book`;
CREATE TABLE `book` (
  `ID` int(4) NOT NULL AUTO_INCREMENT,
  `Name` varchar(100) DEFAULT NULL,
  `Author` varchar(50) DEFAULT NULL,
  `Price` decimal(10,0) DEFAULT NULL,
  `Publisher` varchar(100) DEFAULT NULL,
  PRIMARY KEY (`ID`)
) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of book
-- ----------------------------
INSERT INTO `book` VALUES ('1', '明朝那些事儿图文增订版', '当年明月', '82', '北京联合出版公司');
INSERT INTO `book` VALUES ('2', '战争从未如此热血4:二战美日太平洋大对决:西方视角下的晚清图景', '关河五十州', '29', '民主与建设出版社');
INSERT INTO `book` VALUES ('3', '我们的征途是星辰大海', '花千芳', '20', '作家出版社');
INSERT INTO `book` VALUES ('4', '松下幸之助经营智慧书', '松下幸之助', '54', '人民文学出版社');
INSERT INTO `book` VALUES ('5', '大数据时代', '(英)迈尔-舍恩伯格', '31', '浙江人民出版社');
INSERT INTO `book` VALUES ('6', '销售就是要搞定人—一个销售总经理十六年的抢单笔记', '倪建伟', '21', '时代文艺出版社');
INSERT INTO `book` VALUES ('7', '这个男生不太冷:告诉你一个真实的陈楚生', '万俊人', '24', '海南出版社');


2.welcome.jsp 页面设计

<body>
欢迎${name}登录!<br/>
<br/>
<br/>
请输入书名进行模糊查询:<input type="text" id="pattern" >
<input type="button" id="get" value="获取图书"><br>
<table id="books">
</table>
</body>

3.引入JQuery库

拷贝jquery库文件到jslib目录下

<script type="text/javascript" src="${pageContext.request.contextPath}/jslib/jquery-1.11.1.js"></script>
<script type="text/javascript">
$(function(){
})
</script>

4.编写Book实体

5.编写BookMapper接口和BookMapper映射文件
  
   添加通过图书名称模糊查询的方法

6.编写dao方法

7.编写controller方法

8.引入jackson包(core,annotations,databind)

    http://pan.baidu.com/s/1i3GoYsl

9.修改配置文件(第一个bean可以省略)

<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">  
    <property name="messageConverters">  
        <list>  
            <bean class="org.springframework.http.converter.StringHttpMessageConverter">  
                <property name="supportedMediaTypes">  
                    <list>  
                        <value>text/html; charset=UTF-8</value>  
                        <value>application/json;charset=UTF-8</value>  
                    </list>  
                </property>  
            </bean>  
            <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">  
                <property name="supportedMediaTypes">  
                    <list>  
                        <value>text/html; charset=UTF-8</value>  
                        <value>application/json;charset=UTF-8</value>  
                    </list>  
                </property>  
            </bean>  
        </list>  
    </property>  
</bean>  

2,    前端接收到json后的处理
    jquery的append方法

 

1.新建Java项目,引入jar包,mybatis的jar包和mysql的jar包src

    mybatis的jar包下载
    https://github.com/mybatis/mybatis-3/releases
 
2.建立数据库users,建立表user(id,userName,userPwd)

3.引入mybatis的主配置文件mybatis-config.xml(名字在代码中要用到)

    http://mybatis.github.io/mybatis-3/getting-started.html

   

 <?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>  


    
    <!-- 对事务的管理和连接池的配置 -->  
    

<environments default="development">  
        <environment id="mysql">  
            <transactionManager type="JDBC" />  
            <dataSource type="POOLED">  
                <property name="driver" value="com.mysql.jdbc.Driver" />  
                <property name="url" value="jdbc:mysql://localhost/users" />  
                <property name="username" value="root" />  
                <property name="password" value="" />  
            </dataSource>  
        </environment>  
    </environments>  


      
    <!-- mapping 文件路径配置 -->  
   

       <mappers>  
        <!-- <mapper class="javastudy.UserMapper" />   -->
        <!-- <mapper resource="userMapper.xml"/> --> 
       </mappers>  
    </configuration>

4.将数据库连接信息写入单独的properties文件

    (1)主配置文件中将连接参数修改为变量
   

    <property name="driver" value="${db.driver}" />  
    <property name="url" value="${db.url}" />  
    <property name="username" value="${db.user}" />  
    <property name="password" value="${db.password}" />  

    (2)引入db.properties文件
        

<properties resource="db.properties"></properties>

    (3)在src目录下添加db.properties文件

    

    db.driver=com.mysql.jdbc.Driver
    db.url=jdbc:mysql://localhost/users
    db.username=root
    db.password=

5.编写实体类User
  User(id,userName,userPwd)

6.在实体类所在包下,编写userMapper.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="javastudy.userMapper">
        <select id="selectUser" parameterType="int" resultType="javastudy.User">
            select * from User where id = #{id}
        </select>
    </mapper>

7.编写测试程序

(1)编写MyBatis的工具类

  

 import java.io.IOException;
    import java.io.InputStream;
    import org.apache.ibatis.io.Resources;
    import org.apache.ibatis.session.SqlSession;
    import org.apache.ibatis.session.SqlSessionFactory;
    import org.apache.ibatis.session.SqlSessionFactoryBuilder;

    public class MybatisUtils {
        public static SqlSession openSession() throws IOException
        {
            String resource = "mybatis-config.xml";
            InputStream in = Resources.getResourceAsStream(resource);
            SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(in,"mysql");
            return sessionFactory.openSession();
        }
    }

8,
    准备工作:
  1.建立项目Student&Contact,拷贝mybatis主配置文件,properties文件,MyBatisUtils工具类
  2.建立实体类Student和Contact
  3.建立StudentMapper.xml和ContactMapper.xml映射文件模板
  4.建立StudentMapper和ContactMapper接口
  5.建表student和contact,设定其一对一的对应关系
9,
    mybatis日志
(1)mybatis.properties

   

    # Global logging configuration  
    log4j.rootLogger=ERROR, stdout  
    # MyBatis logging configuration...  
    log4j.logger.javastudy=DEBUG  
    # Console output...  
    log4j.appender.stdout=org.apache.log4j.ConsoleAppender  
    log4j.appender.stdout.layout=org.apache.log4j.PatternLayout  
    log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n 

    注意这行代码
    log4j.logger.javastudy=DEBUG  
10,
    多对多需要建立中间表
    student_course(sid,cid)

11,
    primary key , 复合主键,联合主键(composite key)
    让sid和cid都做主键(复合主键)
    提取学生的时候,要把学生选择的所有课程也提取出来。(三个表的左连接查询,相对比较复杂)

    left jion :学生即使没有选择课程,也能把学生的信息提取出来。

    from student,course where (=内连接:inner join) 
    ... 如果学生没有选择课程,学生的信息也提取不出来

12,
    三)修改
    关联字段一般不需要修改!!一定要修改的话,需要处理好关联关系

13,
    IOC控制反转,AOP面向切面编程

14,
    什么是spring mvc? spring框架中的一个产品中提供的mvc框架,实现类似 struts的功能。

    主要功能:收集表单信息,处理数据,完成处理后的跳转

    1.先准备mybatis环境

    2.准备springmvc环境

    spring mvc 基于 servlet ,需要在web.xml中配置 DispatcherServlet
    相比之下,struts2基于过滤器filter,struts1基于servlet,

    搭建步骤
    1)spring jar下载地址

     http://maven.springframework.org/release/org/springframework/spring/

     7个jar包的下载地址:http://pan.baidu.com/s/1c02lQla

     beans,context,aop,core,web,webmvc,expression + comms-logging

     ClassNotFoundException:类找不到异常

    2)配置web.xml,引入前端控制器DispatcherServlet


    <!-- Spring MVC配置 -->

    

<servlet>
      <servlet-name>spring</servlet-name>
      <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>

<servlet-mapping>
     <servlet-name>spring</servlet-name>
     <url-pattern>*.do</url-pattern>
</servlet-mapping>

    特别注意servlet-name,这个名字要用于创建springmvc的配置文件。!!!!!!!!!!

    3) WEB-INF下创建配置文件
    spring-servlet.xml.(spring这个名字要求和web.xml中配置servlet-name的名字一样)

    格式和spring的基础配置文件(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"
        xsi:schemaLocation="http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

    </beans>

    4)springmvc可以采用xml配置或者注解配置,xml配置很少用,也比较麻烦,我们只讲解注解配置。

    a)引入相关的命名空间mvc和context

    xmlns:mvc="http://www.springframework.org/schema/mvc"  

    http://www.springframework.org/schema/mvc  
        http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd


    xmlns:context="http://www.springframework.org/schema/context"  

        http://www.springframework.org/schema/context  
        http://www.springframework.org/schema/context/spring-context-4.1.xsd 

    b)设置注解驱动

    <mvc:annotation-driven/>

    c)设置controller扫描路径的包名,spring mvc会自动的实例化该包下的controller。
      controller相当于struts中的action,用于处理数据,完成转发。
            <context:component-scan base-package="javastudy"/>

15,
    新建controller接收页面数据
    redirect:
    1)RequestMapping的设置
    2) 如何接受表单数据:通过HttpServletRequest接收数据,像servlet那样操作springmvc。
    3)通过对象接收数据
    4)通过ModelAndView处理数据和转发

16,
        springMVC
    @Controller   实例化类
    public class UserController {

    @RequestMapping("/checke.do")  配置路径
    public String check()
    {

17,
    设置容器外跳转return "redirect:welcome.jsp";去掉redirect编程容器内跳转,

 

1,引入jar包,放到src,在选中点右键Buildpath
2,
 

<select id="selectUser" resultType="javastudy.User">
        select * from User where id = #{id}
    </select>
     <select id="selectall"  resultType="javastudy.User">
        select * from User 
    </select>
    <insert id="insertuser" parameterType="javastudy.User" >
         insert into user (userName,userPwd) values (#{userName},#{userPwd})     
    </insert>
    <update id="updateuser" parameterType="javastudy.User">
        update user set userName=#{userName},userPwd=#{userPwd} where id=#{id}
    </update>
    <delete id="deleuser" >
        delete from user where id=#{id}
    </delete>


3,sql语句可以写在
    1,映射文件里也可以通过
    2,注解写在接口里    
    3.写在专门的类中

4,
    保存联系人信息的时候,指定该联系人对应的学生。

    返回插入后生成的自增长属性值的办法
    useGeneratedKeys="true" keyProperty="id"
    加在student的映射文件里 
    (在有主键,主表一方加)<insert id="add"parameterType="javastudy.Student" useGeneratedKeys="true" keyProperty="id">
    
5, 

insert into student
   (
        name,
        sex,
        pwd,
        phone,
        grade,
        photo
   )
   values
   (
        #{name},
        #{sex},
        #{pwd},
        #{phone},
        #{grade},
        #{photo}
   )


   sql语句最后一句不用加逗号
   
 6,测试类
        

public void test() throws IOException {
        SqlSession session= MybatisUtils.openSession();
        StudentMapper mapper= session.getMapper(StudentMapper.class);
        Student student =new Student();
        student.setName("张三");
        student.setSex("男");
        student.setPhone("123456");
        student.setGrade("二年级");
        student.setPwd("1234566");
        mapper.add(student);
        
        ContactMapper mapp= session.getMapper(ContactMapper.class);
        Contact contact =new Contact();
        contact.setName("张三");
        contact.setSex("男");
        contact.setPhone("123456");
        contact.setRelation("cc");
        contact.setStudent(student);//添加学生
        mapp.add(contact);
        
        session.commit();
        session.close();    


    
7,
    特别注意,要在主配置文件中引入Mapper接口!!
        mybatis-config.xml里的<mappers>  
        <mappers>  
            <mapper class="javastudy.ContactMapper"/>
            <mapper class="javastudy.StudentMapper"/>
        </mappers> 
        
8,有外键的要在映射文件配置sid,values;#{student.id}

9,resultMap="student" 必须为小写 

10,

<resultMap type="javastudy.Student" id="student">
           <id property="id" column="sid" />
           <result property="name" column="sname"/>
           <result property="sex" column="ssex"/>    
        <result property="pwd" column="spwd"/>    
        <result property="phone" column="sphone"/>
        <result property="grade" column="sgrade"/>    
        <result property="photo" column="sphoto"/>    
    <association property="contact" javaType="javastudy.Contact">//关联的Contact
        <id property="id" column="cid" />
        <result property="name" column="cname"/>
        <result property="sex" column="csex"/>
        <result property="relation" column="crelation"/>
        <result property="phone" column="cphone"/>
    </association>    
   </resultMap>


   (property必须用name,sex,)
   
11,左连接 left join: 左边表中数据必须出来

  

  select 
            s.id sid,
            s.name sname,
            s.sex ssex,
            s.pwd spwd,
            s.phone sphone,
            s.grade sgrade,
            s.photo sphoto,
            c.id cid,
            c.name cname,
            c.sex csex,
            c.relation crelation,
            c.phone cphone
    from 
            student s(student的数据是一定会出来,这就是使用左连接的好处)
    left join
            contact c (然后是右表)
    ON 
            c.sid=s.id
    WHERE
                  s.id=16

1.修改从表数据
    非关联字段可以随便修改,关联字段sid必须修改为student表中存在的(而且没有联系人的)
    学生的id或者修改为null(前提是contact表的sid已经设置为可空)。

2.修改主表数据,非主键字段可以随便修改,
    !!!!!!!主键字段不能随便修改,一般也不需要修改!!!!!!!

3,  老师单独添加
    添加课程的时候,把课程对应的老师添加进去
    返回插入后生成的自增长属性值的办法
    useGeneratedKeys="true" keyProperty="id"
    
4.一对多在一方加,多对多两方都加(<collection property="courses" ofType="javastudy.Course">);

    

 <resultMap type="javastudy.Teacher" id="teacher">
           <id property="id" column="tid"/>
           <result property="name" column="tname"/>
           <result property="sex" column="tsex"/>
           <result property="phone" column="tphone"/>
       <collection property="courses" ofType="javastudy.Course">
           <id property="id" column="cid"/>
           <result property="name" column="cname"/>
           <result property="type" column="ctype"/>
           <result property="hours" column="chours"/>
       </collection>    


       
5. 学生  学生课程表  课程, 老师(四表)
   (A)      (B)       (C)   (D)
    (A - B) - (C - D)
   

 select
            cid,cname,ctype,chours,
            tid,tname,tsex,tphone,
            sid,sname,ssex,spwd,sphone,sgrade,sphoto
        from 
      (
      select 
        c.id cid,
        c.name cname,
        c.type ctype,
        c.hours chours,
        t.id    tid,
        t.name  tname,
        t.sex   tsex,
        t.phone tphone
      from 
                course c
      left JOIN
        teacher t
      on c.tid=t.id
      ) t1
        left join
            (
            select
                    s.id     sid,
                    s.name     sname,
                    s.sex      ssex,
                    s.pwd     spwd,
                    s.phone    sphone,
                    s.grade sgrade,
                    s.photo sphoto,
                    sc.cid    sccid            
            from 
                student_course sc
            left join
                student s
            on sc.sid=s.id
            ) t2
        on t1.cid=t2.sccid
        where t1.cid=#{id}


    !!(此sql语句放在course里面)!!
1,
    设置controller扫描路径的包名,spring mvc会自动的实例化该包下的controller。
    controller相当于struts中的action,用于处理数据,完成转发。    

 

1,
    springMVC

public class UserController {

    //第一种方式(优先选用)
    @RequestMapping("/checke.do")
    public String check(HttpSession session,User user)
    {
        System.out.println("提交成功!");
        String path="login.jsp";
        if("zhang".equals(user.getName()))
        {
            session.setAttribute("name", user.getName());
            path="welcome.jsp";
        }
        return "redirect:"+path;        
    }

    //两种方式实现跳转
    

@RequestMapping("/checke1.do")
    public ModelAndView checke1(User user,HttpSession session)
    {
        String path="login.jsp";
        if("zhang".equals(user.getName()))
        {
            session.setAttribute("name", user.getName());
            path="welcome.jsp";
        }
        ModelAndView mav =new ModelAndView(new RedirectView(path));
//        mav.addObject("name", user.getName());
        return mav;
    }
}

2,
    视图,简单说就是JSP文件!

    视图解析器的作用:通过视图名称,找到视图!


    视图解析器有很多,常用的只有以下这种

  

  <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value= ""/>
        <property name="suffix" value= ".jsp"/>
    </bean>

    redirect跳转的方式,视图解析器不起作用。

 

SSM整合参考文章(直接百度“SSM整合”)

http://my.oschina.net/sherwayne/blog/262616

1.需要哪些配置文件? (3个配置文件)
 
 web.xml,springmvc的配置文件,spring和mybatis整合的配置文件

 与ssh整合进行对比

1.web.xml中的配置

(1)spring的配置(加载spring的相关配置),其实就是spring和mybatis整合的配置文件

  第一步:加载listener

  

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener> 

  第二步:指定spring配置文件的位置和名字(默认的方式和非默认的方式)。(一般采用默认的)!!!!

  contextConfigLocation

  http://blog.csdn.net/zhangliao613/article/details/6289114

  总结:可以默认将applicationContext.xml放在web-inf目录下,也可以指定配置文件的名称和位置。

  从之前的项目中复制配置文件

   

 <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring/applicationContext.xml</param-value>
    </context-param> 

  省略以后,相当于

   

 <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/applicationContext.xml</param-value>
    </context-param> 


(2)spring mvc的配置

 (a)默认的方式:在web.xml中配置springmvc的servlet的名字xxx,默认的springmvc配置文件名为xx-servlet.xml

 (b)非默认的方式:直接在web.xml中配置springmvc的servlet的时候,指定springmvc配置文件的位置和名字。

<!-- Spring MVC servlet -->
  <servlet>
    <servlet-name>SpringMVC</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:spring-mvc.xml</param-value>
    </init-param>
  </servlet>
  <servlet-mapping>
    <servlet-name>SpringMVC</servlet-name>
    <url-pattern>*.do</url-pattern>
  </servlet-mapping>

============================================================================
ssh整合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"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:aop="http://www.springframework.org/schema/aop"
    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.1.xsd
          http://www.springframework.org/schema/tx
          http://www.springframework.org/schema/tx/spring-tx-4.1.xsd        
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop-4.1.xsd">
         <context:annotation-config/>
        <context:component-scan base-package="net.xinqushi.dao.impl,net.xinqushi.service.impl,net.xinqushi.aop"/>
        <aop:aspectj-autoproxy/>
        
        <context:property-placeholder location="classpath:dataSource.properties" />
        
        <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"  destroy-method="close">
            <!-- 初始化连接数量; -->
            <property name="initialSize" value="0" />
            <!-- 最大并发连接数     -->
            <property name="maxActive" value="20" />

            <!-- 最大空闲连接数 -->
            <property name="maxIdle" value="20" />
            <!-- 最小空闲连接数 -->
            <property name="minIdle" value="0" />
            <!-- 最大等待时长 -->
            <property name="maxWait" value="60000" />
            <!-- 超过时间限制是否回收 -->
            <property name="removeAbandoned" value="true" />
            <!-- 超过时间限制多长; -->
            <property name="removeAbandonedTimeout" value="180"/>     
              
              
            <!-- 数据源连接参数配置; -->
            <property name="username" value="${db.username}"/>
            <property name="url" value="${db.url}"/>
            <property name="password" value="${db.password}"/>
            <property name="driverClassName" value="${db.driverClassName}"/>
           
        </bean>     

        <!-- 配置SessionFactory -->
        <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
            <property name="dataSource" ref="dataSource"/>    
            <property name="packagesToScan" value="net.xinqushi.model"/>
            <property name="hibernateProperties">
                <props>
                    <prop key="hibernate.dialect">${hibernate.dialect}</prop>
                    <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
                    <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
                    <prop key="hibernate.format_sql">${hibernate.format_sql}</prop>
                </props>
            </property>
        </bean>        

      <bean id="hibernateTemplate" class="org.springframework.orm.hibernate4.HibernateTemplate">
               <property name="sessionFactory" ref="sessionFactory"></property>
      </bean>        
         <!-- 配置事务管理器 -->
        <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
            <property name="sessionFactory" ref="sessionFactory"/>
        </bean> 
        
        <!-- 定义切面 -->
        <aop:config>
            <aop:pointcut expression="execution(* net.xinqushi.service.impl.*.* (..))" id="txPointCut"/>
            <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"/>
        </aop:config>
          
        <!-- 声明式事务 -->
        <tx:advice id="txAdvice" transaction-manager="transactionManager">            
            <tx:attributes>
                    <tx:method name="add*" propagation="REQUIRED"/>
                    <tx:method name="get*" read-only="true" propagation="REQUIRED"/>
                    <tx:method name="check*" read-only="true" propagation="REQUIRED"/>
            </tx:attributes>        
        </tx:advice>           
</beans>

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值