技术准备
- Java:
基础知识
- 框架:
Spring,SpringMVC,Mybatis
- 数据库:
Mysq
- 开发工具:
Eclipse,Maven
项目结构
数据库设计
- 创建数据库:student
SET NAMES utf8mb4; SET FOREIGN_KEY_CHECKS = 0; -- ---------------------------- -- Table structure for student -- ---------------------------- DROP TABLE IF EXISTS `student`; CREATE TABLE `student` ( `id` int(11) NOT NULL, `studentName` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, `studentSex` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, `studentAge` int(255) NULL DEFAULT NULL, `school` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, `className` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, PRIMARY KEY (`id`) USING BTREE ) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic; -- ---------------------------- -- Records of student -- ---------------------------- INSERT INTO `student` VALUES (1, '小明', '男', 14, '第一中学', '高三1班'); INSERT INTO `student` VALUES (2, '小红', '女', 15, '第一中学', '高三2班'); INSERT INTO `student` VALUES (3, '小黄', '女', 14, '第一中学', '高三1班'); INSERT INTO `student` VALUES (4, '小蓝', '男', 14, '第一中学', '高三2班'); SET FOREIGN_KEY_CHECKS = 1;
依赖引入
- pom.xml文件
<dependencies> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.6</version> </dependency> <!-- commons Start --> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.5</version> </dependency> <!-- 文件上传支持(commons-io) --> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.3</version> </dependency> <!-- Logback相关依赖 Start(slf4j-api) --> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-core</artifactId> <version>1.2.3</version> </dependency> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-classic</artifactId> <version>1.2.3</version> </dependency> <!-- Logback相关依赖 Ends --> <!-- Fastjson --> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.46</version> </dependency> <!-- Spring相关依赖 Start --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jcl</artifactId> <version>5.0.5.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>5.0.5.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>5.0.5.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-expression</artifactId> <version>5.0.5.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>5.0.5.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.0.5.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>5.0.5.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>5.0.5.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>5.0.5.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>5.0.5.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>5.0.5.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.0.5.RELEASE</version> </dependency> <!-- Spring相关依赖 Ends --> <!-- Druid(数据库连接池) --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.6</version> </dependency> <!-- MyBatis相关依赖 Start --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.5</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.3.1</version> </dependency> <!-- MyBatis相关依赖 Ends --> <!-- jstl --> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <!-- servlet-api --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>4.0.0</version> <scope>provided</scope> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.47</version> </dependency> </dependencies>
配置文件
- config.properties(数据库连接配置)
# 配置说明 # driverClassName : 数据库驱动的名称 # url : 数据库的地址 # username : 用户名 # password : 密码 # maxActive : 最大激活连接数 # initialSize : 连接池启动时创建的初始化连接数量 jdbc.mysql.driverClassName=com.mysql.jdbc.Driver jdbc.mysql.url=jdbc:mysql:///shiro?useUnicode=true&characterEncoding=utf8 jdbc.mysql.username=root jdbc.mysql.password=root jdbc.mysql.maxActive=20 jdbc.mysql.initialSize=5
- applicationContext.xml(Spring配置)
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" 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:util="http://www.springframework.org/schema/util" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:task="http://www.springframework.org/schema/task" xmlns:cache="http://www.springframework.org/schema/cache" 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.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task.xsd http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd"> <!-- 加载相关资源文件 --> <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <list> <value>classpath:config.properties</value> </list> </property> <property name="fileEncoding" value="UTF-8"></property> </bean> <!-- 开启注解扫描 --> <context:annotation-config/> <!-- 自动扫描的包名 --> <context:component-scan base-package="org.zyu"> <!-- 不控制 Controller注解,即与 Controller分离 --> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan> <!-- 配置数据源 --> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"> <property name="driverClassName" value="${jdbc.mysql.driverClassName}"></property> <property name="url" value="${jdbc.mysql.url}"></property> <property name="username" value="${jdbc.mysql.username}"></property> <property name="password" value="${jdbc.mysql.password}"></property> </bean> <!-- SqlSessionFactory --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <!-- 数据库连接池 --> <property name="dataSource" ref="dataSource"/> <!-- 加载MyBatis的全局配置文件 --> <property name="mapperLocations"> <list> <value>classpath*:**/dao/**/*Mapper.xml</value> </list> </property> </bean> <!-- Mapper扫描器 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <!-- 扫描包路径,如果需要扫描多个包,中间使用半角逗号隔开 --> <!-- 对**.dao包内进行扫描 --> <property name="basePackage" value="**.dao"/> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/> </bean> <!-- 事务管理器,对MyBatis操作数据库事务控制,Spring使用jdbc的事务控制类 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager" scope="singleton"> <!-- 数据源dataSource在applicationContext-mybatis.xml中配置了 --> <property name="dataSource" ref="dataSource"/> </bean> <!-- 注解的事务管理@Transactional --> <tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true"/> </beans>
- springMVC-servlet.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" 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:util="http://www.springframework.org/schema/util" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:task="http://www.springframework.org/schema/task" xmlns:cache="http://www.springframework.org/schema/cache" 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.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task.xsd http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd"> <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"> <!-- @ResponseBody返回JSON数据中文乱码解决,注意,此配置一定要在<mvc:annotation-driven/>配置前面 --> <property name="messageConverters"> <list> <bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter"> <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.StringHttpMessageConverter"> <property name="supportedMediaTypes"> <list> <value>text/html;charset=UTF-8</value> </list> </property> </bean> </list> </property> </bean> <!-- 静态资源映射(通用) --> <mvc:resources mapping="/css/**" location="/WEB-INF/css/" /> <mvc:resources mapping="/js/**" location="/WEB-INF/js/" /> <mvc:resources mapping="/img/**" location="/WEB-INF/img/" /> <mvc:resources mapping="/3rd/**" location="/WEB-INF/3rd/" /> <!-- 当上面要访问的静态资源不包括在上面的配置中时,则根据此配置来访问 --> <mvc:default-servlet-handler /> <!-- 默认的注解映射的支持 --> <mvc:annotation-driven /> <!-- 开启Controller注解支持 --> <!-- use-default-filters="false"只扫描指定的注解 --> <context:component-scan base-package="**.controller"> <!-- 不控制 Service 注解的事务.即与Service事务分离 --> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Service" /> </context:component-scan> <!-- SpringMVC上传文件时,需配置MultipartResolver处理器 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"/> <!-- 视图解析器 --> <bean id="jspViewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" /> <property name="prefix" value="/WEB-INF/views/" /> <property name="suffix" value=".jsp" /> </bean> <!-- 拦截器配置 --> <mvc:interceptors> <!-- 可配多个拦截器,顺序执行 --> <mvc:interceptor> <!-- [/**]表示所有url包括子url路径 --> <mvc:mapping path="/**"/> <!-- 不拦截静态资源路径下的请求 --> <mvc:exclude-mapping path="/css/**"/> <mvc:exclude-mapping path="/fonts/**"/> <mvc:exclude-mapping path="/img/**"/> <mvc:exclude-mapping path="/js/**"/> <mvc:exclude-mapping path="/plugins/**"/> <mvc:exclude-mapping path="/upload/**"/> <bean class="org.zyu.intercepter.BaseHandlerInterceptor"/> </mvc:interceptor> </mvc:interceptors> </beans>
- logback.xml(打印日志信息)
<?xml version="1.0" encoding="UTF-8"?> <configuration> <!-- 基本信息配置 --> <property name="localAppName" value="org.xujun"/> <property name="logHomeDir" value="${user.dir}/logs/logback"/> <property name="logbackLevel" value="DEBUG"/> <contextName>default</contextName> <!-- 控制台输出配置 --> <appender name="ConsoleAppender" class="ch.qos.logback.core.ConsoleAppender"> <target>System.out</target> <encoder> <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg %n</pattern> </encoder> </appender> <!-- 针对本项目配置的日志 Start --> <appender name="LOCALAPP_DEBUG" class="ch.qos.logback.core.rolling.RollingFileAppender"> <Encoding>UTF-8</Encoding> <Prudent>false</Prudent> <filter class="ch.qos.logback.classic.filter.LevelFilter"> <level>DEBUG</level> <onMatch>ACCEPT</onMatch> <onMismatch>DENY</onMismatch> </filter> <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> <FileNamePattern>${logHomeDir}/${localAppName}/debug/debug-%d{yyyy-MM-dd}.log</FileNamePattern> <MaxHistory>10</MaxHistory> <!-- 日志保留的个数 --> </rollingPolicy> <layout class="ch.qos.logback.classic.PatternLayout"> <Pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</Pattern> </layout> </appender> <appender name="LOCALAPP_WARN" class="ch.qos.logback.core.rolling.RollingFileAppender"> <Encoding>UTF-8</Encoding> <Prudent>false</Prudent> <filter class="ch.qos.logback.classic.filter.LevelFilter"> <level>WARN</level> <onMatch>ACCEPT</onMatch> <onMismatch>DENY</onMismatch> </filter> <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> <FileNamePattern>${logHomeDir}/${localAppName}/warn/warn-%d{yyyy-MM-dd}.log</FileNamePattern> <MaxHistory>10</MaxHistory> <!-- 日志保留的个数 --> </rollingPolicy> <layout class="ch.qos.logback.classic.PatternLayout"> <Pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</Pattern> </layout> </appender> <appender name="LOCALAPP_INFO" class="ch.qos.logback.core.rolling.RollingFileAppender"> <Encoding>UTF-8</Encoding> <Prudent>false</Prudent> <filter class="ch.qos.logback.classic.filter.LevelFilter"> <level>INFO</level> <onMatch>ACCEPT</onMatch> <onMismatch>DENY</onMismatch> </filter> <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> <FileNamePattern>${logHomeDir}/${localAppName}/info/info-%d{yyyy-MM-dd}.log</FileNamePattern> <MaxHistory>10</MaxHistory> <!-- 日志保留的个数 --> </rollingPolicy> <layout class="ch.qos.logback.classic.PatternLayout"> <Pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</Pattern> </layout> </appender> <appender name="LOCALAPP_ERROR" class="ch.qos.logback.core.rolling.RollingFileAppender"> <Encoding>UTF-8</Encoding> <Prudent>false</Prudent> <filter class="ch.qos.logback.classic.filter.LevelFilter"> <level>ERROR</level> <onMatch>ACCEPT</onMatch> <onMismatch>DENY</onMismatch> </filter> <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> <FileNamePattern>${logHomeDir}/${localAppName}/error/error-%d{yyyy-MM-dd}.log</FileNamePattern> <MaxHistory>10</MaxHistory> <!-- 日志保留的个数 --> </rollingPolicy> <layout class="ch.qos.logback.classic.PatternLayout"> <Pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</Pattern> </layout> </appender> <!-- 针对本项目配置的日志 Ends --> <!-- 针对第三方配置的日志 Start --> <appender name="THIRDPART_DEFAULT" class="ch.qos.logback.core.rolling.RollingFileAppender"> <Encoding>UTF-8</Encoding> <Prudent>false</Prudent> <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> <FileNamePattern>${logHomeDir}/${localAppName}/thirdpart/thirdpart-%d{yyyy-MM-dd}.log</FileNamePattern> <MaxHistory>10</MaxHistory> <!-- 日志保留的个数 --> </rollingPolicy> <layout class="ch.qos.logback.classic.PatternLayout"> <Pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</Pattern> </layout> </appender> <!-- 针对第三方配置的日志 Ends --> <!-- 针对指定包配置的日志 Start --> <logger name="test" addtivity="false" level="${logbackLevel}"> <appender-ref ref="ConsoleAppender"/> </logger> <logger name="org" addtivity="false" level="${logbackLevel}"> <appender-ref ref="ConsoleAppender"/> <appender-ref ref="THIRDPART_DEFAULT"/> </logger> <logger name="com" addtivity="false" level="${logbackLevel}"> <appender-ref ref="ConsoleAppender"/> <appender-ref ref="THIRDPART_DEFAULT"/> </logger> <!-- log4jdbc 专用配置 --> <logger name="jdbc.sqltiming" addtivity="false" level="${logbackLevel}"> <appender-ref ref="ConsoleAppender"/> </logger> <logger name="jdbc.resultsettable" level="INFO"></logger> <logger name="jdbc.sqlonly" level="OFF"></logger> <logger name="jdbc.audit" level="OFF"></logger> <logger name="jdbc.resultset" level="OFF"></logger> <logger name="jdbc.connection" level="OFF"></logger> <!-- 针对指定包配置的日志 Ends --> <!-- 根logger<root>此标签必须设置在最后面方可正常读取,否则系统将识别为无输出控制. 只有一个level属性,用来设置打印级别,大小写无关:TRACE, DEBUG, INFO, WARN, ERROR, ALL 和 OFF, 不能设置为INHERITED或者同义词NULL. 默认是DEBUG. <root>可以包含零个或多个<appender-ref>元素,标识这个appender将会添加到这个loger. --> <root level="WARN"> <!-- <appender-ref ref="ConsoleAppender"/> --> </root> </configuration>
- web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <!-- Spring的配置 Start --> <context-param> <description>配置spring读取的xml文件,param-name是spring规定,spring自动加载以下内容.</description> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- Spring的配置 Ends --> <!-- SpringMVC 配置 Start --> <!-- Web请求编码过滤器,POST中文乱码解决方案 --> <filter> <filter-name>characterEncodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>characterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- DispatcherServlet 配置加载 --> <servlet> <servlet-name>springMVC</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <!-- 以下配置springmvc-servlet.xml放在包内或部署的classes目录下的对应目录下皆可. --> <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> <!-- SpringMVC 配置 Ends --> <session-config> <session-timeout>30</session-timeout> </session-config> </web-app>
好了,基本配置完成,接下来开始写代码。
① 实体类设计
实体类的字段名需要和数据库的一一对应
- 在Package【org.zyu.bean】下创建Student类
package org.zyu.bean; public class Student { private Integer id; private String studentName; private String studentSex; private Integer studentAge; private String school; private String className; public Student() { } public Student(Integer id, String studentName, String studentSex, Integer studentAge, String school, String className) { this.id = id; this.studentName = studentName; this.studentSex = studentSex; this.studentAge = studentAge; this.school = school; this.className = className; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getStudentName() { return studentName; } public void setStudentName(String studentName) { this.studentName = studentName; } public String getStudentSex() { return studentSex; } public void setStudentSex(String studentSex) { this.studentSex = studentSex; } public Integer getStudentAge() { return studentAge; } public void setStudentAge(Integer studentAge) { this.studentAge = studentAge; } public String getSchool() { return school; } public void setSchool(String school) { this.school = school; } public String getClassName() { return className; } public void setClassName(String className) { this.className = className; } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("Student [id="); builder.append(id); builder.append(", studentName="); builder.append(studentName); builder.append(", studentSex="); builder.append(studentSex); builder.append(", studentAge="); builder.append(studentAge); builder.append(", school="); builder.append(school); builder.append(", className="); builder.append(className); builder.append("]"); return builder.toString(); } }
② DAO类设计
DAO,即 Date Access Object,数据库访问对象,就是对数据库相关操作的封装,让其他地方看不到 JDBC 的代码。
在【org.zyu.dao】下创建【StudentMapper】接口(注意:接口的方法名需要和映射文件的id一致)
package org.zyu.dao; import java.util.List; import org.zyu.bean.Student; public interface StudentMapper { /** * 获取学生列表 * @return List<Bean> */ List<Student> getStudentList(); }
在【org.zyu.dao】下创建【StudentMapper.xml】映射文件(注意:namespace:对应接口的相对路径)
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//ibatis.apache.org//DTD Mapper 3.0//EN" "http://ibatis.apache.org/dtd/ibatis-3-mapper.dtd"> <mapper namespace="org.zyu.dao.StudentMapper"> <!-- 查询学生列表 --> <select id="getStudentList" resultType="org.zyu.bean.Student"> SELECT * FROM student </select> </mapper>
③ 业务类设计
- 问题:为什么不直接使用 Dao 类而是还要在上面封装一层 Service 层呢?
- 回答:
基于责任分离的原则,Dao 层就应该专注于对数据库的操作,而在 Service 层我们可以增加一些非 CRUD 的方法去更好的完成本身抽离出来的 service 服务(业务处理)。
在【org.zyu.service】包下创建【StudentService】接口:
package org.zyu.service; import java.util.List; import org.zyu.bean.Student; public interface StudentService { /** * 获取所有学生列表 * @return */ List<Student> getStudentList(); }
在【org.zyu.service.impl】下创建【StudentServiceImpl】:
package org.zyu.service.impl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.zyu.bean.Student; import org.zyu.dao.StudentMapper; import org.zyu.service.StudentService; @Service public class StudentServiceImpl implements StudentService { @Autowired private StudentMapper mapper; public List<Student> getStudentList() { return mapper.getStudentList(); } }
④ 功能开发
在【org.zyu.controller】包下创建【StudentController】控制器:
package org.zyu.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.zyu.service.StudentService; import com.alibaba.fastjson.JSONObject; @Controller public class StudentController { @Autowired public StudentService studentService; @RequestMapping("/showList") @ResponseBody public JSONObject getStudentList() { JSONObject data = new JSONObject(); data.put("list", studentService.getStudentList()); return data; } }
运行项目。。。
输入网址:http://localhost:8080/java_Excel/showList
项目地址:https://pan.baidu.com/s/1mg9AZUzMVomqRxduCWNE0Q 密码:8z6j