Spring和Mybatis 配置与使用

来源:互联网 发布:银泰证券股票交易软件 编辑:程序博客网 时间:2024/05/20 13:06

 目录

1.    Spring和MyBatis环境整合示例... 2

1.1.     前期准备... 2

1.1.1.      Jdk环境... 2

1.1.2.      数据库环境... 2

1.1.3.      编译器环境... 2

1.2.     创建数据库... 2

1.3.     创建基本目录结构... 2

1.4.     创建配置文件... 5

1.4.1.      Mybatis配置文件——mybatis-config.xml5

1.4.2.      Spring配置文件——ApplicationContext.xml5

1.5.     编写测试文件... 6

1.6.     执行测试文件... 8

2.    Junit9

2.1.     导入包... 9

2.2.     编写测试用例... 9

2.3.     注意... 9

3.    Spring. 10

3.1.     Spring背景... 10

3.1.1.      什么是spring. 10

3.1.2.      架构概述... 10

3.1.3.      框架优缺点... 11

3.2.     Bean—xml文件方式实现... 11

3.2.1.      Bean的作用域... 11

3.2.2.      初始化... 12

3.2.3.      销毁... 12

3.2.4.      配置全局默认初始化、销毁方法... 12

3.2.5.      Aware接口... 12

3.2.6.      Bean的自动装配... 12

3.2.7.      Resources. 13

3.3.     Bean—注解实现... 13

3.3.1.      Classpath扫描与组件管理... 13

3.3.2.      元注解... 13

3.3.3.      类的自动检测... 13

3.3.4.      使用过滤器进行自定义扫描... 13

3.3.5.      定义bean. 14

3.3.6.      作用域... 14

3.3.7.      Aotowired注解说明... 14

3.3.8.      基于java的容器注解... 14

3.3.9.      String对于JSR标准的支持... 15

4.    MyBatis. 16

4.1.     MyBatis简介... 16

4.2.     开发环境搭建... 16

4.2.1.      依赖项... 16

4.2.2.      环境配置... 16

4.3.     使用... 17

4.3.1.      执行查询... 17

4.3.2.      添加... 18

4.3.3.      修改... 18

4.3.4.      删除... 18

4.3.5.      接口的调用... 18

4.4.     mybatis generator19

4.4.1.      什么是mybatis generator19

4.4.2.      mybatis generator 生成的文件结构... 19

4.4.3.      mybatis generator的安装... 20

4.4.4.      使用mybatis generator进行查询... 21

4.4.5.      参考资料... 21

5.    Spring MVC. 22

5.1.     SpringMVC基础入门,创建一个HelloWorld程序... 22

5.2.     配置解析... 23

5.3.     SpringMVC常用注解... 24

5.4.     自动匹配参数... 25

5.5.     自动装箱... 25

5.6.     使用InitBinder来处理Date类型的参数... 26

5.7.     向前台传递参数... 26

5.8.     使用Ajax调用... 26

5.9.     在Controller中使用redirect方式处理请求... 27

5.10.       文件上传... 27

5.11.       使用@RequestParam注解指定参数的name. 28

5.12.       RESTFul风格的SringMVC. 28

5.13.       返回json格式的字符串... 30

5.14.       异常的处理... 30

5.15.       设置一个自定义拦截器... 31

5.16.       表单的验证(使用Hibernate-validate)及国际化... 32

5.17.       整合SpringIOC和SpringMVC. 34

5.18.       SpringMVC详细运行流程图... 37

5.19.       SpringMVC与struts2的区别... 37

5.20.       参考网址... 37

 

 

1.  Spring和MyBatis环境整合示例

1.1.     前期准备

1.1.1.     Jdk环境

本例jdk版本使用1.7版本

1.1.2.     数据库环境

本例中数据库使用mysql

1.1.3.     编译器环境

编译器使用Eclipse,neon版本。

1.2.     创建数据库

数据库中,新建数据库,命名为:springmybaitis;

然后再数据库中创建一个数据表:user;

User表中添加三种属性:id(int),username(char),password(char),设置id为主键.

1.3.     创建基本目录结构

基本目录结构分为4部分:

1、  Dao——主要用于连接数据库。

2、  Model——业务的模型。

3、  Test——用于编写测试文件。

4、  其他配置文件——包括mybatis和spring的配置文件。

文件结构如图:


model----User.java

 1 package com.springMyBatis.system.model;

 2

 3 public class User {

 4    private int id;

 5    privateString username;

 6    privateString password;

 7    publicUser(){}

 8    public int getId() {

 9        return id;

10     }

11    public void setId(int id) {

12        this.id = id;

13     }

14    public String getUsername() {

15        return username;

16     }

17    public void setUsername(String username) {

18        this.username = username;

19     }

20    public String getPassword() {

21        return password;

22     }

23    public void setPassword(String password) {

24        this.password = password;

25     }

26    public String toString(){

27        return "User[id="+id+" ,username="+username+" , password="+password+"]";

28     }

29    

30

31 }

dao------接口UserDao.java

 1 package com.springMyBatis.system.dao;

 2

 3 import com.springMyBatis.system.model.User;

 4

 5 public interface UserDao {

 6    public User getUser(Useruser);

 7    public void addUser(User user);

 8    public void updateUser(User user);

 9    public void deleteUser(int UserId);

10 }

dao-----UserDao.xml

 1 <?xml version="1.0" encoding="UTF-8"?>

 2 <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper3.0//EN"  

 3 "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> 

 4 <mappernamespace="com.springMyBatis.system.dao.UserDao"> 

 5 <select id="getUser"parameterType="com.springMyBatis.system.model.User" resultType="com.springMyBatis.system.model.User"> 

 6     SELECT * FROM user WHEREusername=#{username} AND password=#{password} 

 7 </select> 

 8 <insert id="addUser"parameterType="com.springMyBatis.system.model.User"flushCache="true"> 

 9    INSERT INTO user(id,username,password) VALUES (#{id},#{username},#{password}) 

10 </insert> 

11 <update id="updateUser"parameterType="com.springMyBatis.system.model.User"> 

12    UPDATE user SET password=#{password} WHERE id=#{id} 

13 </update> 

14 <delete id="deleteUser"parameterType="int"> 

15    DELETE FROM user WHERE id=#{id} 

16 </delete> 

17 </mapper> 

 

1.4.     创建配置文件

1.4.1.     Mybatis配置文件——mybatis-config.xml

1 <?xml version="1.0" encoding="UTF-8"?>
2 <!DOCTYPE configuration PUBLIC  
3     "-//mybatis.org//DTD Config 3.0//EN"  
4     "http://mybatis.org/dtd/mybatis-3-config.dtd">  
5 <configuration>  
6     <mappers>  
7         <mapper resource="com/springMyBatis/system/dao/UserDao.xml"/>  
8     </mappers>  
9 </configuration>  

1.4.2.     Spring配置文件——ApplicationContext.xml

1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans  
 3     xmlns="http://www.springframework.org/schema/beans"  
 4     xmlns:tx="http://www.springframework.org/schema/tx"  
 5     xmlns:p="http://www.springframework.org/schema/p"  
 6     xmlns:aop="http://www.springframework.org/schema/aop"   
 7     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
 8     xsi:schemaLocation="http://www.springframework.org/schema/beans   
 9     http://www.springframework.org/schema/beans/spring-beans-3.0.xsd   
10     http://www.springframework.org/schema/tx   
11     http://www.springframework.org/schema/tx/spring-tx-3.0.xsd   
12     http://www.springframework.org/schema/aop    
13     http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">  
14 <!-- 配置数据源-->  
15     <bean id="jdbcDataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">  
16     <property name="driverClassName">  
17         <value>org.gjt.mm.mysql.Driver</value>  
18     </property>  
19     <property name="url">  
20         <value>jdbc:mysql://localhost:3306/springmybaitis?useUnicode=true&amp;characterEncoding=UTF-8</value>  
21        <!--springmybaitis是我的数据库  -->
22     </property>  
23     <property name="username">  
24         <value>root</value>  
25     </property>  
26     <property name="password">  
27         <value>123456</value>  
28     </property>  
29 </bean>  
30 <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">  
31     <property name="dataSource" ref="jdbcDataSource" />  
32     <property name="configLocation" value="classpath:mybatis-config.xml"></property>  
33 </bean>  
34 <bean id="userDao" class="org.mybatis.spring.mapper.MapperFactoryBean">  
35     <property name="mapperInterface" value="com.springMyBatis.system.dao.UserDao"></property>  
36     <property name="sqlSessionFactory" ref="sqlSessionFactory"></property>  
37 </bean>  
38 </beans> 

1.5.     编写测试文件

测试文件添加一条数据:

1 package com.springMyBatis.system.test;
 2 
 3 import org.springframework.context.ApplicationContext;
 4 import org.springframework.context.support.ClassPathXmlApplicationContext;
 5 
 6 import com.springMyBatis.system.dao.UserDao;
 7 import com.springMyBatis.system.model.User;
 8 
 9 public class UserController {
10     
11     /**
12      * @param args
13      */
14     public static void main(String[] args) {
15         ApplicationContext ctx=null;
16         ctx=new ClassPathXmlApplicationContext("applicationContext.xml");
17         UserDao userDao=(UserDao) ctx.getBean("userDao");
18         User user=new User();
19         //添加两条数据
20         user.setId(1);
21         user.setUsername("Jessica");
22         user.setPassword("123");
23         userDao.addUser(user);
24         user.setId(2);
25         user.setUsername("Jessica2");
26         user.setPassword("123");
27         userDao.addUser(user);
28         System.out.println("添加成功");
29         //查询数据
30         user.setUsername("Jessica");
31         user.setPassword("123");
32         System.out.println(userDao.getUser(user).toString());
33         user.setUsername("Jessica2");
34         user.setPassword("123");
35         System.out.println(userDao.getUser(user).toString());
36         //修改数据
37         user.setId(2);
38         user.setPassword("802");
39         userDao.updateUser(user);
40         System.out.println("修改成功");
41         //删除数据
42         userDao.deleteUser(1);
43         System.out.println("删除成功");
44         
45     }
46 
47 }

1.6.     执行测试文件

测试结果:


2.  Junit

Junit可以用来进行单元测试。

2.1.     导入包

在集成开发环境中导入相应jar包:

junit-4.12.jar、

hamcrest-core-1.3.rc2.jar、

hamcrest-library-1.3.rc2.jar。

2.2.     编写测试用例

编写测试类,类上添加注释@Test。然后右键选中类,runas JUnit Test.

2.3.     注意

注意,类名不能为Test,否则会出错。


 

 

3.  Spring

3.1.     Spring背景

3.1.1.     什么是spring

spring是J2EE应用程序框架,是轻量级的IoC和AOP的容器框架,主要是针对javaBean的生命周期进行管理的轻量级容器,可以单独使用,也可以和Struts框架,Mybatis框架等组合使用。


3.1.2.     架构概述

 

1)IoC(Inversion of Control)控制反转,对象创建责任的反转,在spring中BeanFacotory是IoC容器的核心接口,负责实例化,定位,配置应用程序中的对象及建立这些对象间的依赖。XmlBeanFacotory实现BeanFactory接口,通过获取xml配置文件数据,组成应用对象及对象间的依赖关系。

spring中有三种注入方式,一种是set注入,一种是接口注入,另一种是构造方法注入。

 

2)AOP面向切面编程

aop就是纵向的编程,例如,业务1和业务2都需要一个共同的操作,与其往每个业务中都添加同样的代码,不如写一遍代码,让两个业务共同使用这段代码。

spring中面向切面变成的实现有两种方式,一种是动态代理,一种是CGLIB,动态代理必须要提供接口,而CGLIB实现是继承。

3.1.3.     框架优缺点

框架优点:

轻量级的容器框架没有侵入性

使用IoC容器更加容易组合对象直接间关系,面向接口编程,降低耦合

Aop可以更加容易的进行功能扩展,遵循ocp开发原则

创建对象默认是单例的,不需要再使用单例模式进行处理

3.2.     Bean—xml文件方式实现

Bean的配置项有以下:

常用:

Id——唯一标识

Class——绝对路径

其他:

Scope

Constructor arguments

Properties

Autowirting mode

Lazy-initialization mode

Initialization/destruction method

实现方法:

<beans>

    <beanid=" "class=" ">

        <propertyname=" "ref=" "/>

        <propertyname=" "value=" "></property>

  </bean>

</beans>

3.2.1.     Bean的作用域

Singleton:单例,一个bean容器中只存在一份。

Prototype:每次请求(每次使用)创建新的实例,destroy方式不生效。

Request:每次http请求创建一个实例且仅在当前request内有效。

Session:同上。

Global session:基于portlet的web中有效,在web中同session。

3.2.2.     初始化

实现InitiallizingBean接口,覆盖afterPropertiesSet方法;

@Override

Public voidafterPropertiesSet() throws Expection{}

或者配置init-method:

<beaninit-method=”init”>

Public void init(){}

3.2.3.     销毁

覆盖destroy方法

或者配置destroy-method

方式同3.2.2.

3.2.4.     配置全局默认初始化、销毁方法

<default-init-method=”init”default-destroy-method=”destroy”>

3.2.5.     Aware接口

Aware接口用于得到相关的资源

使用方法:implement   ***aware(调用接口)。

 

ApplicationContextAware——获取上下文。

BeanNameAware——获取bean名称。

其他。。。

3.2.6.     Bean的自动装配

<default-autowire=”___”>

no:不做任何操作。

byName:根据属性类型自动装配。

byType:根据类型自动装配。

constructor:构造器——查找构造器方法传入类型是否符合。

备注:如存在多个符合条件的则抛出异常。

3.2.7.     Resources

父类:ResourceLoader

输入参数前缀:

Classpath:chasspath:___

File : file:___

http : url :http://___

(none):依赖applicationContext

3.3.     Bean—注解实现

3.3.1.     Classpath扫描与组件管理

从spring3.0开始,可以使用java注解来定义bean。

@Component:通用注解。

@Repository:DAO类,持久层。

@Service:service类,服务层。

@Controller:Controller类,控制层(mvc)。

3.3.2.     元注解

注解的注解。

3.3.3.     类的自动检测

注解到类上或者方法上可以被自动检测。

<context:component-scan  base-package”org.example”(扫描包下的所有类)>

——可以扫描类的注解。

包含了<context:annotation-config>(不常用)

——只能处理类中的方法或成员变量的注解。

3.3.4.     使用过滤器进行自定义扫描

<beans>

    <context:component-scanbase-package=”org.example”>

             <context:include-filtertype=”regex” expression=”.*Stub.*Repository”/>

             <context:exclude-filtertype=”annotation” expression=org.___.___.___”/>

    </>

</>

3.3.5.     定义bean

可以指定ID:@Service(“___”)

不指定(默认)ID:首字母小写。

自定义命名策略:实现BeanNameGenerator接口,必须包含一个无参构造器。

<beans>

         <context:component-scanbase-package=”___” name-generator=”org.___.___”/>

</>

3.3.6.     作用域

@Scope(“___”)。可以自定义。

3.3.7.     Aotowired注解说明

@Required

适用于bean属性的setter方法。 要求必须在配置时被填充。

@Autowired

可以注解为常用的set方法,也可以注解在成员变量或者构造方法。如果找不到合适的bean会抛异常,解决方法:@Autowired(required=false)。每个类只能有一个构造器标记为required=true。必要属性建议使用required注解。

注意:@Autowired不能在自己的BeanPostProcessor或BeanFactoryPostProcessor类型应用这些注解。

@Order

         只针对数组,在对数组的注解中表示顺序。

@Qualifier

         按类型自动装配可能多个bean实例,可以使用@Qualifier缩小范围。也可以用于指定单独的构造器参数或方法参数。

         @Qualifier(“main”)

3.3.8.     基于java的容器注解

@Bean对应<bean …./>

支持自定义name,init-method;destroy-method;

@Configuration对应<beans></beans>

读取配置文件信息步骤:

@Configuration

@ImportResource(“文件路径”)

以上写在类上面

@Value(“$(___)”)——写在变量上面。

@Scope设置作用域。

3.3.9.     String对于JSR标准的支持

JSR250:支持@Resource,@PostConstructand @PreDestroy.

JSR330:需要引入javax.inject包。

@Inject等效于@AotoWare。

@Named:使用特定名称进行注入,与@Component等效。


 

 

4.  MyBatis

4.1.     MyBatis简介

MyBatis是支持普通SQL查询,存储过程和高级映射的优秀持久层框架。MyBatis消除了几乎所有的JDBC代码和参数的手工设置以及结果集的检索。MyBatis使用简单的XML或注解用于配置和原始映射,将接口和Java的POJOs(Plan Old Java Objects,普通的Java对象)映射成数据库中的记录.

orm工具的基本思想

无论是用过的hibernate,mybatis,你都可以法相他们有一个共同点:

1. 从配置文件(通常是XML配置文件中)得到 sessionfactory.

2. 由sessionfactory  产生 session

3. 在session 中完成对数据的增删改查和事务提交等.

4. 在用完之后关闭session 。

5. 在Java 对象和数据库之间有做mapping 的配置文件,也通常是xml 文件。

4.2.     开发环境搭建

4.2.1.     依赖项

Eclipse:j2ee 版

数据库:mysql

jdk

mybatis.jar包

4.2.2.     环境配置

4.2.2.1.  配置配置文件Configuration.xml:

< ?xmlversion="1.0" encoding="UTF-8" ?>

< !DOCTYPEconfiguration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"

"http://mybatis.org/dtd/mybatis-3-config.dtd">

<configuration>

    <environmentsdefault="development">

        <environmentid="development">

        <transactionManagertype="JDBC"/>

            <dataSourcetype="POOLED">

            <propertyname="driver" value="com.mysql.jdbc.Driver"/>

            <property name="url"value="jdbc:mysql://127.0.0.1:3306/mybatis" />

            <propertyname="username" value="root"/>

            <propertyname="password" value="password"/>

            </dataSource>

        </environment>

    </environments>

   

    <mappers>

        <mapper resource=" User.xml"/>

    </mappers>

</configuration>

4.2.2.2.  添加实体类和xml文件

例如数据库中表为user

则添加UserDAO.java和UserDAO.xml;

其中UserDAO.java是一个javabean,与数据库中的字段对应。而UserDAO.xml为UserDAO.java的配置文件,对每个映射字段进行配置。

.xml:

< mappernamespace="___.___.___.UserDAO">

    <select id="selectUserByID"parameterType="int" resultType="User">

        select * from `user` where id = #{id}

    </select>

< /mapper>

执行查询代码:

session.selectOne("___.___.___.selectUserByID",1)

4.3.     使用

4.3.1.     执行查询

返回List类型的对象

<selectid="selectUsers" parameterType="string"resultMap="resultListUser">

    select * from user where userName like#{userName}

</select>

 

<resultMap type="User"id="resultListUser">

     <id column="id"property="id" />

     <result column="userName"property="userName" />

     <result column="userAge"property="userAge" />

     <result column="userAddress"property="userAddress" />

</resultMap>

 

在 IUserOperation 接口中增加方法:publicList<User> selectUsers(String userName);

注意接口名必须与select id完全一致。

4.3.2.     添加

<insertid="addUser" parameterType="User"  useGeneratedKeys="true"keyProperty="id">

        insert intouser(userName,userAge,userAddress)

             values(#{userName},#{userAge},#{userAddress}) 

</insert>

对应接口:public int insertUser(UserBean user) throws Exception;

4.3.3.     修改

<updateid="updateUser" parameterType="User" >

    update user setuserName=#{userName},userAge=#{userAge},

userAddress=#{userAddress} where id=#{id}

</update>

对应接口:public int updateUser (UserBean user,intid) throws Exception;

4.3.4.     删除

<deleteid="deleteUser" parameterType="int">

    delete from user where id=#{id}

</delete>

对应接口:public int deleteUser(intid) throwsException;

4.3.5.     接口的调用

在实际应用中,需要调用相应的接口来进行数据库的操作。

首先创建DBTools.Java,用来产生会话。

publicclassDBTools {

     public staticSqlSessionFactory sessionFactory;

     static{

        try {

                //使用MyBatis提供的Resources类加载mybatis的配置文件

           Reader reader = Resources.getResourceAsReader("mybatis.cfg.xml");

              //构建sqlSession的工厂

              sessionFactory =newSqlSessionFactoryBuilder().build(reader);

          } catch (Exceptione) {

              e.printStackTrace();

          }

        }

        //创建能执行映射文件中sqlsqlSession

        public static SqlSession getSession(){

            returnsessionFactory.openSession();

        }

}

 

然后是一个示例:

@Test

    public void insertUser() {

        SqlSession session = DBTools.getSession();//创建会话

        UserMapper mapper = session.getMapper(UserMapper.class);

        UserBean user = new UserBean(2, "username","password");

        try {

            mapper.insertUser(user);//执行查询

            System.out.println(user.toString());

            session.commit();//提交会话——重要

        } catch (Exceptione) {

            e.printStackTrace();

            session.rollback();

        }

}

4.4.     mybatis generator

4.4.1.     什么是mybatis generator

虽然说有了 mybatis框架,但是学习 mybatis 也需要学习成本,尤其是配置它需要的 XML 文件,那也是相当繁琐,而且配置中出现错误,不容易定位。当出现莫名其妙的错误或者有大批量需要生成的对象时,时常会有种生无可恋的感觉在脑中徘徊。故此, mybatis generator 应运而生了。

它只需要简单配置,即可完成大量的表到 mybatis Java 对象的生成工作,不仅速度快,而且不会出错,可让开发人员真正的专注于业务逻辑的开发。

官方提供的 mybatisgenerator 功能比较简单,对于稍微复杂但是开发中必然用到的分页功能、批量插入功能等没有实现,但已经有成熟的插件功能支持。

4.4.2.     mybatis generator 生成的文件结构

生成的文件包含三类:

1.      Model 实体文件,一个数据库表生成一个 Model 实体;

2.      ModelExample 文件,此文件和实体文件在同一目录下,主要用于查询条件构造;

3.      Mapper 接口文件,数据数操作方法都在此接口中定义;

4.      Mapper XML 配置文件;

4.4.3.     mybatis generator的安装

mybatisgenerator在eclipse中,可以使用help->install new soft ware 安装。

安装后会自动生成xml文件,填入相应的内容,右键运行就可以自动生成表结构。

配置文件示例:

1.  <?xml version="1.0" encoding="UTF-8"?>  

2. <!DOCTYPE generatorConfiguration  

3.    PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"  

4.   "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">  

5.    

6. <generatorConfiguration>  

7.    

8.   <!--MySQL连接驱动-->  

9.    <classPathEntry location="mysql-connector-java-5.1.9.jar" />  

10.    

11.   <!--数据库链接URL,用户名、密码 -->  

12.  <context id="MySQL" targetRuntime="MyBatis3">  

13.     <commentGenerator>    

14.            <property name="suppressDate" value="true"/>    

15.             <!-- 是否去除自动生成的注释 true:是  false: -->    

16.            <property name="suppressAllComments" value="true"/>    

17.     </commentGenerator>   

18.    <jdbcConnection driverClass="com.mysql.jdbc.Driver"  

19.         connectionURL="jdbc:mysql://127.0.0.1/test"  

20.        userId="root"  

21.         password="123456">  

22.    </jdbcConnection>  

23.   

24.    <!--是否启用java.math.BigDecimal-->  

25.     <javaTypeResolver >  

26.      <property name="forceBigDecimals" value="false" />  

27.     </javaTypeResolver>  

28.  

29.     <javaModelGenerator targetPackage="test.model" targetProject="src">  

30.      <property name="enableSubPackages" value="true" />  

31.       <property name="trimStrings" value="true" />  

32.    </javaModelGenerator>  

33.   

34.    <sqlMapGenerator targetPackage="test.xml"  targetProject="src">  

35.       <property name="enableSubPackages" value="true" />  

36.    </sqlMapGenerator>  

37.   

38.    <javaClientGenerator type="XMLMAPPER" targetPackage="test.dao"  targetProject="src">  

39.       <property name="enableSubPackages" value="true" />  

40.    </javaClientGenerator>  

41.   

42.    <table tableName="salary" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false">  

43.     </table>  

44.    <table tableName="persons" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false">  

45.     </table>  

46.    <table tableName="orders" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false">  

47.     </table>  

48.  </context>  

49. </generatorConfiguration>  

4.4.4.     使用mybatis generator进行查询

使用generator进行查询和在mybatis中查询基本一致,唯一不同在于generator可以生成example文件,方便查询。

Example使用方法:

UserExample example =new UserExample();

example.createCriteria()

.andIdBetween(0, 3)

.andUsernameIsNotNull();//可以添加其他检索条件

得到结果:mapper.selectByExample(example);

4.4.5.     参考资料

http://generator.sturgeon.mopaas.com/index.html


 

5.  Spring MVC

5.1.     SpringMVC基础入门,创建一个HelloWorld程序

1.首先,导入SpringMVC需要的jar包。

  2.添加Web.xml配置文件中关于SpringMVC的配置

<!--configurethe setting of springmvcDispatcherServlet and configure the mapping-->

<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:springmvc-servlet.xml</param-value>

      </init-param>

      <!-- <load-on-startup>1</load-on-startup>-->

</servlet>

 

<servlet-mapping>

   <servlet-name>springmvc</servlet-name>

    <url-pattern>/</url-pattern>

</servlet-mapping>

  3.在src下添加springmvc-servlet.xml配置文件

<?xmlversion="1.0" encoding="UTF-8"?>

<beansxmlns="http://www.springframework.org/schema/beans"

   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

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

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

    xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsd

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

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

 

    <!-- scan the package and the subpackage -->

    <context:component-scanbase-package="test.SpringMVC"/>

 

    <!-- don't handle the static resource-->

    <mvc:default-servlet-handler />

 

    <!-- if you use annotation you mustconfigure following setting -->

    <mvc:annotation-driven />

    

    <!-- configure theInternalResourceViewResolver -->

    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"

           id="internalResourceViewResolver">

        <!-- 前缀 -->

        <property name="prefix"value="/WEB-INF/jsp/" />

        <!-- 后缀 -->

        <property name="suffix"value=".jsp" />

    </bean>

</beans>

  4.在WEB-INF文件夹下创建名为jsp的文件夹,用来存放jsp视图。创建一个hello.jsp,在body中添加“HelloWorld”。

  5.建立包及Controller,如下所示

  6.编写Controller代码

@Controller

@RequestMapping("/mvc")

public classmvcController {

 

    @RequestMapping("/hello")

    public String hello(){       

        return "hello";

    }

}

  7.启动服务器,键入http://localhost:8080/项目名/mvc/hello

5.2.     配置解析

  1.Dispatcherservlet

  DispatcherServlet是前置控制器,配置在web.xml文件中的。拦截匹配的请求,Servlet拦截匹配规则要自已定义,把拦截下来的请求,依据相应的规则分发到目标Controller来处理,是配置spring MVC的第一步。

  2.InternalResourceViewResolver

 

  视图名称解析器

 

  3.以上出现的注解

 

  @Controller 负责注册一个bean 到spring 上下文中

 

  @RequestMapping 注解为控制器指定可以处理哪些 URL 请求

 

5.3.      SpringMVC常用注解

 

  @Controller

 

  负责注册一个bean 到spring 上下文中

 

  @RequestMapping

 

  注解为控制器指定可以处理哪些 URL 请求

 

  @RequestBody

 

  该注解用于读取Request请求的body部分数据,使用系统默认配置的HttpMessageConverter进行解析,然后把相应的数据绑定到要返回的对象上 ,再把HttpMessageConverter返回的对象数据绑定到 controller中方法的参数上

 

  @ResponseBody

 

  该注解用于将Controller的方法返回的对象,通过适当的HttpMessageConverter转换为指定格式后,写入到Response对象的body数据区

 

  @ModelAttribute    

 

  在方法定义上使用@ModelAttribute 注解:Spring MVC 在调用目标处理方法前,会先逐个调用在方法级上标注了@ModelAttribute 的方法

 

  在方法的入参前使用@ModelAttribute 注解:可以从隐含对象中获取隐含的模型数据中获取对象,再将请求参数–绑定到对象中,再传入入参将方法入参对象添加到模型中

 

  @RequestParam 

 

  在处理方法入参处使用@RequestParam 可以把请求参数传递给请求方法

 

  @PathVariable

 

  绑定 URL 占位符到入参

 

  @ExceptionHandler

 

  注解到方法上,出现异常时会执行该方法

 

  @ControllerAdvice

 

  使一个Contoller成为全局的异常处理类,类中用@ExceptionHandler方法注解的方法可以处理所有Controller发生的异常

 

5.4.     自动匹配参数

//matchautomatically

@RequestMapping("/person")

public StringtoPerson(String name,double age){

    System.out.println(name+" "+age);

    return "hello";

}

5.5.         自动装箱

 

  1.编写一个Person实体类

packagetest.SpringMVC.model;

 

public classPerson {

    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;

    }

    private String name;

    private int age;

    

}

  2.在Controller里编写方法

//boxingautomatically

@RequestMapping("/person1")

public StringtoPerson(Person p){

    System.out.println(p.getName()+""+p.getAge());

    return "hello";

}

5.6.     使用InitBinder来处理Date类型的参数

//the parameterwas converted in initBinder

@RequestMapping("/date")

public Stringdate(Date date){

    System.out.println(date);

    return "hello";

}

   

//At the time ofinitialization,convert the type "String" to type "date"

@InitBinder

public voidinitBinder(ServletRequestDataBinder binder){

    binder.registerCustomEditor(Date.class, newCustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"),

            true));

}

5.7.     向前台传递参数

//pass theparameters to front-end

@RequestMapping("/show")

public StringshowPerson(Map<String,Object> map){

    Person p =new Person();

    map.put("p", p);

    p.setAge(20);

    p.setName("jayjay");

    return "show";

}

  前台可在Request域中取到"p"

 

5.8.     使用Ajax调用

//pass theparameters to front-end using ajax

@RequestMapping("/getPerson")

public voidgetPerson(String name,PrintWriter pw){

    pw.write("hello,"+name);        

}

@RequestMapping("/name")

public StringsayHello(){

    return "name";

}

  前台用下面的Jquery代码调用

$(function(){

    $("#btn").click(function(){

      $.post("mvc/getPerson",{name:$("#name").val()},function(data){

            alert(data);

        });

    });

});

5.9.     在Controller中使用redirect方式处理请求

//redirect

@RequestMapping("/redirect")

public Stringredirect(){

    return "redirect:hello";

}

5.10.  文件上传

  1.需要导入两个jar包

  2.在SpringMVC配置文件中加入

<!-- uploadsettings -->

<beanid="multipartResolver"  class="org.springframework.web.multipart.commons.CommonsMultipartResolver">

    <property name="maxUploadSize"value="102400000"></property>

</bean>

  3.方法代码

@RequestMapping(value="/upload",method=RequestMethod.POST)

public Stringupload(HttpServletRequest req) throws Exception{

    MultipartHttpServletRequest mreq =(MultipartHttpServletRequest)req;

    MultipartFile file =mreq.getFile("file");

    String fileName =file.getOriginalFilename();

    SimpleDateFormat sdf = newSimpleDateFormat("yyyyMMddHHmmss");        

    FileOutputStream fos = newFileOutputStream(req.getSession().getServletContext().getRealPath("/")+

            "upload/"+sdf.format(newDate())+fileName.substring(fileName.lastIndexOf('.')));

    fos.write(file.getBytes());

    fos.flush();

    fos.close();

    

    return "hello";

}

  4.前台form表单

<formaction="mvc/upload" method="post"enctype="multipart/form-data">

    <input type="file"name="file"><br>

    <input type="submit"value="submit">

</form>

5.11.  使用@RequestParam注解指定参数的name

@Controller

@RequestMapping("/test")

public classmvcController1 {

    @RequestMapping(value="/param")

    public StringtestRequestParam(@RequestParam(value="id") Integer id,

           @RequestParam(value="name")String name){

        System.out.println(id+""+name);

        return "/hello";

    }   

}

5.12.  RESTFul风格的SringMVC

 

  1.RestController

@Controller

@RequestMapping("/rest")

public classRestController {

   @RequestMapping(value="/user/{id}",method=RequestMethod.GET)

    public Stringget(@PathVariable("id") Integer id){

        System.out.println("get"+id);

        return "/hello";

    }

    

   @RequestMapping(value="/user/{id}",method=RequestMethod.POST)

    public Stringpost(@PathVariable("id") Integer id){

       System.out.println("post"+id);

        return "/hello";

    }

    

   @RequestMapping(value="/user/{id}",method=RequestMethod.PUT)

    public Stringput(@PathVariable("id") Integer id){

        System.out.println("put"+id);

        return "/hello";

    }

    

    @RequestMapping(value="/user/{id}",method=RequestMethod.DELETE)

    public Stringdelete(@PathVariable("id") Integer id){

       System.out.println("delete"+id);

        return "/hello";

    }

    

}

  2.form表单发送put和delete请求

 

  在web.xml中配置

<!--configure the HiddenHttpMethodFilter,convert the post method to put or delete-->

<filter>

   <filter-name>HiddenHttpMethodFilter</filter-name>

   <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>

</filter>

<filter-mapping>

    <filter-name>HiddenHttpMethodFilter</filter-name>

    <url-pattern>/*</url-pattern>

</filter-mapping>

  在前台可以用以下代码产生请求

<formaction="rest/user/1" method="post">

    <input type="hidden"name="_method" value="PUT">

    <input type="submit"value="put">

</form>

 

<form action="rest/user/1"method="post">

    <input type="submit"value="post">

</form>

 

<formaction="rest/user/1" method="get">

    <input type="submit"value="get">

</form>

 

<formaction="rest/user/1" method="post">

    <input type="hidden"name="_method" value="DELETE">

    <input type="submit"value="delete">

</form>

5.13.  返回json格式的字符串

 

  1.导入以下jar包

  2.方法代码

@Controller

@RequestMapping("/json")

public classjsonController {

    

    @ResponseBody

    @RequestMapping("/user")

    public User get(){

        User u = new User();

        u.setId(1);

        u.setName("jayjay");

        u.setBirth(new Date());

        return u;

    }

}

5.14.  异常的处理

 

  1.处理局部异常(Controller内)

@ExceptionHandler

publicModelAndView exceptionHandler(Exception ex){

    ModelAndView mv = newModelAndView("error");

    mv.addObject("exception", ex);

    System.out.println("intestExceptionHandler");

    return mv;

}

   

@RequestMapping("/error")

public Stringerror(){

    int i = 5/0;

    return "hello";

}

  2.处理全局异常(所有Controller)

 

@ControllerAdvice

public classtestControllerAdvice {

    @ExceptionHandler

    public ModelAndViewexceptionHandler(Exception ex){

        ModelAndView mv = newModelAndView("error");

        mv.addObject("exception",ex);

        System.out.println("in testControllerAdvice");

        return mv;

    }

}

  3.另一种处理全局异常的方法

 

  在SpringMVC配置文件中配置

<!--configure SimpleMappingExceptionResolver -->

<beanclass="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">

    <property name="exceptionMappings">

        <props>

            <propkey="java.lang.ArithmeticException">error</prop>

        </props>

    </property>

</bean>

  error是出错页面

 

5.15.  设置一个自定义拦截器

 

  1.创建一个MyInterceptor类,并实现HandlerInterceptor接口

public classMyInterceptor implements HandlerInterceptor {

 

    @Override

    public voidafterCompletion(HttpServletRequest arg0,

            HttpServletResponse arg1, Objectarg2, Exception arg3)

            throws Exception {

        System.out.println("afterCompletion");

    }

 

    @Override

    public void postHandle(HttpServletRequestarg0, HttpServletResponse arg1,

            Object arg2, ModelAndView arg3)throws Exception {

       System.out.println("postHandle");

    }

 

    @Override

    public boolean preHandle(HttpServletRequestarg0, HttpServletResponse arg1,

            Object arg2) throws Exception {

       System.out.println("preHandle");

        return true;

    }

 

}

  2.在SpringMVC的配置文件中配置

<!--interceptor setting -->

<mvc:interceptors>

    <mvc:interceptor>

        <mvc:mappingpath="/mvc/**"/>

        <beanclass="test.SpringMVC.Interceptor.MyInterceptor"></bean>

    </mvc:interceptor>       

</mvc:interceptors>

  3.拦截器执行顺序

 

 

 

5.16.  表单的验证(使用Hibernate-validate)及国际化

 

  1.导入Hibernate-validate需要的jar包

(未选中不用导入)

  2.编写实体类User并加上验证注解

public classUser {

    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 Date getBirth() {

        return birth;

    }

    public void setBirth(Date birth) {

        this.birth = birth;

    }

    @Override

    public String toString() {

        return "User [id=" + id +", name=" + name + ", birth=" + birth + "]";

    }   

    private int id;

    @NotEmpty

    private String name;

 

    @Past

   @DateTimeFormat(pattern="yyyy-MM-dd")

    private Date birth;

}

  ps:@Past表示时间必须是一个过去值

 

  3.在jsp中使用SpringMVC的form表单

<form:formaction="form/add" method="post"modelAttribute="user">

    id:<form:inputpath="id"/><form:errors path="id"/><br>

    name:<form:inputpath="name"/><form:errors path="name"/><br>

    birth:<form:inputpath="birth"/><form:errors path="birth"/>

    <input type="submit"value="submit">

</form:form>

  ps:path对应name

 

  4.Controller中代码

@Controller

@RequestMapping("/form")

public classformController {

   @RequestMapping(value="/add",method=RequestMethod.POST)   

    public String add(@Valid Useru,BindingResult br){

        if(br.getErrorCount()>0){           

            return "addUser";

        }

        return "showUser";

    }

    

   @RequestMapping(value="/add",method=RequestMethod.GET)

    public String add(Map<String,Object>map){

        map.put("user",new User());

        return "addUser";

    }

}

  ps:

 

  1.因为jsp中使用了modelAttribute属性,所以必须在request域中有一个"user".

 

  2.@Valid 表示按照在实体上标记的注解验证参数

 

  3.返回到原页面错误信息回回显,表单也会回显

 

  5.错误信息自定义

 

  在src目录下添加locale.properties

 

NotEmpty.user.name=namecan't not be empty

Past.user.birth=birthshould be a past value

DateTimeFormat.user.birth=theformat of input is wrong

typeMismatch.user.birth=theformat of input is wrong

typeMismatch.user.id=theformat of input is wrong

  在SpringMVC配置文件中配置

<!--configure the locale resource -->

<beanid="messageSource"class="org.springframework.context.support.ResourceBundleMessageSource">

    <property name="basename"value="locale"></property>

</bean>

  6.国际化显示

 

  在src下添加locale_zh_CN.properties

 

username=账号

password=密码

  locale.properties中添加

 

username=username

password=password

  创建一个locale.jsp

<body>

  <fmt:messagekey="username"></fmt:message>

  <fmt:messagekey="password"></fmt:message>

</body>

  在SpringMVC中配置

<!-- make thejsp page can be visited -->

<mvc:view-controllerpath="/locale" view-name="locale"/>

  让locale.jsp在WEB-INF下也能直接访问

 

  最后,访问locale.jsp,切换浏览器语言,能看到账号和密码的语言也切换了

 

5.17.  整合SpringIOC和SpringMVC

  1.创建一个test.SpringMVC.integrate的包用来演示整合,并创建各类

 

 

 

  2.User实体类

public classUser {

    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 Date getBirth() {

        return birth;

    }

    public void setBirth(Date birth) {

        this.birth = birth;

    }

    @Override

    public String toString() {

        return "User [id=" + id +", name=" + name + ", birth=" + birth + "]";

    }   

    private int id;

    @NotEmpty

    private String name;

 

    @Past

   @DateTimeFormat(pattern="yyyy-MM-dd")

    private Date birth;

}

  3.UserService类

@Component

public classUserService {

    public UserService(){

        System.out.println("UserServiceConstructor...\n\n\n\n\n\n");

    }

    

    public void save(){

        System.out.println("save");

    }

}

  4.UserController

@Controller

@RequestMapping("/integrate")

public classUserController {

    @Autowired

    private UserService userService;

    

    @RequestMapping("/user")

    public String saveUser(@RequestBody@ModelAttribute User u){

        System.out.println(u);

        userService.save();

        return "hello";

    }

}

  5.Spring配置文件

 

  在src目录下创建SpringIOC的配置文件applicationContext.xml

<?xmlversion="1.0" encoding="UTF-8"?>

<beansxmlns="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.xsd

       http://www.springframework.org/schema/util

       http://www.springframework.org/schema/util/spring-util-4.0.xsd

       http://www.springframework.org/schema/context

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

        "

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

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

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

        >

    <context:component-scanbase-package="test.SpringMVC.integrate">

        <context:exclude-filtertype="annotation"

           expression="org.springframework.stereotype.Controller"/>

        <context:exclude-filter type="annotation"

           expression="org.springframework.web.bind.annotation.ControllerAdvice"/>       

    </context:component-scan>

    

</beans>

  在Web.xml中添加配置

<!--configure the springIOC -->

<listener>

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

</listener>

<context-param> 

 <param-name>contextConfigLocation</param-name> 

 <param-value>classpath:applicationContext.xml</param-value>

</context-param>

  6.在SpringMVC中进行一些配置,防止SpringMVC和SpringIOC对同一个对象的管理重合

<!-- scan thepackage and the sub package -->

    <context:component-scanbase-package="test.SpringMVC.integrate">

        <context:include-filtertype="annotation"

           expression="org.springframework.stereotype.Controller"/>

        <context:include-filtertype="annotation"

           expression="org.springframework.web.bind.annotation.ControllerAdvice"/>

    </context:component-scan>

5.18.  SpringMVC详细运行流程图

 

 

 

5.19.  SpringMVC与struts2的区别

 

  1、springmvc基于方法开发的,struts2基于类开发的。springmvc将url和controller里的方法映射。映射成功后springmvc生成一个Handler对象,对象中只包括了一个method。方法执行结束,形参数据销毁。springmvc的controller开发类似web service开发。

 

  2、springmvc可以进行单例开发,并且建议使用单例开发,struts2通过类的成员变量接收参数,无法使用单例,只能使用多例。

 

3、经过实际测试,struts2速度慢,在于使用struts标签,如果使用struts建议使用jstl。

5.20.  参考网址

http://www.admin10000.com/document/6436.html

 

阅读全文
0 0
原创粉丝点击