SpringMVC+Mybatis初尝试
一个月前简单学完了SpringMVC框架和Mybatis框架,一直没有使用过,今天主要用它做了个简单的学生管理系统,不过第一次用框架,实现的功能简单,比较low.
注:这里使用的数据库是SQLServer,如果想用MySQL数据库的话,只需要改下数据库配置文件和导入连接MySQL的ja包即可。
项目结构图:
导入的jar包:
项目源文件代码:
控制层
package cn.itcast.controller; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import cn.itcast.po.Student; import cn.itcast.service.StudentService; @Controller @RequestMapping("/student") public class StudentController { @Autowired private StudentService studentService; @RequestMapping("/addStudent") public String addStudent(Student student) { studentService.addStudent(student); return "success"; } @RequestMapping("/deleteStudent") public String deleteStudent(int id) { studentService.deleteStudent(id); return "success"; } @RequestMapping("/modifyStudent") public String modifyStudent(Student student) { studentService.modifyStudent(student); return "success"; } @RequestMapping("/getStudentList") public String getStudentList(Model model) { List<Student> studentList=studentService.getStudentList(); model.addAttribute("studentList",studentList); return "student/index"; } @RequestMapping("/getStudent") public String getStudent(Model model,int id) { Student student=studentService.geStudent(id); model.addAttribute("student",student); return "/student/edit"; } @RequestMapping("/add") public String add() { return "/student/add"; } }
mapper代理
package cn.itcast.mapper; import java.util.List; import cn.itcast.po.Student; public interface StudentMapper { //添加学生 int addStudent(Student student); //删除学生 int deleteStudent(int id); //修改学生 int modifyStudent(Student student); //查询学生列表 List<Student> getStudentList(); //得到单个学生信息 Student getStudent(int id); }
<?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="cn.itcast.mapper.StudentMapper"> <insert id="addStudent" parameterType="cn.itcast.po.Student"> insert into student(stunumber,name,sex,birthday,address) values(#{stunumber},#{name},#{sex}, #{birthday},#{address}) </insert> <delete id="deleteStudent" parameterType="int"> delete from student where id = #{value} </delete> <update id="modifyStudent" parameterType="cn.itcast.po.Student"> update student set stunumber=#{stunumber},name=#{name},sex=#{sex},birthday=#{birthday}, address=#{address} where id=#{id} </update> <select id="getStudentList" resultType="cn.itcast.po.Student"> select * from student </select> <select id="getStudent" parameterType="int" resultType="cn.itcast.po.Student"> select * from student where id=#{value} </select> </mapper>
po层
package cn.itcast.po; public class Student { int id; String stunumber; String name; String sex; String birthday; String address; public Student() { } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getStunumber() { return stunumber; } public void setStunumber(String stunumber) { this.stunumber = stunumber; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public String getBirthday() { return birthday; } public void setBirthday(String birthday) { this.birthday = birthday; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } }
service层
package cn.itcast.service; import java.util.List; import cn.itcast.po.Student; public interface StudentService { public void addStudent(Student student); public void deleteStudent(int id); public void modifyStudent(Student student); public List<Student> getStudentList(); public Student geStudent(int id); }
service接口实现层
package cn.itcast.service.impl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import cn.itcast.mapper.StudentMapper; import cn.itcast.po.Student; import cn.itcast.service.StudentService; public class StudentServiceImpl implements StudentService { @Autowired private StudentMapper studentMapper; @Override public void addStudent(Student student) { studentMapper.addStudent(student); } @Override public void deleteStudent(int id) { studentMapper.deleteStudent(id); } @Override public void modifyStudent(Student student) { studentMapper.modifyStudent(student); } @Override public List<Student> getStudentList() { return studentMapper.getStudentList(); } @Override public Student geStudent(int id) { return studentMapper.getStudent(id); } }
框架的配置
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <display-name>SpringMvc_Mybatis</display-name> <!-- 加载spring容器 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/classes/spring/applicationContext-*.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- 解决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> <!-- springmvc前端控制器 --> <servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!-- contextConfigLocation配置springmvc加载的配置文件(配置处理器映射器、设配器等等) 如果不配置contextConfigLocation,springmvc默认加载/WEB-INF/servlet名称-servlet.xml(springmvc-servlet.xml) --> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring/springmvc.xml</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name> <!-- 配置方式有多种 第一种:*.action 访问以.action结尾的文件 由DispatcherServlet进行解析 第二种:/,所有访问的地址都由DispatcherServlet进行解析,对于静态文件的解析,我们需要配置其不被DispatcherServlet解析 因为根目录下有图片,pdf等文件,这些文件不是handler,使用此种方法可以实现RESTful风格的url 第三种(错误的做法):/* 这种配置不对,使用这种配置,最终要转发到一个jsp页面,仍然需要DispatcherServlet解析jsp, 不能根据jsp页面找到handler,会报错。 --> <url-pattern>*.action</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file>default.html</welcome-file> <welcome-file>default.htm</welcome-file> <welcome-file>default.jsp</welcome-file> </welcome-file-list> </web-app>
mybatis配置
<?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> <!-- 全局setting配置,根据需要添加 --> <!-- 配置别名:这里采用批量扫描的形式 --> <typeAliases> <package name="cn.itcat.po"/> </typeAliases> <!-- 配置mapper : 由于使用mybatis和spring的整合包进行mapper扫描,所以这里不用配置mapper了 但必须遵循相关规范:即mapper.xml名称和mapper.java的类名一致且必需在同一个目录 --> </configuration>
spring配置
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd "> <!-- 加载db.properties中的内容 db.properties文件key值的命名要有一定的规则--> <context:property-placeholder location="classpath:db.properties"/> <!-- 配置数据员:dbcp连接池 --> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" > <property name="driverClassName" value="${jdbc.driver}"/> <property name="url" value="${jdbc.url}"/> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> <property name="maxActive" value="10"/> <property name="maxIdle" value="5"/> </bean> <!-- sqlSessionFactory --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <!-- 数据库连接池 --> <property name="dataSource" ref="dataSource" /> <!-- 加载mybatis的全局配置文件 --> <property name="configLocation" value="classpath:mybatis/sqlMapConfig.xml" /> </bean> <!-- mapper扫描器 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <!-- 扫描包路径,如果要扫描多个包,中间用半角英文符号隔开 --> <property name="basePackage" value="cn.itcast.mapper"></property> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property> </bean> </beans>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd "> <!-- 学生管理的service --> <bean id="studentService" class="cn.itcast.service.impl.StudentServiceImpl"> </bean> </beans>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd "> <!-- 事务管理器 对mybatis操作数据库事务控制,spring使用jdbc的控制类 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <!-- 因为要操作数据库,所以要配置数据源 dataSource在applicationContext-dao中配置 --> <property name="dataSource" ref="dataSource"/> </bean> <!-- 将通知传递给Manager --> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <!-- 传播行为 --> <tx:method name="save*" propagation="REQUIRED"/> <tx:method name="delete*" propagation="REQUIRED"/> <tx:method name="insert*" propagation="REQUIRED"/> <tx:method name="update*" propagation="REQUIRED"/> <tx:method name="find*" propagation="SUPPORTS" read-only="true"/> <tx:method name="get*" propagation="SUPPORTS" read-only="true"/> <tx:method name="select*" propagation="SUPPORTS" read-only="true"/> </tx:attributes> </tx:advice> <!-- aop: --> <aop:config> <aop:advisor advice-ref="txAdvice" pointcut="execution(* cn.itcast.ssm.service.impl.*.*(..))"/> </aop:config> </beans>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd "> <!-- 可以扫描controller,service...这里让扫描controller,指定controller的包--> <context:component-scan base-package="cn.itcast.controller"/> <!-- 简单方式:可以使用mvc:annotation-driven形式代替注解映射器和注解适配器 最主要的是mvc:annotation-driven默认加载了很多参数绑定的方法,比如json的转换解析器就默认加载 配置了mvc:annotation-driven就不用对注解映射器和注解适配器进行配置,实际开发中使用此方法 --> <!-- 视图解析器,解析jsp,默认使用jstl标签,classpath下面得有jstl的包--> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <!-- 配置jsp绝对路径的前缀 --> <property name="prefix" value="/WEB-INF/jsp/"/> <!-- 配置jsp绝对路径的后缀 --> <property name="suffix" value=".jsp"/> </bean> </beans>
数据库文件和日志文件配置
jdbc.driver=com.microsoft.sqlserver.jdbc.SQLServerDriver jdbc.url=jdbc:sqlserver://localhost:1433;DatabaseName=stumes jdbc.username=sa jdbc.password=123
# Global logging configuration log4j.rootLogger=DEBUG, stdout # Console output... log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
视图层
css文件
body { text-align: center; } table { width: 400px; border: 1px solid #696969; border-collapse: collapse; margin:0 auto; } th { border: 1px solid #696969; background-color: #FFF8DC; } td { text-align: center; border: 1px solid #696969; height: 50px; background-color: #E0FFFF; } input { font-size: 20px; }
js文件(jquery的jar包自己导入即可)
$(function(){ $("#bt").click(function(event){ var flag=true; for(var i=0;i<5;i++) { var temp=$("input").eq(i).val().trim(); console.log(temp); if(temp==""){ flag=false; } } if(!flag){ alert('请将信息填写完整'); event.preventDefault(); } }); function time() { var now = new Date(); var year = now.getFullYear(); //得到年份 var month = now.getMonth()+1;//得到月份 var date = now.getDate();//得到日期 var hour= now.getHours();//得到小时数 var minute= now.getMinutes();//得到分钟数 var second= now.getSeconds();//得到秒数 $("#time").text(year+"年 "+month+"月 "+date+"日 "+hour+"时 "+minute+"分 "+second+"秒 "); } time(); setInterval(time,1000); });
jsp文件
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>添加个人信息</title>
<link rel="stylesheet" type="text/css" href="../css/style.css">
<script src="../js/jquery-1.12.4.min.js"></script>
<script src="../js/judge.js"></script>
</head>
<body>
<form action="${pageContext.request.contextPath }/student/addStudent.action" method="post">
<h2>添加个人信息</h2>
<table border="1" style="width: 50%">
<tr>
<th width="30%">学号:</th>
<td width="70%"><input name="stunumber" type="text"></td>
</tr>
<tr>
<th>姓名:</th>
<td><input name="name" type="text"></td>
</tr>
<tr>
<th>性别:</th>
<td><input name="sex" type="text"></td>
</tr>
<tr>
<th>出生年月:</th>
<td><input name="birthday" type="text"></td>
</tr>
<tr>
<th>住址:</th>
<td><input name="address" type="text"></td>
</tr>
<tr>
<td colspan="2"><input type="submit" id="bt" value="添加" > <input type="reset" value="重置"></td>
</tr>
</table>
</form>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>修改个人信息</title>
<link rel="stylesheet" type="text/css" href="../css/style.css">
<script src="../js/jquery-1.12.4.min.js"></script>
<script src="../js/judge.js"></script>
</head>
<body>
<form action="${pageContext.request.contextPath }/student/modifyStudent.action" method="post">
<h2>修改个人信息</h2>
<table border="1" style="width:50%">
<tr>
<th>学号</th>
<th><input type="text" name="stunumber" value="${student.stunumber }"></th>
</tr>
<tr>
<th>姓名</th>
<th><input type="text" name="name" value="${student.name }"></th>
</tr>
<tr>
<th>性别</th>
<th><input type="text" name="sex" value="${student.sex }"></th>
</tr>
<tr>
<th>出生年月</th>
<th><input type="text" name="birthday" value="${student.birthday }"></th>
</tr>
<tr>
<th>住址</th>
<th><input type="text" name="address" value="${student.address }"></th>
</tr>
<tr>
<th colspan="2"><input type="hidden" name="id" value="${student.id }"><input type="submit" id="bt" value="修改"> <input type="reset" value="重置"></th>
</tr>
</table>
</form>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>学生信息管理系统</title> <link rel="stylesheet" type="text/css" href="../css/style.css"> <script src="../js/jquery-1.12.4.min.js"></script> <script src="../js/judge.js"></script> </head> <body> <h1>学生信息管理系统</h1> <a href="${pageContext.request.contextPath }/student/add.action">添加学生信息</a> <br /> <br /> <table border="1" style="width: 50%;"> <tr> <th>学号</th> <th>姓名</th> <th>性别</th> <th>出生年月</th> <th>住址</th> <th>操作</th> </tr> <c:forEach items="${studentList}" var="item"> <tr> <td>${item.stunumber }</td> <td>${item.name }</td> <td>${item.sex }</td> <td>${item.birthday }</td> <td>${item.address }</td> <td><a href="${pageContext.request.contextPath }/student/getStudent.action?id=${item.id}">修改</a> <a href="${pageContext.request.contextPath }/student/deleteStudent.action?id=${item.id}">删除</a> </td> </tr> </c:forEach> </table> <br /> <hr /> <div style="text-align: center; width: 100%; font-size: 15px; color: #333;" id="time"></div> </body> </html>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> <div>操作成功<a href="${pageContext.request.contextPath }/student/getStudentList.action"> ,返回首页</a></div> </body> </html>
运行结果截图