前幾天作了一個學生信息管理的項目,使用純控制檯輸入,查詢數據庫,將信息在控制檯中打印,功能完善得差很少以後,老師讓將這個項目移植到Web中,使用Spring+SpringMVC+MyBatis將項目作成網頁,藉此機會熟悉一下SSM框架的搭建流程。html
項目的目錄結構以下:java
圖片中的jar包可能一些多於的包,另外在開發中遇到沒有導入的包的時候再去下載mysql
<?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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <!-- 該監聽器監聽應用的啓動,加載Spring的配置文件,默認加載WEB-INF下的名字爲applicationContext.xml文件 並建立Spring容器 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- 告訴ContextLoaderListener下面配置的文件也是須要加載的 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param> <!-- 攔截器用於解決post請求中請求參數值可能出現亂碼的狀況 --> <filter> <filter-name>characterEncoding</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>characterEncoding</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- 配置SpringMVC中的分發控制器DispatcherServlet 默認加載WEB-INF下的springmvc-servlet.xml --> <servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>
<?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 "> <!-- 讓Spring識別註解 --> <context:component-scan base-package="com.sysystem.controller"></context:component-scan> <!-- 讓SpringMVC識別註解 --> <mvc:annotation-driven></mvc:annotation-driven> <!-- 配置視圖解析器 若是是顯式轉發,則能夠不須要視圖解析器--> <bean id="resourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/> <property name="prefix" value="/"/> <property name="suffix" value=".jsp"/> </bean> <!-- 配置文件上傳解析器 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"/> </beans>
<?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" 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 "> <!-- 讓Spring識別註解 --> <context:component-scan base-package="com.sysystem"></context:component-scan> <!-- 配置數據源,指出鏈接數據庫須要的驅動、url、用戶名和密碼以及鏈接池相關信息 --> <bean id="dbcpdataSource" class="org.apache.commons.dbcp.BasicDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver"></property> <property name="url" value="jdbc:mysql://localhost:3306/traineeinfo"></property> <property name="username" value="root"></property> <property name="password" value="root"></property> <property name="initialSize" value="20"></property> <property name="maxActive" value="10"></property> <property name="maxIdle" value="3"></property> <property name="minIdle" value="2"></property> </bean> <bean id="SqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="configLocation" value="classpath:mybatis-config.xml"/> <property name="dataSource" ref="dbcpdataSource"/> </bean> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer" > <property name="basePackage" value="com.sysystem.model.dao"/> <property name="sqlSessionFactory" ref="SqlSessionFactory"></property> </bean> </beans>
<?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> <!-- 在配置文件中定義別名,能夠在映射文件中使用別名 --> <typeAliases> <package name="com.sysystem.model.entity"/> </typeAliases> <!-- 註冊映射文件 --> <mappers> <package name="com.sysystem.model.dao"/> </mappers> </configuration>
student.java Student學生類,標準的JavaBean,屬性私有,提供setter/getter方法web
IStudentDao.java 數據操做對象接口spring
package com.sysystem.model.dao; import java.util.List; import java.util.Map; import com.sysystem.model.entity.Student; public interface IStudentDao { // 獲取全部的學生信息 List<Student> getAllStudentWithPage(Map<String,Object> map); // 根據學生id查詢學生信息 Student getSingleStudent(int stu_id); // 得到學生表的記錄個數 int getStuRows(); // 新增學生信息 boolean addStu(Student stu); // 修改學生信息 boolean updateStu(Student stu); }
IStudentDao.xml 實現對數據庫的增刪改查操做sql
<?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.sysystem.model.dao.IStudentDao"> <select id="getSingleStudent" parameterType="int" resultType="Student"> select stu_name,birthday,sex,school from stu_info where stu_id = #{stu_id} </select> <select id="getStuRows" resultType="int"> select count(1) from (SELECT s.stu_id FROM (stu_info s LEFT JOIN stu_pro_relation spr ON s.stu_id = spr.stu_id) LEFT JOIN project p ON p.pro_id = spr.pro_id) temp </select> <select id="getAllStudentWithPage" parameterType="java.util.Map" resultType="Student"> SELECT s.stu_id,s.stu_name,CEIL(DATEDIFF(CURDATE(), s.birthday) / 365.2422) age, s.sex,s.school,p.pro_id,p.pro_name,p.`code` FROM (stu_info s LEFT JOIN stu_pro_relation spr ON s.stu_id = spr.stu_id) LEFT JOIN project p ON p.pro_id = spr.pro_id LIMIT #{pageStart},#{pageSize} </select> <insert id="addStu" parameterType="Student"> insert into stu_info (stu_name,birthday,sex,school) values (#{stu_name},#{birthday},#{sex},#{school}) </insert> <update id="updateStu" parameterType="Student"> update stu_info set stu_name = #{stu_name},birthday = #{birthday},sex = #{sex},school = #{school} where stu_id = #{stu_id} </update> </mapper>
IStudentService.java 數據庫
package com.sysystem.model.service; import java.util.List; import java.util.Map; import com.sysystem.model.entity.Student; public interface IStudentService { // 獲取全部的學生信息 List<Student> getAllStudentWithPage(Map<String,Object> map); // 根據學生id查詢學生信息 Student getSingleStudent(int stu_id); // 得到學生表的記錄個數 int getStuRows(); // 新增學生信息 boolean addStu(Student stu); // 修改學生信息 boolean updateStu(Student stu); }
StudentServiceImpl.java 經過Dao獲取對象,而後進行業務邏輯實現apache
package com.sysystem.model.service.impl; import java.util.List; import java.util.Map; import javax.annotation.Resource; import org.springframework.stereotype.Service; import com.sysystem.model.dao.IStudentDao; import com.sysystem.model.entity.Student; import com.sysystem.model.service.IStudentService; @Service("stuService") public class StudentServiceImpl implements IStudentService { @Resource private IStudentDao stuDao; @Override public Student getSingleStudent(int stu_id) { return stuDao.getSingleStudent(stu_id); } @Override public int getStuRows() { return stuDao.getStuRows(); } @Override public List<Student> getAllStudentWithPage(Map<String,Object> map) { return stuDao.getAllStudentWithPage(map); } @Override public boolean addStu(Student stu) { return stuDao.addStu(stu); } @Override public boolean updateStu(Student stu) { return stuDao.updateStu(stu); } }
BaseController.javajson
package com.sysystem.controller; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.http.HttpServletResponse; import com.google.gson.Gson; public class BaseController { /** * 向響應的輸出流寫文本數據 * @param response 響應 * @param str 文本數據 */ public void writeToRes (HttpServletResponse response, String str){ // 設置輸出的字符集 response.setContentType("text/html;charset=utf-8"); // 定義輸出流對象 PrintWriter out = null; try { out = response.getWriter(); out.print(str); } catch (IOException e) { e.printStackTrace(); } finally { out.close(); } } /** * 向響應的輸出流寫json數據 * @param response 響應 * @param obj json數據 */ public void writeToRes (HttpServletResponse response, Object obj){ response.setContentType("text/html;charset=utf-8"); PrintWriter out = null; try { out = response.getWriter(); String json = new Gson().toJson(obj); out.print(json); } catch (IOException e) { e.printStackTrace(); } finally { out.close(); } } }
StudentController.java瀏覽器
package com.sysystem.controller; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import com.sysystem.model.entity.Student; import com.sysystem.model.service.IStudentService; import com.sysystem.model.util.ChangeDate; import com.sysystem.model.util.Page; @Controller @RequestMapping("/student") public class StudentController extends BaseController{ @Resource private IStudentService studentService; /** * 根據學生的id獲取學生信息 * @param request 請求 * @param response 響應 * @param stu_id 學生id * @return 指定頁面前綴 * @throws Exception */ @RequestMapping("/getSingleStudent") public String getSingleStudent(HttpServletRequest request,HttpServletResponse response, int stu_id) throws Exception { Student student = studentService.getSingleStudent(stu_id); // 將CST類型的時間轉換爲字符串 String date = ChangeDate.cst2String(student.getBirthday()); request.setAttribute("date", date); request.setAttribute("stu", student); return "updateStu"; } /** * 分頁得到學生的記錄信息 * @param request 請求 * @param response 響應 * @param curpage 當前頁 * @return 指定頁面的前綴 * @throws Exception */ @RequestMapping("/getAllStudentWithPage") public String getAllStudentWithPage(HttpServletRequest request,HttpServletResponse response,int curpage) throws Exception { // 定義每頁記錄個數 int pageSize = 3; // 得到總記錄個數 int total = studentService.getStuRows(); // 建立Page對象 Page page = new Page(curpage, pageSize, total); // 得到總頁數 int totalpage = page.gettotalpage(); // 獲得真實的當前頁 curpage = page.getcurpage(); // 獲得Limit的第一個參數 int pageStart = page.getStart(); // 將參數存放在map集合中(MyBatis中傳遞多個參數使用的方法) Map<String,Object> map = new HashMap<String,Object>(); map.put("pageStart", pageStart); map.put("pageSize", pageSize); // 得到查詢到的記錄集合 List<Student> stulist = studentService.getAllStudentWithPage(map); // 將集合,當前頁,總頁數存放在request中 request.setAttribute("stulist", stulist); request.setAttribute("curpage", curpage); request.setAttribute("totalpage", totalpage); return "allStu"; } @RequestMapping("/addStu") public String addStu(HttpServletRequest request,HttpServletResponse response,Student stu) throws Exception { boolean flag = studentService.addStu(stu); if (flag) { return "index"; }else{ return null; } } @RequestMapping("/updateStu") public void updateStu(HttpServletRequest request,HttpServletResponse response,Student stu) throws Exception { boolean flag = studentService.updateStu(stu); if (flag) { writeToRes(response, "1"); }else{ writeToRes(response, "0"); } } }
ChangeDate.java
package com.sysystem.model.util; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; public class ChangeDate { /** * 將java.util包下的Date對象轉爲java.sql包下的date * @param date java.util.Date * @return java.sql.Date */ public static java.sql.Date utilDateToSqlDate(Date date) { // 獲取了毫秒值ֵ long millisTime = date.getTime(); // 根據毫秒值來獲取java.sql包下的Date對象 java.sql.Date pubTime = new java.sql.Date(millisTime); return pubTime; } /** * 將字符串轉換成Date類型 * @param time String類型的時間字符串 * @return Date */ public static Date strDate(String time) { Date date = null; DateFormat df = new SimpleDateFormat("yyyy-MM-dd"); try { date = df.parse(time); } catch (ParseException e) { System.out.println("日期格式輸入不正確 "); } return date; } /** * 將CST格式的日期轉換爲String字符串 * @param date 日期 * @return 字符串 */ public static String cst2String(Date date){ String datestr = date.toString(); SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.US); Date d =null; try { d = sdf.parse(datestr); } catch (ParseException e) { e.printStackTrace(); } String formatDate = new SimpleDateFormat("yyyy-MM-dd").format(d); return formatDate; } }
Page.java 進行分頁的方法
package com.sysystem.model.util; public class Page { // 當前頁 private int curpage; // 每頁記錄個數 private int pageSize; // 總記錄數 private int total; public Page(int curpage, int pageSize, int total) { this.curpage = curpage; this.pageSize = pageSize; this.total = total; } public Page() { } /** * 得到總頁數的方法 * * @return 總頁數 */ public int gettotalpage() { int totalpage = 0; // 記錄總頁數分別對每頁記錄個數進行除法和取餘 int m = total / pageSize; int n = total % pageSize; // 當結果存在餘數時則進行+1 totalpage = (n == 0) ? m : m + 1; return totalpage; } /** * 得到當前頁的方法 * * @return 當前頁 */ public int getcurpage() { // 得到總頁數 int totalpage = gettotalpage(); // 噹噹前頁小於1時重置爲1 if (curpage < 1) { curpage = 1; } // 噹噹前頁大於總頁數時重置爲總頁數 if (curpage > totalpage) { curpage = totalpage; } return curpage; } /** * 得到LIMIT的第一個參數的方法 * * @return 返回第一個參數 */ public int getStart() { // 得到總頁數 int curpage = getcurpage(); int pageStart = (curpage - 1) * pageSize; return pageStart; } }
allStu.jsp
<body> <h1 align="center" >學生信息表</h1> <table width="100%" height="30%" border="1" > <tr> <td>學生姓名</td> <td>年齡</td> <td>性別</td> <td>學校</td> <td>項目名</td> <td>代碼量</td> </tr> <c:forEach var="stu" items="${stulist }"> <tr> <td>${stu.stu_name }</td> <td>${stu.age }</td> <td>${stu.sex }</td> <td>${stu.school }</td> <td>${stu.pro_name }</td> <td>${stu.code }</td> </tr> </c:forEach> </table> <a href="<%=path %>/student/getAllStudentWithPage.do?curpage=1">首頁</a> <a href="<%=path %>/student/getAllStudentWithPage.do?curpage=${curpage-1 }">上一頁</a> <a href="<%=path %>/student/getAllStudentWithPage.do?curpage=${curpage+1 }">下一頁</a> <a href="<%=path %>/student/getAllStudentWithPage.do?curpage=${totalpage }">尾頁</a> </body>
在瀏覽器地址欄輸入:
http://localhost:8080/studentManager/student/getAllStudentWithPage.do?curpage=0