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";
    }
}
View Code

 

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);
}
View Code

 

<?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>
View Code

 

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;
    }
    
    
}
View Code

 

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);
}
View Code

 

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);
    }

}
View Code

 

框架的配置

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>
View Code

 

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>
View Code

 

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>
View Code

 

<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>
View Code

 

<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>
View Code

 

<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>
View Code

 

數據庫文件和日誌文件配置

jdbc.driver=com.microsoft.sqlserver.jdbc.SQLServerDriver
jdbc.url=jdbc:sqlserver://localhost:1433;DatabaseName=stumes
jdbc.username=sa
jdbc.password=123
View Code

 

# 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
View Code

 

視圖層

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;
}
View Code

 

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);
});
View Code

 

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>
View Code

 

<%@ 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="修改">&nbsp;&nbsp;<input type="reset" value="重置"></th>
            </tr>
        </table>
</form>
</body>
</html>
View Code

 

<%@ 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>
View Code

 

<%@ 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>
View Code

 

運行結果截圖

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章