使用springmvc+mybatis實現增刪改查並進行登入註冊功能
一、第一次使用springmvc+mybatis整合出的框架,使用的是maven版本
1.使用maven有以下主要要建立maven資料夾,匯入maven包並進行配置環境變數,在後面的文章中會提到maven配置。使用maven主要是依賴其pom.xml配置檔案進行匯入jar包的操作,瀏覽器開啟:mvnrepository.com搜尋包就可以了,在<dependency>標籤中加入搜尋出的連結會自動進行下載。
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>wb.cn</groupId> <artifactId>springDemo</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>springDemo Maven Webapp</name> <url>http://maven.apache.org</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <spring.version>4.3.3.RELEASE</spring.version> <junit.version>4.12</junit.version> <aspectj.version>1.8.9</aspectj.version> <jackson.json.version>2.7.4</jackson.json.version> <fasterxml.jackson.version>2.7.4</fasterxml.jackson.version> <codehaus.woodstox.version>4.4.1</codehaus.woodstox.version> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>${junit.version}</version> <scope>test</scope> </dependency> <!-- servlet/ jstl --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> <scope>provided</scope> </dependency> <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.38</version> </dependency> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <!-- spring --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-oxm</artifactId> <version>${spring.version}</version> </dependency> <!-- jackson json --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>${jackson.json.version}</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>${jackson.json.version}</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> <version>${jackson.json.version}</version> </dependency> <!-- jackson xml --> <dependency> <groupId>com.fasterxml.jackson.dataformat</groupId> <artifactId>jackson-dataformat-xml</artifactId> <version>${fasterxml.jackson.version}</version> </dependency> <dependency> <groupId>org.codehaus.woodstox</groupId> <artifactId>woodstox-core-asl</artifactId> <version>${codehaus.woodstox.version}</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-validator</artifactId> <version>5.2.4.Final</version> </dependency> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.2</version> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>${aspectj.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${spring.version}</version> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${spring.version}</version> </dependency> <!-- mybatis --> <dependency> <groupId>com.mchange</groupId> <artifactId>c3p0</artifactId> <version>0.9.5.2</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.1</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.3.0</version> </dependency> <!-- 日誌 --> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.7.21</version> </dependency> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-core</artifactId> <version>1.1.7</version> </dependency> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-classic</artifactId> <version>1.1.7</version> </dependency> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-access</artifactId> <version>1.1.7</version> </dependency> <!-- https://mvnrepository.com/artifact/commons-dbutils/commons-dbutils --> <dependency> <groupId>commons-dbutils</groupId> <artifactId>commons-dbutils</artifactId> <version>1.6</version> </dependency> </dependencies> <build> <finalName>sprintmvc-mybaitis</finalName> <plugins> <plugin> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-maven-plugin</artifactId> <version>1.3.5</version> <configuration> <configurationFile>src/main/resources/generator.xml</configurationFile> <verbose>true</verbose> <overwrite>true</overwrite> </configuration> <dependencies> <dependency> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-core</artifactId> <version>1.3.5</version> </dependency> </dependencies> </plugin> </plugins> </build> </project>
2.在這裡使用的是mybatis程式碼生成器,可以生成出mapper、mapper.xml以及model層,具體使用配置在generator.xml中
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd"> <generatorConfiguration> <!-- java -jar mybatis-generator-core-1.3.2.jar -configfile generator.xml -overwrite --> <!-- 資料庫驅動包位置 --> <classPathEntry location="D:\maven\repository\mysql\mysql-connector-java\5.1.38\mysql-connector-java-5.1.38.jar" /> <!-- <classPathEntry location="C:\oracle\product\10.2.0\db_1\jdbc\lib\ojdbc14.jar" />--> <context id="DB2Tables" targetRuntime="MyBatis3"> <commentGenerator> <property name="suppressAllComments" value="true" /> </commentGenerator> <!-- 資料庫連結URL、使用者名稱、密碼 --> <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://127.0.0.1:3306/bpmx33" userId="root" password="123456"> <!--<jdbcConnection driverClass="oracle.jdbc.driver.OracleDriver" connectionURL="jdbc:oraclF:thin:@localhost:1521:orcl" userId="msa" password="msa">--> </jdbcConnection> <javaTypeResolver> <property name="forceBigDecimals" value="false" /> </javaTypeResolver> <!-- 生成實體類的包名和位置,這裡配置將生成的實體類放在me.gacl.domain這個包下 --> <javaModelGenerator targetPackage="lyb.cn.ssm.model" targetProject="C:\Users\Administrator\Desktop\springDeom\src\main\java"> <property name="enableSubPackages" value="true" /> <property name="trimStrings" value="true" /> </javaModelGenerator> <!-- 生成的SQL對映檔案包名和位置,這裡配置將生成的SQL對映檔案放在me.gacl.mapping這個包下 --> <sqlMapGenerator targetPackage="lyb.cn.ssm.mapper" targetProject="C:\Users\Administrator\Desktop\springDeom\src\main\java"> <property name="enableSubPackages" value="true" /> </sqlMapGenerator> <!-- 生成DAO的包名和位置,這裡配置將生成的dao類放在me.gacl.dao這個包下 --> <javaClientGenerator type="XMLMAPPER" targetPackage="lyb.cn.ssm.dao" targetProject="C:\Users\Administrator\Desktop\springDeom\src\main\java"> <property name="enableSubPackages" value="true" /> </javaClientGenerator> <!-- 要生成那些表(更改tableName和domainObjectName就可以) --> <table tableName="w_test" domainObjectName="Test" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false" /> </context> </generatorConfiguration>
配置好自己的表名,然後再右鍵pom.xml,選擇run as maven build path,輸入mybatis-generator:generate從而實現程式碼生成功能,其他mybatis.xml以及spring和springmvc配置檔案會在之後的原始碼中,可以進行參考。
3.之後就要自己建立controller層來進行控制層的功能
(1)在controller層遇到的問題及注意事項
a.要設定@controller註解,告訴springmvc這是控制類層,才可以讀取到該層
b.使用了@Autowired來進行自動注入了mapper層,具體@Autowired和@Resource區別可參考其他部落格
c.對於@RequestMapping的使用
我這次只使用了幾種方式,如@RequestMapping("方法名")、@RequestMapping(value="/方法名",method=RequestMethod.POST)後面加方法的這種,不過method方法在從前臺資料通過表單post方法傳遞過來時method寫post可以,但從後臺controller傳遞到前臺時寫post會報錯,不知道什麼原因,改為了get方法.而且當使用了後面跟method這種方法時,String型別的方法不能返回到頁面只能返回到controller方法中
4.Controller層方法
a. list方法,進行查詢出所有的資料返回到列表中
@RequestMapping("list")
public ModelAndView testList(ModelAndView m){
//System.out.println(t1.selectByPrimaryKey(10000000160001L));
List<Test> list = new ArrayList<Test>();
list = t1.selectList();
m.addObject("list", list);
m.addObject("test", "123");
for(int i = 0;i<list.size();i++){
System.out.println(list.get(i).getfXm());
}
m.setViewName("ui");
return m;
}
需要注意的,引數為ModelAndView進行引數的傳遞,t1為前面通過自動注入得到的mapper類,ModelAndView可以通過m.addObject來進行對list的傳遞,類似以前servlet中的setAttribute封裝,當使用ModelAndView時可以通過其方法m.setViewName(“”)來進行頁面的跳轉括號內為跳轉的頁面名稱,最後return返回的值為m;
在跳轉的ui.jsp採用的是easyui佈局結合css,其中接受值通過EL表示式
<div id="content" region="center" title="資料彙總"
style="padding: 20px; ">
<div>
<ul>
<a href="add1"><input type = "button" value = "新增"></a>
<a href="index"><input type = "button" value = "返回登入"></a>
</ul>
<table class="tablelist" style="width: 800px; height: 400px;"
data-options="rownumbers:true,singleSelect:true,selectOnCheck:false,checkOnSelect:false,pagination:true,pageSize:20,url:'',method:'get',striped:true,rowStyler:setRowBgColor">
<thead>
<tr>
<th>選擇</th>
<th>姓名</th>
<th>性別</th>
<th>年齡</th>
<th>愛好</th>
<th>日期</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<c:forEach items="${list}" var="Bean">
<tr class="odd">
<td><input type="radio" name="Id" value="${Bean.id }"></td>
<td><a href="edit?id=${Bean.id}" dir="ltr" title="點選檢視詳情"
onclick="">${Bean.fXm }</a></td>
<td>${Bean.fXb }</td>
<td>${Bean.fNl }</td>
<td>${Bean.fDxk }</td>
<%-- <td>${Bean.fRq }</td> --%>
<td><fmt:formatDate value="${Bean.fRq}" pattern="yyyy-MM-dd" />
</td>
<td><a href="del?id=${Bean.id}" dir="ltr" onclick="">刪除</a></td>
</tr>
</c:forEach>
<c:if test="${empty list}">
<tr class="odd">
<td colspan="5" align="center">沒有查詢到相關記錄!</td>
</tr>
</c:if>
</tbody>
</table>
</div>
</div>
b.編輯方法edit,前臺點選名字傳遞一個a標籤的href指向一個edit方法,跳轉到了controller中的edit方法,同時把該條資訊的id傳遞過來
@RequestMapping(value="/edit",method=RequestMethod.GET)
public ModelAndView edit(Long id,ModelAndView m,HttpServletRequest request) throws Exception
{
System.out.println("進入edit方法");
//String fXm = request.getParameter("fXm");
Test t = t1.selectByPrimaryKey(id);
m.setViewName("edit");
m.addObject("t", t);
System.out.println(t);
return m;
}
對應的mapper是通過id查詢資訊的dao方法,返回一個物件,並跳轉到edit頁面中
<div class="row-fluid">
<div class="span12">
<form action="save" method="post">
<fieldset>
<legend>id</legend> <input type="text" name="id" value="${t.id} " />
<legend>名稱</legend> <input type="text" name="fXm" value="${t.fXm}"/>
<legend>性別</legend> <input type="text" name="fXb" value="${t.fXb }"/>
<legend>年齡</legend> <input type="text" name="fNl" value="${t.fNl }"/>
<legend>日期</legend> <input type="text" name="fRq" value="<fmt:formatDate value="${t.fRq}" pattern="yyyy-MM-dd" />"/>
<legend>愛好</legend> <input type="text" name="fDxk" value="${t.fDxk }"/>
<button type="submit" class="btn">提交</button>
</fieldset>
</form>
</div>
</div>
在一個form表單中得到通過物件.出來的資訊,然後跳轉到controller層中的save方法進行修改操作儲存
@RequestMapping(value="/save",method=RequestMethod.POST)
public String save(ModelAndView m,Test t){
t1.updateByPrimaryKeySelective(t);
//t1.updateByPrimaryKey(t);
System.out.println("執行了更新方法");
// t1.insert(t);
//t1.updateByPrimaryKey(t);
//m.setViewName("list");
//m.addObject("", attributeValue)
return "redirect:list";
}
這裡是進行了一個通過物件來執行更新操作。之後return的方法redirect意思是跳轉到controller中的方法list,又進行一次查詢列表的操作。c.新增操作add1,在前面ui.jsp頁面有連結指向新增操作,為add1
@RequestMapping(value="/add1",method=RequestMethod.GET)
public ModelAndView add1(ModelAndView m,Test t){
System.out.println("進入了add1方法");
m.setViewName("add");
m.addObject(t);
return m;
}
這時跳轉到了add.jsp頁面中
<form action="add" method="post">
<fieldset>
<legend>id</legend> <input type="text" name="id" />
<legend>名稱</legend> <input type="text" name="fXm" />
<legend>性別</legend> <input type="text" name="fXb" />
<legend>年齡</legend> <input type="text" name="fNl" />
<legend>愛好</legend> <input type="text" name="fDxk" />
<legend>日期</legend> <input type="text" name="fRq" value="<fmt:formatDate value="${t.fRq}" pattern="yyyy-MM-dd" />"/>
<button type="submit" class="btn">提交</button>
</fieldset>
</form>
提交的form action為add方法
@RequestMapping(value="/add",method=RequestMethod.POST)
public String add(ModelAndView m,Test t){
t1.insert(t);
//日期格式的新增問題
return "redirect:list";
}
執行了insert方法,增加的為一個物件,並返回到list方法中
d.刪除操作del方法
@RequestMapping("del")//刪除操作
public String del(ModelAndView m,Test t){
t1.deleteByPrimaryKey(t.getId());
return "redirect:list";
}
問題存在有開了一個頁面
e.登入註冊功能
由於資料庫表是之前的,所以欄位中沒有password,暫時使用性別來進行當做密碼來進行識別。
@RequestMapping("index")//
public String index(ModelAndView m,Test t){
//t1.deleteByPrimaryKey(t.getId());
return "login";
}
設定一個主的登入介面跳轉到login.jsp頁面進行登入
<form action="login" method="post">
<fieldset>
<a href="add1"><input type = "button" value = "註冊"></a>
<h3>請輸入您的名字,性別進行驗證(測試性別相當於密碼)</h3>
<legend>名稱</legend> <input type="text" name="fXm" />
<legend>性別</legend> <input type="text" name="fXb" />
<button type="submit" class="btn">提交</button>
</fieldset>
</form>
點選提交跳轉到controller中的login方法
@RequestMapping("login")
public String login(Test t){
String fXm = t.getfXm();
String fXb = t.getfXb();
Test test = t1.selectName(fXm);
System.out.println(test+"mapper");
System.out.println(fXb+"jsp");
if(test!=null){
if(fXb.equals(test.getfXb())){
return "redirect:list";
}
else{
return "error";
}
}else{
return "error";
}
}
這時傳遞過來的引數是前臺傳的一個實體,然後通過實體.get得到需要的欄位值,對應mapper中有一個返回實體的方法
<select id="selectName" resultMap="BaseResultMap">
select * from w_test where F_xm=#{fXm,jdbcType=VARCHAR}
</select>
通過前臺的fXm在資料庫中找到其相應的性別(相當於密碼),返回一個數據的實體test,為了防止空指標異常,進行if非空判斷,然後判斷前臺的性別和資料庫查出來的性別test.getfXb()是否一致來決定返回的路徑
之後的註冊功能實際上是又呼叫了一次增加方法。
部分功能如跳轉問題,攔截器問題,非空校驗還沒有完善,之後會進行補充。
資料庫圖