springMVC+ibatis数据持久化入门级学习例子

1.web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4" 
    xmlns="http://java.sun.com/xml/ns/j2ee" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 
    http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
    
    <servlet>
        <servlet-name>spring-mvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:applicationContext.xml</param-value>
        </init-param>
    </servlet>
    
    <servlet-mapping>
        <servlet-name>spring-mvc</servlet-name>
        <url-pattern>*.do</url-pattern>
    </servlet-mapping>
</web-app>

2.application.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">

<beans>

    <bean id="handler" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
        <property name="mappings">
            <props>
                <prop key="test.do">testControllerAction</prop>
            </props>
        </property>
    </bean>
    
    <bean id="testControllerAction" class="org.ue.action.TestControllerAction">
        <property name="pageSize">
            <value>20</value>
        </property>
        <property name="successView">
            <value>list.jsp</value>
        </property>
    </bean>
    
    <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="location">
            <value>classpath:db-properties.properties</value>
        </property>
    </bean>
    <bean id="ds" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName">
            <value>${jdbc.driverClassName}</value>
        </property>
        <property name="url">
            <value>${jdbc.url}</value>
        </property>
        <property name="username">
            <value>${jdbc.username}</value>
        </property>
        <property name="password">
            <value>${jdbc.password}</value>
        </property>
    </bean>
    
    <bean id="sqlMapClient" class="org.springframework.orm.ibatis.SqlMapClientFactoryBean">
        <property name="configLocation">
            <value>classpath:sqlmap-config.xml</value>
        </property>
    </bean>
    
    <bean id="studentDao" class="org.ue.dao.impl.StudentDaoImpl">
        <property name="dataSource" ref="ds"></property>
        <property name="sqlMapClient" ref="sqlMapClient"></property>
    </bean>
    
</beans>

3.db-properties.properties

jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&amp;characterEncoding=utf-8
jdbc.username=test
jdbc.password=test

4.sqlmap-config.xml

<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE sqlMapConfig PUBLIC "-//iBATIS.com//DTD SQL Map Config 2.0//EN" "http://www.ibatis.com/dtd/sql-map-config-2.dtd">
<sqlMapConfig>
    <settings cacheModelsEnabled="true" enhancementEnabled="true"
        lazyLoadingEnabled="true" errorTracingEnabled="true" maxRequests="32"
        maxSessions="10" maxTransactions="5" useStatementNamespaces="false" />

    <!--
        Identify all SQL Map XML files to be loaded by this SQL map. 
        Notice the paths are relative to the classpath.
    -->
    <sqlMap resource="sqlmap-test.xml" />

</sqlMapConfig>

5.sqlmap-test.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE sqlMap
    PUBLIC "-//iBATIS.com//DTD SQL Map 2.0//EN"
    "http://www.ibatis.com/dtd/sql-map-2.dtd">

<sqlMap namespace="ts">
    <typeAlias alias="stu" type="org.ue.po.Student" />
    
    <select id="listStu" resultClass="stu">
        select id, name from tbl_student
    </select>
</sqlMap>

6.Action

public class TestControllerAction implements Controller {
    
    private String successView;
    private String pageSize;
    /* (non-Javadoc)
     * @see org.springframework.web.servlet.mvc.Controller#handleRequest(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
     */
    public ModelAndView handleRequest(HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        // TODO Auto-generated method stub
        System.out.println("---pageSize---" + pageSize);
        request.setAttribute("pageSize", pageSize);
        return new ModelAndView(successView);
    }
    
    public String getPageSize() {
        return pageSize;
    }
    public void setPageSize(String pageSize) {
        this.pageSize = pageSize;
    }
    public String getSuccessView() {
        return successView;
    }
    public void setSuccessView(String successView) {
        this.successView = successView;
    }
    
    
}

7.dao

public interface StudentDao {
    public List getStudent() throws Exception;
}
public class StudentDaoImpl extends SqlMapClientDaoSupport implements StudentDao {

    /* (non-Javadoc)
     * @see org.ue.dao.StudentDao#getStudent()
     */
    public List getStudent() throws Exception{
        // TODO Auto-generated method stub
        return getSqlMapClientTemplate().queryForList("listStu",null);
    }

}

8.po

public class Student {
    private int id;
    private String name;
    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;
    }
    
}

9.list.jsp

<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'list.jsp' starting page</title>
    
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->
    
    <%
        String pageSize = (String)request.getAttribute("pageSize");
        out.println("pageSize:" + pageSize);
     %>
  </head>
  
  <body>
    This is my JSP page. <br>
    <%
        ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
            //DataSource ds = (DataSource) ac.getBean("ds");
            //System.out.println(ds.getConnection().getMetaData().getDriverName());
            
            StudentDao studentDao = (StudentDao) ac.getBean("studentDao");
            List ls = studentDao.getStudent();
            for (int i = 0; i < ls.size(); i++) {
                Student stu = (Student)ls.get(i);
                out.println("<strong>--id--"+stu.getId()+"--name--"+stu.getName()+"</strong><br/>");
            }
     %>
  </body>
</html>

10.数据库脚本test.tbl_student

create database if not exists `test`;

USE `test`;

/*数据表 `tbl_student` 的表结构*/

CREATE TABLE `tbl_student` (
  `id` int(11) NOT NULL auto_increment,
  `name` varchar(20) default NULL,
  PRIMARY KEY  (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=gbk;

/*数据表 `tbl_student` 的数据*/

insert into `tbl_student` values (1,'hnhj');
insert into `tbl_student` values (2,'zndx');
insert into `tbl_student` values (3,'steve');
insert into `tbl_student` values (4,'china');
原文地址:https://www.cnblogs.com/simpledev/p/3149174.html