发表于: 2017-05-22 22:26:05
1 1162
今日目标:添加Mybatis,数据库连接池,初步实现接口。
添加Mybatis和C3p0已经在任务1的日报中实现。
编写StudentController:
package com.qhs.rest.controller;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.json.JSONArray;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import com.qhs.rest.bean.Student;
import com.qhs.rest.mapper.StudentMapper;
@Controller
public class StudentController {
@RequestMapping(value="/students",method=RequestMethod.GET)
@ResponseBody
//分页查询所有用户,加入默认页数参数为1
//2017年5月22日21:37:13 未完成根据专业查询用户
public ModelAndView getList(@RequestParam(value="pn",required=false,defaultValue="1") Integer pn) throws IOException{
//指定mapper
StudentMapper mapper = new SqlSessionFactoryBuilder()
.build(Resources.getResourceAsStream("mybatis-config.xml")).openSession()
.getMapper(StudentMapper.class);
List<Student> list = new ArrayList<Student>();
//不带参数,pn=0,参数为0,10
//带2,参数为10,20
list = mapper.list((pn-1)*10,pn*10);
ModelAndView mav = new ModelAndView("students");
JSONArray json = new JSONArray();
json.put(list);
mav.addObject("msg",json);
return mav;
}
}
指定处理/students请求(实现了视图定位),方法为get,传参数pn
将pn作为参数传入,交给Mapper处理,返回List,直接封装进json对象,直接作为返回值传出。
package com.qhs.rest.mapper;
import java.util.List;
import org.apache.ibatis.annotations.*;
import com.qhs.rest.bean.Student;
public interface StudentMapper {
@Select("select * from signup limit #{start},#{count}")
public List<Student> list(@Param("start") int start, @Param("count")int count);
@Select("select * from signup where id= #{id}")
public Student get(int id);
@Select("select * from signup where id= #{name}")
public Student getall(String name);
@Insert("INSERT INTO signup VALUES "
+ "(UNIX_TIMESTAMP(now())*1000,UNIX_TIMESTAMP(now())*1000,null,#{name},#{qq},#{major},#{start_date},"
+ "#{school},#{onlineclass},#{onlineno},#{diarylink},"
+ "#{aim},#{recommender},#{censor},#{wherefrom})")
public int add(Student student);
@Delete("delete * from signup where id= #{id}")
public boolean delete(int id);
}
mapper是接口,其中提供一个分页查询的方法。
students.jsp里直接用EL表达式输出msg的内容。
</head>
<body>
${msg}
</body>
</html>
初步实现了接口的分页查询所有学生的功能。
参考文档:http://www.cnblogs.com/wangchuanfu/p/5913310.html(SpringMvc之@RequestParam详解)
遇到的问题:
1.JSP中文乱码(手动指定编码为UTF-8解决)
2.向github提交项目的时候,由于之前误操作添加了内置的Tomcat,多出了400+个Unstaged Changes,只好删掉整个项目重新从github导入。
导入时报错,Java compiler level does not match,解决方法参见https://jingyan.baidu.com/article/95c9d20da3ec5fec4e756186.html。
3.暂时不知道要处理两个参数时,方法体内应该怎么写。。逐个判断是否为空?
明日目标:
继续做接口……对参数major的响应,以及student/name/的实现。
评论