package com.ssm.utils;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class Access {
    private Connection connection;

    private PreparedStatement ps;

    private ResultSet rs;

    public Connection getConn() {

        try {
            // 加载驱动
            Class.forName("com.mysql.jdbc.Driver");
            connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "root123");

        } catch (ClassNotFoundException e) {

            e.printStackTrace();// 打印异常输出

        } catch (SQLException e) {

            e.printStackTrace();

        }
        return connection;
    }

    /**
     * 关闭所打开的连接
     * 
     * @param con
     * @param ps
     * @param rs
     */
    public void colseCon(Connection con, PreparedStatement ps, ResultSet rs) {
        try {
            if (rs != null) {
                rs.close();
            }
            if (ps != null) {
                ps.close();
            }
            if (con != null) {
                con.close();
            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /**
     * 测试是否连接成功
     * 
     * @param args
     */
    public static void main(String[] args) {
        Access cd = new Access();
        if(cd.getConn()!=null){
            System.out.println("链接成功");
        }else{
            System.out.println("链接shibai");
        }
        //System.out.println("链接成功"+cd.getConn().hashCode());

    }
}

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class ConnectionTest {

    public static Connection getConnection() {
        // 定义连接
        Connection connection = null;
        
        try {
            // 加载驱动
            Class.forName("com.mysql.jdbc.Driver");
            connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "root");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return connection;
    }
    
    public static List<HashMap<String, Object>> getMysqlData() {
        Connection connection = null;
        // 预执行加载
        PreparedStatement preparedStatement = null;
        // 结果集
        ResultSet resultSet = null;
        
        connection = getConnection();
        
        String sqlString = "select * from user_t";
        
        List<HashMap<String, Object>> list = new ArrayList<HashMap<String,Object>>();
        
        try {
            preparedStatement = connection.prepareStatement(sqlString);
            resultSet = preparedStatement.executeQuery();
            HashMap<String, Object> map = null;
            while (resultSet.next()) {
                map = new HashMap<String, Object>();
                map.put("name", resultSet.getString("user_name"));
                list.add(map);
            }
         } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                if (resultSet != null) {
                    resultSet.close();
                }
                if (preparedStatement != null) {
                    preparedStatement.close();
                }
                if (connection != null) {
                    connection.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return list;
    }

    public static void main(String[] args) {
        List<HashMap<String, Object>> mysqlData = getMysqlData();
        for(HashMap<String, Object> map : mysqlData) {
            System.out.println(map.get("name"));
        }
    }

三大框架整合:
第一步:导入jar包
第二步:配置spring的配置文件

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:c="http://www.springframework.org/schema/c"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="
            http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
            http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
            http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
            http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">

        
        <!-- 包扫描 -->
        <context:component-scan base-package="cn.itcast.springmvc.service"/>
        
        
        <!-- 读取配置文件 -->
        <context:property-placeholder location="classpath:*.properties"/>
        <!-- 数据源 -->
        <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
            <property name="driverClassName" value="${jdbc.driver}"></property>
            <property name="url" value="${jdbc.url}"/>
            <property name="username" value="${jdbc.username}"></property>
            <property name="password" value="${jdbc.password}"></property>
        </bean>
        
        
        <!-- sqlSessionFactoryBean -->
        <bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
            <property name="configLocation" value="classpath:SqlMapConfig.xml"></property>
            <property name="dataSource" ref="dataSource"></property>
            <property name="mapperLocations" value="classpath:mappers/*.xml"></property>
        </bean>
        
        <!-- 配置我们所有的接口扫描包 -->
        <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
            <property name="basePackage" value="cn.itcast.springmvc.dao"></property>
        </bean>
        
       <!-- 事物管理 -->
        <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
            <property name="dataSource" ref="dataSource"></property>
        </bean>
        <!-- 开启事物 -->
        <tx:annotation-driven transaction-manager="transactionManager"/>
            
 </beans>  

第二步:配置mybatis的配置文件

第三步:配置springmvc的配置文件

    <!-- 包扫描路径一定要配置到controller层,不要放大包扫描路径 -->
    <context:component-scan base-package="cn.itcast.springmvc.controller"></context:component-scan>
    
    
    <!-- 配置我们的处理器映射器和处理器适配器 -->
    <mvc:annotation-driven/>
    
    
    <!-- 配置我们的资源视图解析器 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>
        
</beans>

第四步:配置web.xml

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

<!-- Bootstraps the root web application context before servlet initialization -->
<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>






<!-- The front controller of this Spring Web application, responsible for handling all application requests -->
<servlet>
    <servlet-name>springDispatcherServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:springmvc.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>

<!-- Map all requests to the DispatcherServlet for handling -->
<servlet-mapping>
    <servlet-name>springDispatcherServlet</servlet-name>
    <url-pattern>*.action</url-pattern>
</servlet-mapping>

SpirngMVC处理器上面五个内置的参数:
HttpServletRequest
HttpServletResponse
HttpSession
Model
ModelMap

SpringMVC当中的简单参数绑定
@RequestMapping("/itemEdit.action")
public ModelAndView skipToEdit(Integer id){
Items items = itemService.selectItemByPrimaryKey(id);
ModelAndView view = new ModelAndView();
view.setViewName("editItem");
view.addObject("item", items);
return view;
}
保证前端传递参数名称与方法上的名称一致即可

SpirngMC当中绑定pojo参数
@RequestMapping("/updateitem.action")
public String updateItem(Items items) throws UnsupportedEncodingException{
itemService.updateItem(items);
return "success";
}
保证前端页面传递参数与对象中的属性保持一致即可

SpirngMVC当中的自定义参数绑定
第一步:定义我们的dateConverters
public class DateConverter implements Converter<String, Date> {

@Override
public Date convert(String source) {
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    try {
        Date parse = format.parse(source);
        return parse;
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return null;
}

}

第二步:配置我们的转换器

             <!-- 配置我们的处理器映射器和处理器适配器 -->
    <mvc:annotation-driven conversion-service="conversionService"/>
    
  <!-- 配置我们的转换器 -->     
        <bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
            <property name="converters">
                <set>
                    <bean id="dateConverter" class="cn.itcast.springmvc.util.DateConverter"></bean>
                </set>
            </property>
        </bean>

课程回顾:
SpringMVC的介绍
SpringMVC的流程
SpringMVC的入门案例,配置四个东西,三个核心组件,一个servlet
SpringMVC的各个组件的详细介绍
三大框架的整合:
SpringMVC参数的绑定:简单数据类型绑定,对象数据类型绑定,包装数据类型绑定,自定义数据类型绑定

@Service
@Transactional
public class ItemsServiceImpl implements ItemsService {

@Autowired
private ItemsMapper itemsMapper;


@Override
public List<Items> getAllItems() {
    ItemsExample example = new ItemsExample();
    List<Items> selectByExampleWithBLOBs = itemsMapper.selectByExampleWithBLOBs(example);
    return selectByExampleWithBLOBs;
}


@Override
public Items selectItemByPrimaryKey(Integer id) {
    Items selectByPrimaryKey = itemsMapper.selectByPrimaryKey(id);
    return selectByPrimaryKey;
}


/**
 * 数据库的更新操作
 */
@Override
public void updateItem(Items items) {
    itemsMapper.updateByPrimaryKeySelective(items);
    
}

}

@Controller
public class ItemsController {

@Autowired
private ItemsService itemService;

/**
 * 实现页面数据的展示
 * @return
 */
@RequestMapping("/itemList.action")
public ModelAndView getItemsList(){
    List<Items> itemList = itemService.getAllItems();
    ModelAndView view = new ModelAndView();
    view.setViewName("itemList");
    view.addObject("itemList", itemList);
    return view;
}



/**
 * 实现页面数据的修改操作,通过request来获取参数
 */
/*@RequestMapping("/itemEdit.action")
public ModelAndView skipToEdit(HttpServletRequest request,HttpServletResponse response,HttpSession session){
    
    String parameter = request.getParameter("id");
    Integer id = new Integer(parameter);
    Items items = itemService.selectItemByPrimaryKey(id);
    System.out.println(parameter);
    ModelAndView view = new ModelAndView();
    view.setViewName("editItem");
    view.addObject("item", items);
    return view;
}
*/

/**
 * 简单参数绑定
 * @param id
 * @return
 */
/*@RequestMapping("/itemEdit.action")
public ModelAndView skipToEdit(Integer  id){
    Items items = itemService.selectItemByPrimaryKey(id);
    ModelAndView view = new ModelAndView();
    view.setViewName("editItem");
    view.addObject("item", items);
    return view;
}*/




/**
 * 通过model来实现我们的模型和视图
 * @param id
 * @param model
 * @return
 */
@RequestMapping("/itemEdit.action")
public String skipToEdit(@RequestParam(value="id",defaultValue="2",required=true)Integer ids,Model model){
    Items items = itemService.selectItemByPrimaryKey(ids);
    model.addAttribute("item", items);
    return "editItem";
}


/**
 * 修改操作,通过手动转码,实现乱码的解决
 * @throws UnsupportedEncodingException 
 */
/*@RequestMapping("/updateitem.action")
public String updateItem(Items items,HttpServletRequest request) throws UnsupportedEncodingException{
    
    String parameter = request.getParameter("name");
    String parameter2 = request.getParameter("detail");
    
    String name = new String(parameter.getBytes("iso-8859-1"), "utf-8");
    String detail = new String(parameter2.getBytes("iso-8859-1"), "utf-8");
    
    items.setName(name);
    items.setDetail(detail);
    itemService.updateItem(items);
    return "success";
}*/

/**
 * 修改操作,通过filter过滤器来实现我们乱码的解决
 * @throws UnsupportedEncodingException 
 */
@RequestMapping("/updateitem.action")
public String updateItem(Items items) throws UnsupportedEncodingException{
    itemService.updateItem(items);
    return "success";
}



/**
 * 查询操作
 */
@RequestMapping("/queryitem.action")
public ModelAndView queryItem(QueryVo vo){
    
    System.out.println(vo.getItems().getName());
    System.out.println(vo.getItems().getDetail());
    ModelAndView view = new ModelAndView();
    view.setViewName("success");
    
    
    return view;
}