技术准备
- 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
SSM简易版的更多相关文章
-
学生管理系统(SSM简易版)总结
之前用 Servlet + JSP 实现了一个简易版的学生管理系统,在学习了 SSM 框架之后,我们来对之前写过的项目重构一下! 技术准备 为了完成这个项目,需要掌握如下技术: Java 基础知识 前 ...
-
.NET Core的文件系统[5]:扩展文件系统构建一个简易版&ldquo;云盘&rdquo;
FileProvider构建了一个抽象文件系统,作为它的两个具体实现,PhysicalFileProvider和EmbeddedFileProvider则分别为我们构建了一个物理文件系统和程序集内嵌文 ...
-
MVC 验证码实现( 简易版)
现在网站上越来越多的验证码,使用场景也是越来越多,登陆.注册.上传.下载...等等地方,都有可能大量使用到验证码,那么制作验证码到底有多简单呢?我们一起来看下最简易版的验证码实现过程- 验证码的基本步 ...
-
简易版自定义BaseServlet
这几天在学Java Web,一直在思考Servlet重用的问题,就用java的反射机制实现自定义的简易版BaseServlet; 该方式有点像struts2 利用映射获取前端的参数.有兴趣的同学可以自 ...
-
简易版的TimSort排序算法
欢迎探讨,如有错误敬请指正 如需转载,请注明出处http://www.cnblogs.com/nullzx/ 1. 简易版本TimSort排序算法原理与实现 TimSort排序算法是Python和Ja ...
-
html5 canvas简易版捕鱼达人游戏源码
插件描述:html5利用canvas写的一个js版本的捕鱼,有积分统计,鱼可以全方位移动,炮会跟着鼠标移动,第一次打开需要鼠标移出背景图,再移入的时候就可以控制炮的转动,因为是用的mouseover触 ...
-
Python写地铁的到站的原理简易版
Python地铁的到站流程及原理(个人理解) 今天坐地铁看着站牌就莫名的想如果用Python写其工作原理 是不是很简单就小试牛刀了下大佬们勿喷纯属小弟个人理解 首先来看看地铁上显示的站牌如下: 就想这 ...
-
MVC5+EF6 简易版CMS(非接口) 第四章:使用业务层方法,以及关联表解决方案
目录 简易版CMS后台管理系统开发流程 MVC5+EF6 简易版CMS(非接口) 第一章:新建项目 MVC5+EF6 简易版CMS(非接口) 第二章:建数据模型 MVC5+EF6 简易版CMS(非接口 ...
-
C+命令行+方向键=简易版扫雷
前言: 想起来做这个是因为那时候某天知道了原来黑框框里面的光标是可以控制的,而且又经常听人说起这个,就锻炼一下好了. 之前就完成了那1.0的版本,现在想放上来分享却发现有蛮多问题的,而且最重要的是没什 ...
随机推荐
-
JAVA语言基础——类型转换
1.自动类型转换 自动类型转换又称作隐式转换,可以将一个int变量转换为float类型. public class Conver { public static void main(String[] ...
-
Tomcat Manager用户配置详解
Tomcat Manager是Tomcat自带的.用于对Tomcat自身以及部署在Tomcat上的应用进行管理的web应用.Tomcat是Java领域使用最广泛的服务器之一,因此Tomcat Ma ...
-
vue-购物车
最终的实现效果: 需求分析: 购物车需要展示一个已加入购物车的商品列表,包含商品名称,商品单价,购买数量和操作等信息,还需要实时显示购买的总价.其中购买数量可以增加或减少,每类商品还可以从购物车中移除 ...
-
iOS逆向工程,(狗神)沙梓社大咖免费技术分享。
序言 简介:本文针对于广大iOS开发者,作为一名开发者,仅仅专注于一门语言可能已经不适用现在的市场需求,曾经因高薪和需求量巨大,而火爆一时的移动端开发者(Android,ios),如今的路却是不再那么 ...
-
win7 / mysql-8.0.11-winx64 安装的测坑步骤
虚惊一场,主要问题是 Navicat Premium 连接 mysql8 Client does not support authentication . 1. 下载 官网下载压缩包: mysql ...
-
Go signals 信号
Go中通过os/signals包,可以接受系统信号. package main import "fmt" import "os" import "os ...
-
binlog2sql之MySQL数据闪回实践
DBA或开发人员,有时会误删或者误更新数据,如果是线上环境并且影响较大,就需要能快速回滚.传统恢复方法是利用备份重搭实例,再应用去除错误sql后的binlog来恢复数据.此法费时费力,甚至需要停机维护 ...
-
【玩转Golang】 自定义json序列化对象时,非法字符错误原因
由于前台web页面传来的日期对象是这样的格式“2010-11-03 15:23:22”,所以我安装网上查来的办法,自定义包装了time.Time对象,实现自己的Marshal和UnMarshal方法 ...
-
ubuntu生成core转储文件
1.ulimit -c 判断是否开启转储 为0 则没有开启 2.ulimit -c unlimited 设置转储core大小没有限制 3.设置转储文件位置 echo "/var/core/% ...
-
面向对象编程课程(OOP)第二单元总结
一.设计策略 第一次作业(傻瓜式电梯): 由于是第一次写多线程作业,许多的知识还处在理论阶段,所以第一次作业写得非常的朴实无华.整个程序总共有四个类,Main类负责通过电梯类实例化一个电梯,然后通过w ...