Spring学习笔记--spring-springMVC-mybits搭建

  1. 基本概念
    1.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 )的容器框架。
    1.2. 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. 开发环境搭建
    2.1. eclipse EE
    2.2. Maven
  3. Maven Web项目创建
    可以参考一下我写的
    maven webapp 搭建
  4. 文件目录

Spring学习笔记--spring-springMVC-mybits搭建_第1张图片
5. maven
+ 使用框架都是较新的版本 :
+ Spring 4.0.2 RELEASE
+ Spring MVC 4.0.2 RELEASE
+ MyBatis 3.2.6
```XML


4.0.2.RELEASE

3.2.6

1.7.7
1.2.17

	
		
			junit
			junit
			3.8.1
			
			test
		
		
		
			org.springframework
			spring-core
			${spring.version}
		

		
			org.springframework
			spring-web
			${spring.version}
		
		
			org.springframework
			spring-oxm
			${spring.version}
		
		
			org.springframework
			spring-tx
			${spring.version}
		

		
			org.springframework
			spring-jdbc
			${spring.version}
		

		
			org.springframework
			spring-webmvc
			${spring.version}
		
		
			org.springframework
			spring-aop
			${spring.version}
		

		
			org.springframework
			spring-context-support
			${spring.version}
		

		
			org.springframework
			spring-test
			${spring.version}
		
		
		
			org.mybatis
			mybatis
			${mybatis.version}
		
		
		
			org.mybatis
			mybatis-spring
			1.2.2
		
		
		
			javax
			javaee-api
			7.0
		
		
		
			mysql
			mysql-connector-java
			5.1.30
		
		
		
			commons-dbcp
			commons-dbcp
			1.2.2
		
		
		
			jstl
			jstl
			1.2
		
		
		
		
			log4j
			log4j
			${log4j.version}
		
		
		
			com.alibaba
			fastjson
			1.1.41
		
		
			org.slf4j
			slf4j-api
			${slf4j.version}
		
		
			org.slf4j
			slf4j-log4j12
			${slf4j.version}
		
		
		
		
			org.codehaus.jackson
			jackson-mapper-asl
			1.9.13
		
		
		
			commons-fileupload
			commons-fileupload
			1.3.1
		
		
			commons-io
			commons-io
			2.4
		
		
			commons-codec
			commons-codec
			1.9
		
	
```
  1. spring与mybits整合

    jdbc.properties

    • (文件编码修改为 utf-8 )
    • 头一行是空行
    
      jdbc.driver=com.mysql.jdbc.Driver
      jdbc.url=jdbc:mysql://127.0.0.1:3306/db_test?useUnicode=true&characterEncoding=UTF-8
      jdbc.username=root
      jdbc.password=123456
      #定义初始连接数
      jdbc.initialSize=0
      #定义最大连接数
      jdbc.maxActive=20
      #定义最大空闲
      jdbc.maxIdle=20
      #定义最小空闲
      jdbc.minIdle=1
      #定义最长等待时间
      jdbc.maxWait=60000
    
    

    spring-mybatis.xml

      
      <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:context="http://www.springframework.org/schema/context"
      	xmlns:mvc="http://www.springframework.org/schema/mvc"
      	xsi:schemaLocation="http://www.springframework.org/schema/beans
      	http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
      	http://www.springframework.org/schema/context
      	http://www.springframework.org/schema/context/spring-context-3.1.xsd
      	http://www.springframework.org/schema/mvc
      	http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
      	
      	<context:component-scan base-package="cn.edu.zucc" />
        
      	
      	<context:property-placeholder location="classpath:/jdbc.properties" ignore-unresolvable="true"/>
    
      	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
      		destroy-method="close">
          
      		<property name="driverClassName" value="${jdbc.driver}"/>
      		<property name="url" value="${jdbc.url}" />
      		<property name="username" value="${jdbc.username}" />
      		<property name="password" value="${jdbc.password}" />
      		
      		<property name="initialSize" value="${jdbc.initialSize}">property>
      		
      		<property name="maxActive" value="${jdbc.maxActive}">property>
      		
      		<property name="maxIdle" value="${jdbc.maxIdle}">property>
      		
      		<property name="minIdle" value="${jdbc.minIdle}">property>
      		
      		<property name="maxWait" value="${jdbc.maxWait}">property>
      	bean>
    
      	
      	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
      		<property name="dataSource" ref="dataSource" />
      		
      		<property name="mapperLocations" value="classpath:cn/edu/zucc/dao/xml/*.xml">property>
          
      		
      	bean>
    
      	
      	<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
      		<property name="basePackage" value="cn.edu.zucc.dao" />
          
      		<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
      	bean>
    
      	
      	<bean id="transactionManager"
      		class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
      		<property name="dataSource" ref="dataSource" />
      	bean>
      beans>

    Log4j的配置

    • 这是我直接复制过来的,对于日志没怎么深入研究
      #定义LOG输出级别
      log4j.rootLogger=INFO,Console,File
      #定义日志输出目的地为控制台
      log4j.appender.Console=org.apache.log4j.ConsoleAppender
      log4j.appender.Console.Target=System.out
      #可以灵活地指定日志输出格式,下面一行是指定具体的格式
      log4j.appender.Console.layout = org.apache.log4j.PatternLayout
      log4j.appender.Console.layout.ConversionPattern=[%c] - %m%n
      #文件大小到达指定尺寸的时候产生一个新的文件
      log4j.appender.File = org.apache.log4j.RollingFileAppender
      #指定输出目录
      log4j.appender.File.File = logs/ssm.log
      #定义文件最大大小
      log4j.appender.File.MaxFileSize = 10MB
      # 输出所以日志,如果换成DEBUG表示输出DEBUG以上级别日志
      log4j.appender.File.Threshold = ALL
      log4j.appender.File.layout = org.apache.log4j.PatternLayout
      log4j.appender.File.layout.ConversionPattern =[%p] [%d{yyyy-MM-dd HH\:mm\:ss}][%c]%m%n

    Test

    • SQL创建表和数据
      DROP TABLE IF EXISTS `user_t`;
      CREATE TABLE `user_t` (
      `id`  int(11) NOT NULL AUTO_INCREMENT ,
      `user_name`  varchar(40) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL ,
      `password`  varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL ,
      `age`  int(4) NOT NULL ,
      PRIMARY KEY (`id`)
      )
      BEGIN;
      INSERT INTO `user_t` VALUES ('1', '测试', 'sfasgfaf', '24');
      COMMIT;
    • JavaBean 或者说 POJO
      package cn.edu.zucc.model;
    
      public class BeanUser {
      	private int id;
      	private String user_name;
      	private String password;
      	private int age;
      	public BeanUser() {
    
      	}
      	public BeanUser(int id,String user_name,String password,int age) {
      		this.id=id;
      		this.user_name=user_name;
      		this.password=password;
      		this.age=age;
      	}
      	/**
      	 * @return the id
      	 */
      	public int getId() {
      		return id;
      	}
      	/**
      	 * @param id the id to set
      	 */
      	public void setId(int id) {
      		this.id = id;
      	}
      	/**
      	 * @return the user_name
      	 */
      	public String getUser_name() {
      		return user_name;
      	}
      	/**
      	 * @param user_name the user_name to set
      	 */
      	public void setUser_name(String user_name) {
      		this.user_name = user_name;
      	}
      	/**
      	 * @return the password
      	 */
      	public String getPassword() {
      		return password;
      	}
      	/**
      	 * @param password the password to set
      	 */
      	public void setPassword(String password) {
      		this.password = password;
      	}
      	/**
      	 * @return the age
      	 */
      	public int getAge() {
      		return age;
      	}
      	/**
      	 * @param age the age to set
      	 */
      	public void setAge(int age) {
      		this.age = age;
      	}
    
      }
    • Dao层
      package cn.edu.zucc.dao;
      import java.util.List;
      import org.apache.ibatis.annotations.Param;
      import cn.edu.zucc.model.BeanUser;
    
      public interface UserDAO {
        public List<BeanUser> getAllUsers();
      	public BeanUser getUserById(@Param("id")int id);
      }
    • mapper.xml 文件
      
      
      
      <mapper namespace="cn.edu.zucc.dao.UserDAO">
      	
      	
      	<resultMap id="userResultMap" type="cn.edu.zucc.model.BeanUser">
      	   <id property="id" column="id" jdbcType="INTEGER"/>
      	   
      	   <result property="user_name" column="user_name" 	jdbcType="VARCHAR"/>
      	   <result property="password" 	column="password" 	jdbcType="VARCHAR"/>
      	   <result property="age" 		column="age" 		jdbcType="INTEGER"/>
      	resultMap>
        
       	
       	
      	<select id="getAllUsers" resultMap="userResultMap">
          	SELECT id,user_name,`password`,age FROM user_t;
       	select>
    
       	
          <select id="getUserById" resultType="cn.edu.zucc.model.BeanUser">
          	SELECT  id,user_name,`password`,age  from user_t  where id=#{id}
      	select>
      mapper>
    • service层接口
      package cn.edu.zucc.service;
    
      import java.util.List;
    
      import org.springframework.stereotype.Service;
    
      import cn.edu.zucc.model.BeanUser;
    
      public interface IUserService {
      	public List<BeanUser> getAllUsers();
      	public BeanUser getUserById(int userid);
      }
    • service层实现类
      package cn.edu.zucc.service.impl;
    
      import java.util.List;
    
      import javax.annotation.Resource;
    
      import org.springframework.context.ApplicationContext;
      import org.springframework.context.support.ClassPathXmlApplicationContext;
      import org.springframework.stereotype.Service;
    
      import cn.edu.zucc.dao.UserDAO;
      import cn.edu.zucc.model.BeanUser;
      import cn.edu.zucc.service.IUserService;
      @Service("UserServiceImpl")
      public class UserServiceImpl implements IUserService{
      	@Resource
          private UserDAO userdao;
    
      	@Override
      	public BeanUser getUserById(int userid) {
      		// TODO Auto-generated method stub
      		return userdao.getUserById(userid);
      	}
    
      	@Override
      	public List<BeanUser> getAllUsers() {
      		// TODO Auto-generated method stub
      		return userdao.getAllUsers();
      	}
      }
    测试类
      package test;
    
      import static org.junit.Assert.*;
      import java.util.List;
    
      import javax.annotation.Resource;
    
      import org.apache.log4j.Logger;
      import org.junit.BeforeClass;
      import org.junit.Test;
      import org.springframework.context.ApplicationContext;
      import org.springframework.context.support.ClassPathXmlApplicationContext;
    
      import com.alibaba.fastjson.JSON;
    
      import cn.edu.zucc.model.BeanUser;
      import cn.edu.zucc.service.IUserService;
      import cn.edu.zucc.service.impl.UserServiceImpl;
    
    
      public class TestUserService {
      	private static Logger logger = Logger.getLogger(TestUserService.class);
      	@Resource
      	private static IUserService userService = null;
    
      	@BeforeClass
      	public static void before() {
      		ApplicationContext ctx=new ClassPathXmlApplicationContext("spring-mybatis.xml");
      		userService=(IUserService)ctx.getBean("UserServiceImpl");//之前service实现类注解的那个
      	}
    
      	@Test
      	public void testGetUserById() {
      		BeanUser user = userService.getUserById(1);
      		logger.info(JSON.toJSONString(user));
      		assertNotNull(user);
      	}
    
      	@Test
      	public void testGetAllUsers() {
      		List<BeanUser> users = userService.getAllUsers();
      		logger.info(JSON.toJSONString(users));
      		assertNotNull(users);
      	}
    
      }
  2. 整合springMVC

    • spring-mvc.xml
      
      <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:context="http://www.springframework.org/schema/context"
      	xmlns:mvc="http://www.springframework.org/schema/mvc"
      	xsi:schemaLocation="http://www.springframework.org/schema/beans
      	http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
      	http://www.springframework.org/schema/context
      	http://www.springframework.org/schema/context/spring-context-3.1.xsd
      	http://www.springframework.org/schema/mvc
      	http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
      	
        
      	<context:component-scan base-package="cn.edu.zucc.controller"/>
      	
      	<bean id="mappingJacksonHttpMessageConverter"
      		class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
      		<property name="supportedMediaTypes">
      			<list>
      				<value>text/html;charset=UTF-8value>
      			list>
      		property>
      	bean>
      	
      	<bean
      		class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
      		<property name="messageConverters">
      			<list>
      				<ref bean="mappingJacksonHttpMessageConverter" />	
      			list>
      		property>
      	bean>
    
         
      	<bean id="jspViewResolve"
      		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
      		
      		<property name="prefix" value="/WEB-INF/jsp/" />
          
      		<property name="suffix" value=".jsp" />
      		<property name="order" value="0"/>
      	bean>
    
      	
      	<bean id="multipartResolver"
              class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
              
              <property name="defaultEncoding" value="utf-8" />
              
              <property name="maxUploadSize" value="10485760000" />
              
              <property name="maxInMemorySize" value="40960" />
          bean>
      beans>
    • web.xml
      
      <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>searchdisplay-name>
    
        
        <context-param>
      	<param-name>contextConfigLocationparam-name>
      	<param-value>classpath:spring-mybatis.xmlparam-value>
        context-param>
        
        <filter>
          <filter-name>encodingFilterfilter-name>
      	<filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
      	<async-supported>trueasync-supported>
      	<init-param>
      		<param-name>encodingparam-name>
      		<param-value>UTF-8param-value>
      	init-param>
        filter>
        <filter-mapping>
      	<filter-name>encodingFilterfilter-name>
      	<url-pattern>/*url-pattern>
        filter-mapping>
        
        <listener>
      	<listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
        listener>
        
        <listener>
      	<listener-class>org.springframework.web.util.IntrospectorCleanupListenerlistener-class>
        listener>
        
        <servlet>
      	<servlet-name>SpringMVCservlet-name>
      	<servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
      	<init-param>
      		<param-name>contextConfigLocationparam-name>
      		<param-value>classpath:spring-mvc.xmlparam-value>
      	init-param>
      	<load-on-startup>1load-on-startup>
      	<async-supported>trueasync-supported>
        servlet>
        <servlet-mapping>
      	<servlet-name>SpringMVCservlet-name>
      	
        
      	<url-pattern>/url-pattern>
        servlet-mapping>
        
        <servlet-mapping>
          <servlet-name>defaultservlet-name>
          <url-pattern>*.htmlurl-pattern>
      servlet-mapping>
        <welcome-file-list>
          <welcome-file>index.htmlwelcome-file>
        welcome-file-list>
      web-app>
    • jsp页面
      <%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
      
      
      
      
      Insert title here
      
      
      ${id}
    ${user.user_name}
    ${pwd}
    • controller
      package cn.edu.zucc.controller;
    
      import java.io.IOException;
    
      import javax.annotation.Resource;
      import javax.servlet.ServletException;
      import javax.servlet.http.HttpServletRequest;
      import javax.servlet.http.HttpServletResponse;
      import javax.servlet.http.HttpSession;
    
      import org.apache.log4j.Logger;
      import org.springframework.stereotype.Controller;
      import org.springframework.ui.Model;
      import org.springframework.web.bind.annotation.RequestMapping;
      import org.springframework.web.bind.annotation.RequestMethod;
      import org.springframework.web.servlet.ModelAndView;
    
      import com.alibaba.fastjson.JSON;
    
      import cn.edu.zucc.model.BeanUser;
      import cn.edu.zucc.service.IUserService;
      import test.TestUserService;
    
      @Controller
      @RequestMapping("/user")
      public class TestController{
      	private static Logger logger = Logger.getLogger(TestController.class);
      	@Resource
      	private IUserService userService;
    
      	@RequestMapping(value="/jsp",method = RequestMethod.GET)
      	public ModelAndView toIndex(HttpServletRequest request,HttpServletResponse response){
      		ModelAndView mav = new ModelAndView();
    
      		int userId = Integer.parseInt(request.getParameter("id"));
      		BeanUser user = this.userService.getUserById(userId);
      		logger.info(this.getClass().getName()+"\tid:\t"+userId);
      		logger.info(this.getClass().getName()+"\tuser:\t"+JSON.toJSONString(user));
      		mav.addObject("pwd", user.getPassword());
      		mav.addObject("user",user);
    
      		mav.setViewName("test");
      		//model.addAttribute("user", user);
      		return mav;
      	}
    
      	@RequestMapping(value="/html",method = RequestMethod.GET)
      	public ModelAndView testredirect(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException{
      		response.sendRedirect("/search/html/a.html");
      	    return null;
      	}
      }
  3. 部署网页

    • 访问 http://localhost:8080/search/user/html?id=1
    • 测试通过
    • 至此,SSM三大框架的整合就完成了,在此基础上可再添加其他功能。

你可能感兴趣的:(ssm,框架基础)