项目后续
创建项目表结构
student(id,name,age)
创建实体类
生成setter()和getter()
编写dao和mapper
studentdao
public interface StudentDao {
int insertStudent(Student student);
List<Student> selectStudents();
}
studentdao.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="dao.StudentDao">
<select id="selectStudents" resultType="domain.Student">
select * from student order by id desc
</select>
<insert id="insertStudent">
insert into student values(#{id},#{name},#{email},#{age})
</insert>
</mapper>
写service
studentService接口
public interface StudentService {
int addStudent(Student student);
List<Student> findStduents();
}
studentService实现类
@Service
public class StudentServiceImpl implements StudentService {
@Autowired
private StudentDao studentDao;
@Override
public int addStudent(Student student) {
int nums=studentDao.insertStudent(student);
return nums;
}
@Override
public List<Student> findStduents() {
return studentDao.selectStudents();
}
}
写controller
@Controller
@RequestMapping("/student")
public class StudentController {
@Autowired
private StudentService service;
@RequestMapping("/addStudent")
public ModelAndView addStudent(Student student){
String tips="注册失败";
int i = service.addStudent(student);
if(i>0){
tips="注册成功";
}
ModelAndView mv=new ModelAndView();
mv.addObject("tips",tips);
//转发:显示的不受视图解析器限制mv.setViewName("forward:/WEB-INF/view/result.jsp")
//重定向一样的用法,转发可以时WEB-INF下的资源,重定向不能,model中的参数加到url中作为参数
mv.setViewName("result");
return mv;
}
@RequestMapping(value = "/queryStudent",method = RequestMethod.GET)
@ResponseBody
public List<Student> queryStudent(){
List<Student> stduents = service.findStduents();
return stduents;
}
}
对应的result.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1>注册成功</h1>
</body>
</html>
请求主页
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<script type="text/javascript"
src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js">
</script>
<script>
$(function () {
$("#btnLoader").click(function () {
$.ajax({
url:"student/queryStudent",
type:"get",
dataType:"json",
success:function (data){
$.each(data,function (i,n) {
$("#info").append("<tr>")
.append("<td>"+n.id+"</td>")
.append("<td>"+n.name+"</td>")
.append("<td>"+n.age+"</td>")
.append("</tr>")
})
}
})
})
})
</script>
</head>
<body>
<h2>SSM整合</h2>
<div align="center">
<form action="student/addStudent" method="post">
姓名:<input type="text" name="name"><br/>
id:<input type="text" name="id"><br/>
年龄:<input type="text" name="age"><br/>
<input type="submit" value="提交">
</form><br/><br/><br/>
</div><br/>
<div align="center">
<table>
<thead>
<tr>id</tr>
<tr>name</tr>
<tr>age</tr>
</thead>
<tbody id="info"></tbody>
</table>
<input type="button" id="btnLoader" value="查询数据">
</div>
</body>
</html>
到这里基本的SSM整合项目就已经完成了
下面是框架的异常处理和拦截器