本节实训内容为Spring上传文件和MyBatis简单应用 今天升级Mysql和解bug花了太多时间,没时间自己整理了,就直接贴老师的笔记了,有问题可以私信我。
-
表单文件上传
-
导入依赖
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
-
配置spring–mvc.xml <?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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.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">
<context:component-scan base-package="com.qianfeng.controller"></context:component-scan>
<mvc:default-servlet-handler/>
<mvc:annotation-driven/>
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
</bean>
</beans>
-
upload_form.html
<form action="/day4/upload/user" method="post" enctype="multipart/form-data">
用户名: <input type="text" name="userName"><br>
密码: <input type="password" name="userPass"><br>
年龄: <input type="text" name="userAge"><br>
上传头像: <input type="file" name="userFile"> <br>
<input type="submit" value="提交">
</form>
-
UploadController @Controller
@RequestMapping("/upload")
public class UploadController {
@RequestMapping("/user")
@ResponseBody
public String uploadUser(MultipartFile userFile, User user, HttpServletRequest request){
String realPath = request.getServletContext().getRealPath("/");
String parentPath = realPath+"upload_img/";
File parentFile = new File(parentPath);
if(!parentFile.exists()){
parentFile.mkdirs();
}
String fileName = System.currentTimeMillis()+getFileSuffix(userFile.getOriginalFilename());
try {
userFile.transferTo(new File(parentPath+fileName));
} catch (IOException e) {
e.printStackTrace();
}
user.setUserPhoto("upload_img/"+fileName);
System.out.println(user);
return "success";
}
public static String getFileSuffix(String originalName){
int index = originalName.lastIndexOf(".");
return originalName.substring(index);
}
}
-
Mybatis
-
数据库安装与配置(参考群文档) -
mybatis官网:https://mybatis.org/mybatis-3/zh/index.html -
** 介绍:MyBatis 是一款优秀的持久层框架,它支持自定义 SQL、存储过程以及高级映射。MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集的工作。MyBatis 可以通过简单的 XML 或注解来配置和映射原始类型、接口和 Java POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录。** -
Mybatis配置步骤
-
创建quickstart项目 -
导入依赖
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.6</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.38</version>
</dependency>
-
mybatis对数据库的增删查改都依赖SqlSession,sqlSession是从SqlSessionFactory中获取的,SqlSessionFactory是通过SqlSessionFactoryBuilder()读取mybatis的配置文件构建出来的 -
resources中创建mybatis-config.xml <?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/db_mybatis_wenli?characterEncoding=utf-8"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="UserMapper.xml"></mapper>
</mappers>
</configuration>
千万不要忘记Mapper文件的注册??????
-
dao接口 public interface UserDao {
void addUser(User user);
}
-
dao接口对应的Mapper文件(resources/UserMapper.xml) <?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.qianfeng.dao.UserDao">
<insert id="addUser" parameterType="com.qianfeng.bean.User">
insert into tb_user(user_name,hobby,age)
value(#{name},#{hobby},#{age})
</insert>
</mapper>
-
代码测试
@Test
public void testInsert(){
try {
InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
UserDao userDao = sqlSession.getMapper(UserDao.class);
User user = new User();
user.setName("李四");
user.setHobby("唱歌跳舞");
user.setAge(12);
userDao.addUser(user)
sqlSession.commit();
} catch (IOException e) {
e.printStackTrace();
}
}
注意:增删改都需要提交事务
-
测试mybatis查询数据
-
UserDao接口
User getUserById(int id);
-
UserMapper
<select id="getUserById" resultType="com.qianfeng.bean.User">
select id,user_name as name,hobby,age
from tb_user where id=#{id}
</select>
注意:如果实体类属性与表中字段名不一样的话,返回结果为空,所以可以通过取别名解决问题??????
-
结果测试
@Test
public void testGetUserById(){
try {
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis-config.xml"));
SqlSession sqlSession = sqlSessionFactory.openSession();
UserDao userDao = sqlSession.getMapper(UserDao.class);
User user = userDao.getUserById(2);
System.out.println(user);
} catch (IOException e) {
e.printStackTrace();
}
}
|