1.Spring Ioc属性注入使用 set方法注入
private String bookname;
public void setBookname(String bookname) {
this.bookname = bookname;
}
<bean id="book" class="cn.itcast.property.Book">
<property name="bookname" value="数据结构"/>
bean>
2.使用有参数构造注入
<bean id="book" class="cn.itcast.property.Book">
<constructor-arg name="bookname" value="数据结构"/>
bean>
3.注入对象类型属性
public class UserServiceImpl1 implements IUserService{
private IUserDao userDao;
public void setUserDao(IUserDao userDao) {
this.userDao = userDao;
}
....
}
<bean id="userService" class="nuc.edu.cn.dao.service.impl.UserServiceImpl">
<property name="userDao" ref="userDao">
bean>
<bean id="userDao" class="nuc.edu.cn.dao.impl.UserDaoImpl">
bean>
4.注解注入属性
public class UserServiceImpl1 implements IUserService {
@Autowired
private IUserDao userDao;
@Override
public void saveCustom(String arg){
...
}
}
以下web应用
URL地址输入:http://localhost:8080/test/hello1
页面输出字符串"Hello Spring Boot!"
@Controller
@RequestMapping("/test")
public class HelloController {
// 注解用于处理请求地址映射
@RequestMapping("hello1")
// 响应为JSON数据集
@ResponseBody
public String hello() {
return "Hello Spring Boot!";
}
}
以下web应用 控制类代码 调用业务层实现图书信息查询,添加。
@Controller
@RequestMapping("book")
public class UserController {
@Autowired
private IUserService userService;
/**
1.按bookId查询,查询bookId的值为“001”的图书,显示结果JSON格式
请写出URL地址:http://localhost:8080/book/getById?bookId=001
*/
@RequestMapping("getById")
@ResponseBody
public Book getBookById(Integer bookId) {
Book book = bookService.getBook(bookId);
return book;
}
/**
2. 按bookId查询,显示查询结果JSP视图中,
jsp页面路径book/details.jsp
*/
@RequestMapping("/getByIdForJSP")
public ModelAndView getBookById1(Integer id) {
Book book = bookService.getBook(id);
ModelAndView mv = new ModelAndView();
mv.addObject("book1", book);
mv.setViewName("book/details");
return mv;
}
/**
3. 按bookId查询,查询bookId为"003"的图书信息
请写出URL地址:http://localhost:8080/book/getBookById/003
*/
@GetMapping("/getBookById/{id}")
@ResponseBody
public User get(@PathVariable Integer id) {
return bookService.getBook(id);
}
/**
4.如果获取图书编号为“bookId3“且图书名称为”bookName3”的图书信息,查询结果为多条数据
请写出URL地址:
http://localhost:8080/book/list/bookId3/bookName3
*/
@RequestMapping("list/{bookId1}/{bookName1}")
@ResponseBody
public List<Book> list1(@PathVariable("bookId1") String bookId, @PathVariable("bookName1") String bookName) {
List<Book> books = BookService.findBooks(bookId, bookName);
return books;
}
/**
5. 使用@RequestParam获取参数,按bookId与bookName查询信息
如果bookId参数必须填写,bookName参数可填可不填
*/
@RequestMapping("list2")
@ResponseBody
public Book list2(@RequestParam(value="bookId", required=true)String bookId, @RequestParam(value="bookName", required=false)String bookName) {
Book book = userService.findBook(bookId, bookName);
return book;
}
/**
6.打开“新增图书”请求页面, 页面显示用户信息文本框 return 字符串,指向页面
URL地址:http://localhost:8080/book/add
*/
@RequestMapping("add")
public String add() {
return "book/add";
}
/**
7. 新增图书
前端将数据转换为JSON数据后,通过HTTP请求体提交给后端。
*/
@PostMapping("/insert")
@ResponseBody
public User insert(@RequestBody Book book) {
bookService.insertBook(book);
return user;
}
}
一、test数据库中t_user表结构如下:
1)定义实体类
package com.cn.entity
public class User{
private Integer id;
private String userName;
private String note;
setter、getter方法
}
2)持久层
package com.cn.dao
/***import***/
@Mapper
public interface IUserDao{
public List<User> findAllUsers();
public User getUserById(Integer uid);
public Integer insertUser(User user);
...
}
3) UserMapper.xml文件
<mapper namespace="com.cn.dao.IUserDao">
<select id="getUserById" paramterType="Integer" resultType="com.cn.entity.User">
select id,user_name as userName,note from t_user where id=#{uid};
select>
<select id="findAllUsers" resultType="com.cn.entity.User">
select id,user_name as userName,note from t_user
select>
<insert id="insertUser" parameterType="com.cn.entity.User"
useGeneratedKeys="true" keyProperty="id">
insert into t_user(user_name, note) values(#(userName), #{note})
insert>
mapper>
以下代码清单实现单文件上传,运行结果如图所示,请补充完整代码。(注意:输入答案时区分大小写,标点符号为英文状态下输入。)
URL地址栏输入 http://localhost:8080/upload/page
图1 文件上传页面
图2 选择文件
图3 文件上传结果
1)上传文件JSP /WEB-INF/jsp/file/upload/.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<html>
<body>
<form method="post" action="/upload/multipart" enctype="multipart/form-data">
<input type="file" name="photo" value="请选择上传的文件"/>
<input type="sumbit" value="提交"/>
form>
body>
html>
2)文件上传控制器
package com.springmvc.chapter0320191007.controller;
@Controller
public class FileController{
@PostMapping("/upload/multipart")
@ResponseBody
public Map<String, Object> upload(@RequestParam("photo") MultipartFile photo)
{
String path = "d:/uploaded/";//保存路径
String filename = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
// 获取上传文件的后缀suffix
String suffix = photo.getOriginalFilename().substring(photo.getOriginalFilename().lastIndexOf("."));
try {
// Spring提供了文件操作类FileCopyUtils
FileCopyUtils.copy(photo.getInputStream(), new FileOutputStream(path+filename+suffix));
} catch(IOException e) {
e.printStackTrace();
return dealResultMap(false, "上传失败");
}
return dealResultMap(true, "上传成功");
}
// 处理上传文件结果
private Map<String, Object> dealResultMap(boolean success, String msg) {
Map<String, Object> result = new HashMap<String, Object>();
result.put("success", success);
result.put("msg", msg);
return result;
}
}
以下代码清单为拦截器的使用,请补充完整代码。(注意:输入答案时区分大小写,标点符号为英文状态下输入。)
public class Interceptor1 implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("处理器前方法");
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
System.out.println("处理器后方法");
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
System.out.println("处理器完成方法");
}
}
// 注册拦截器
@Configuration
@SpringBootApplication(scanBasePackages="com.springmvc.chapter0320191007")
public class App1 implements WebMvcConfigurer {
public static void main(String[] args){
SpringAlication.run(App1.class, args);
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
InterceptorRegistration ir = registry.addInterceptor(new Interceptor1());
ir.addPathPatterns("/interceptor/*");
}
}
补充完整代码:
部门表和员工表结构如下:(一个部门有多名员工,一名员工只能属于一个部门,两表通过部门编号deptno建立连接)
1. 定义实体类
package com.cn.pojo
//员工实体类
public class Emp {
private Integer empno;
private String ename;
…
private Dept dept; //定义员工和部门的关系 dept为成员变量
setter,getter 方法
}
package com.cn.pojo
//员工部门实体类
public class Dept {
private Integer deptno;
private String dname;
private String location;
private List<Emp> emps; //定义部门和员工的关系,emps为成员变量
setter,getter 方法
}
2. Dao 接口
package com.cn.dao;
…
public interface IEmpDao {
public Emp findByEmpno(Integer empno); //按员工编号查询员工信息及员工所属部门信息
public List<Emp> findByDeptno(Integer deptno); //根据部分编号查询员工信息
}
3. EmpMapper.xml文件
<mapper namespace="com.cn.dao.IEmpDao">
<!—手动映射 Dept表和Java Dept类属性 -->
<resultMap id="empMap" type="com.cn.pojo.Emp">
<id property="empno" column="empno"/>
<result property="ename" column="ename"/>
。。。。。
<association property="dept" javaType="com.cn.pojo.Dept">
。。。。。
association>
resultMap>
<select id="findByEmpno" parameterType="Integer" resultMap="empMap">
select * from emp e,dept d
where e.deptno=d.deptno and e.empno=#{empno}
select>
<select …….>
select * from emp where deptno=#{deptno}
select>
mapper>
4. Dao 接口
package com.cn.dao;
…
public interface IDeptDao {
public Dept findByDeptno(Integer deptno);//按部门编号查询员工信息,包括员工详细信息
}
5. DeptMapper.xml文件
<mapper namespace="com.cn..dao.IDeptDao">
<resultMap type="com.cn.pojo.Dept" id="deptMap">
<id property="deptno" column="deptno"/>
<result property="dname" column="dname"/>
。。。
<collection property="emps" javaType="ArrayList" ofType="com.cn.pojo.Emp" column="deptno" select="com.cn.dao.IEmpDao.findByDeptno">
collection>
resultMap>
<select id="findByDeptno" parameterType="Integer" resultMap="deptMap">
select * from dept where deptno=#{deptno}
select>
mapper>