SSM搭建整合(Maven專案)第一篇 外加增刪改查
一、 首先我們得先建一個Maven專案,可以參考我這篇文章:https://blog.csdn.net/qq_38000902/article/details/79565136
建後以下目錄,你會發現IDEA識別不了,我們得設定讓IDEA識別一下:
開啟File裡面的Project structure設定
分別設定識別如下:
點選Apply,再點選ok退出設定
二、接著在pom檔案映入jar,修改後如下:
<?xml version="1.0" encoding="UTF-8"?> <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/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.lvzh</groupId> <artifactId>MyTestAllMyBatis</artifactId> <version>1.0-SNAPSHOT</version> <packaging>war</packaging> <name>MyTestAllMyBatis Maven Webapp</name> <!-- FIXME change it to the project's website --> <url>http://www.example.com</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>1.7</maven.compiler.source> <maven.compiler.target>1.7</maven.compiler.target> <!-- spring版本號 --> <spring.version>4.0.2.RELEASE</spring.version> <!-- mybatis版本號 --> <mybatis.version>3.2.6</mybatis.version> <!-- log4j日誌檔案管理包版本 --> <slf4j.version>1.7.7</slf4j.version> <log4j.version>1.2.17</log4j.version> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <!-- 表示開發的時候引入,釋出的時候不會載入此包 --> <scope>test</scope> </dependency> <!-- <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> </dependency> --> <!-- spring核心包 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</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-oxm</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</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-aop</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${spring.version}</version> </dependency> <!-- mybatis核心包 --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>${mybatis.version}</version> </dependency> <!-- mybatis/spring包 --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.2.2</version> </dependency> <!-- 匯入java ee jar 包 --> <dependency> <groupId>javax</groupId> <artifactId>javaee-api</artifactId> <version>8.0</version> </dependency> <!-- 匯入Mysql資料庫連結jar包 --> <!--<dependency>--> <!--<groupId>mysql</groupId>--> <!--<artifactId>mysql-connector-java</artifactId>--> <!--<version>5.1.36</version>--> <!--</dependency>--> <!-- 匯入oracle資料庫連結jar包 --> <dependency> <groupId>com.oracle</groupId> <artifactId>ojdbc6</artifactId> <version>11.2.0.1.0</version> </dependency> <!-- 資料庫連線池 --> <dependency> <groupId>com.mchange</groupId> <artifactId>c3p0</artifactId> <version>0.9.5.2</version> </dependency> <!-- 匯入dbcp的jar包,用來在applicationContext.xml中配置資料庫 --> <dependency> <groupId>commons-dbcp</groupId> <artifactId>commons-dbcp</artifactId> <version>1.2.2</version> </dependency> <!-- JSTL標籤類 --> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <!-- 日誌檔案管理包 --> <!-- log start --> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>${log4j.version}</version> </dependency> <!-- 格式化物件,方便輸出日誌 --> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.1.41</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>${slf4j.version}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>${slf4j.version}</version> </dependency> <!-- log end --> <!-- 映入JSON --> <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-mapper-asl</artifactId> <version>1.9.13</version> </dependency> <!-- 上傳元件包 --> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.1</version> </dependency> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.4</version> </dependency> <dependency> <groupId>commons-codec</groupId> <artifactId>commons-codec</artifactId> <version>1.9</version> </dependency> <!-- 引入Mybatis分頁外掛 --> <!-- 分頁 --> <dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper</artifactId> <version>4.1.5</version> </dependency> </dependencies> <build> <finalName>MyTestAllMyBatis</finalName> <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) --> <plugins> <plugin> <artifactId>maven-clean-plugin</artifactId> <version>3.0.0</version> </plugin> <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging --> <!-- 資原始檔拷貝外掛 --> <plugin> <artifactId>maven-resources-plugin</artifactId> <version>3.0.2</version> <configuration> <encoding>UTF-8</encoding> </configuration> </plugin> <!-- java編譯外掛 --> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.7.0</version> </plugin> <plugin> <artifactId>maven-surefire-plugin</artifactId> <version>2.20.1</version> </plugin> <plugin> <artifactId>maven-war-plugin</artifactId> <version>3.2.0</version> </plugin> <plugin> <artifactId>maven-install-plugin</artifactId> <version>2.5.2</version> </plugin> <plugin> <artifactId>maven-deploy-plugin</artifactId> <version>2.8.2</version> </plugin> <!-- 配置Tomcat外掛 --> <plugin> <groupId>org.apache.tomcat.maven</groupId> <artifactId>tomcat7-maven-plugin</artifactId> <version>2.2</version> <configuration> <port>8080</port> <path>/</path> </configuration> </plugin> </plugins> </pluginManagement> <!--解決Intellij構建專案時,target/classes目錄下不存在mapper.xml檔案--> <resources> <resource> <directory>src/main/java</directory> <includes> <include>**/*.xml</include> </includes> <filtering>true</filtering> </resource> </resources> <plugins> <plugin> <groupId>org.mortbay.jetty</groupId> <artifactId>maven-jetty-plugin</artifactId> <version>6.1.7</version> <configuration> <connectors> <connector implementation="org.mortbay.jetty.nio.SelectChannelConnector"> <port>8888</port> <maxIdleTime>30000</maxIdleTime> </connector> </connectors> <webAppSourceDirectory>${project.build.directory}/${pom.artifactId}-${pom.version} </webAppSourceDirectory> <contextPath>/</contextPath> </configuration> </plugin> </plugins> </build> </project>
三、整合SpringMvc
新建一個配置檔案spring-mvc.xml在resources資料夾下並配置如下:
<?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" xmlns:aop="http://www.springframework.org/schema/aop" 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-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"> <!-- 掃描web相關的bean --> <context:component-scan base-package="com.blast.user.controller"/> <!-- 開啟SpringMVC註解模式 --> <mvc:annotation-driven/> <!-- 靜態資源預設servlet配置 --> <mvc:default-servlet-handler/> <!--避免IE執行AJAX時,返回JSON出現下載檔案 --> <bean id="mappingJacksonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"> <property name="supportedMediaTypes"> <list> <value>text/html;charset=UTF-8</value> </list> </property> </bean> <!-- 啟動SpringMVC的註解功能,完成請求和註解POJO的對映 --> <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> <property name="messageConverters"> <list> <ref bean="mappingJacksonHttpMessageConverter" /> <!-- JSON轉換器 --> </list> </property> </bean> <!-- 配置檔案上傳,如果沒有使用檔案上傳可以不用配置,當然如果不配,那麼配置檔案中也不必引入上傳元件包 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!-- 預設編碼 --> <property name="defaultEncoding" value="utf-8" /> <!-- 檔案大小最大值 --> <property name="maxUploadSize" value="10485760000" /> <!-- 記憶體中的最大值 --> <property name="maxInMemorySize" value="40960" /> <!-- 啟用是為了推遲檔案解析,以便捕獲檔案大小異常 --> <property name="resolveLazily" value="true"/> </bean> <!-- 配置ViewResolver 。可用多個ViewResolver 。使用order屬性排序。 InternalResourceViewResolver 放在最後--> <bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver"> <property name="order" value="1"></property> <property name="mediaTypes"> <map> <!-- 告訴檢視解析器,返回的型別為json格式 --> <entry key="json" value="application/json" /> <entry key="xml" value="application/xml" /> <entry key="htm" value="text/htm" /> </map> </property> <property name="defaultViews"> <list> <!-- ModelAndView裡的資料變成JSON --> <bean class="org.springframework.web.servlet.view.json.MappingJacksonJsonView" /> </list> </property> <property name="ignoreAcceptHeader" value="true"></property> </bean> <!-- 定義跳轉的檔案的前後綴 ,檢視模式配置--> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <!-- 這裡的配置我的理解是自動給後面action的方法return的字串加上字首和字尾,變成一個 可用的url地址 --> <!--<property name="prefix" value="/WEB-INF/jsp/" />--> <property name="prefix" value="/WEB-INF/userjsp/" /> <property name="suffix" value=".jsp" /> </bean> </beans>
四、接著配置web.xml檔案
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1"> <!-- 編碼過濾器 --> <filter> <filter-name>encodingFilter</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> <!-- 處理響應亂碼 --> <init-param> <param-name>forceEncoding</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>encodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!--配置SpringMVC核心控制器--> <!-- 配置springMVC分發器 DispatcherServlet 預設載入WEB-INF下的 《servlet-name》-servlet.xml配置檔案====》spring-mvc.xml --> <servlet> <servlet-name>SpringMVC</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!-- 配置springMVC需要載入的配置檔案 通過初始化引數指定配置檔案 然後就跟servlet-name中的值沒有關係了--> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring/spring-mvc.xml</param-value> </init-param> <!-- 大於等於1時,啟動服務時例項化/初始化 --> <load-on-startup>1</load-on-startup> <async-supported>true</async-supported> </servlet> <servlet-mapping> <servlet-name>SpringMVC</servlet-name> <!-- 匹配所有請求,此處也可以配置成 *.do 形式 --> <url-pattern>/</url-pattern> </servlet-mapping> <!-- spring的初始化配置 通過listener標籤載入spring配置檔案 預設到WEB-INF下載入名字叫applicationContext.xml --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- 防止Spring記憶體溢位監聽器 --> <listener> <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class> </listener> <!-- log4j配置 --> <context-param> <param-name>log4jConfigLocation</param-name> <param-value>classpath:properties/log4j.properties</param-value> </context-param> <listener> <listener-class>org.springframework.web.util.Log4jConfigListener </listener-class> </listener> <!-- 配置logback --> <context-param> <param-name>logbackConfigLocation</param-name> <param-value>classpath:logback.xml</param-value> </context-param> <!-- 通過context-param標籤,載入指定的配置檔案 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring/applicationContext.xml</param-value> </context-param> <!--設定session無操作5分鐘後銷燬--> <!-- <session-config> <session-timeout>5</session-timeout> </session-config>--> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>
五、接著配置logback.xml檔案
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration SYSTEM "http://toolkit.alibaba-inc.com/dtd/log4j/log4j.dtd">
<log4j:configuration xmlns:log4j='http://jakarta.apache.org/log4j/'
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://jakarta.apache.org/log4j/ ">
<!-- ===================================================================== -->
<!-- 定義全域性輸出介面卡 -->
<!-- ===================================================================== -->
<appender name="consoleAppender" class="org.apache.log4j.ConsoleAppender">
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="[%d{yyyy-MM-dd HH:mm:ss.SSS}]-[%c]-[%t] %x - %m%n"/>
</layout>
</appender>
<!-- Mybatis and SQL -->
<logger name="org.apache.ibatis" additivity="true">
<level value="DEBUG"/>
<appender-ref ref="consoleAppender"/>
</logger>
<logger name="org.mybatis.spring" additivity="true">
<level value="ERROR"/>
<appender-ref ref="consoleAppender"/>
</logger>
<logger name="java.sql" additivity="true">
<level value="DEBUG"/>
<appender-ref ref="consoleAppender"/>
</logger>
<logger name="java.sql.Connection" additivity="true">
<level value="DEBUG"/>
<appender-ref ref="consoleAppender"/>
</logger>
<logger name="java.sql.Statement" additivity="true">
<level value="DEBUG"/>
<appender-ref ref="consoleAppender"/>
</logger>
<logger name="java.sql.PreparedStatement" additivity="true">
<level value="DEBUG"/>
<appender-ref ref="consoleAppender"/>
</logger>
<!-- Spring -->
<logger name="org.springframework" additivity="true">
<level value="ERROR"/>
<appender-ref ref="consoleAppender"/>
</logger>
<!-- ActiveMQ -->
<logger name="org.apache.activemq" additivity="true">
<level value="ERROR"/>
<appender-ref ref="consoleAppender"/>
</logger>
<!-- ===================================================================== -->
<!-- 根日誌記錄器 -->
<!-- ===================================================================== -->
<root>
<level value="DEBUG"/>
<appender-ref ref="consoleAppender"/>
</root>
</log4j:configuration>
六、接著配置log4j.properties檔案
#定義LOG輸出級別
log4j.rootLogger=INFO,Console,File
#定義日誌輸出目的地為控制檯
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.Target=System.out
#可以靈活地指定日誌輸出格式,下面一行是指定具體的格式
log4j.appender.Console.layout = org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=[%c] - %m%n
#檔案大小到達指定尺寸的時候產生一個新的檔案
log4j.appender.File = org.apache.log4j.RollingFileAppender
#指定輸出目錄
log4j.appender.File.File = logs/ssm.log
#定義檔案最大大小
log4j.appender.File.MaxFileSize = 10MB
# 輸出所以日誌,如果換成DEBUG表示輸出DEBUG以上級別日誌
log4j.appender.File.Threshold = ALL
log4j.appender.File.layout = org.apache.log4j.PatternLayout
log4j.appender.File.layout.ConversionPattern =[%p] [%d{yyyy-MM-dd HH\:mm\:ss}][%c]%m%n
七、接著配置jdbc.properties檔案
#jdbc.driver=com.mysql.jdbc.Driver
jdbc.driver=oracle.jdbc.OracleDriver
#資料庫地址
#jdbc.url=jdbc:mysql://xxxxxxxxx:3306/ChatRobot?useUnicode=true&characterEncoding=utf8
jdbc.url=jdbc\:oracle\:thin\:@localhost\:1521:orcl
#使用者名稱
jdbc.username=xxxx
#密碼
jdbc.password=xxxxx
#最大連線數
c3p0.maxPoolSize=30
#最小連線數
c3p0.minPoolSize=10
#關閉連線後不自動commit
c3p0.autoCommitOnClose=false
#獲取連線超時時間
c3p0.checkoutTimeout=10000
#當獲取連線失敗重試次數
c3p0.acquireRetryAttempts=2
八、配置applicationContext.xml檔案
<?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:tx="http://www.springframework.org/schema/tx"
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/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- 開啟註解 掃描service包下所有使用註解的型別 -->
<context:annotation-config/>
<context:component-scan base-package="com.blast.user.service"/>
<!-- 配置資料庫相關引數properties的屬性:${url} -->
<context:property-placeholder location="classpath:properties/jdbc.properties"/>
<!-- 資料庫連線池 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driver}"/>
<property name="jdbcUrl" value="${jdbc.url}"/>
<property name="user" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
<property name="maxPoolSize" value="${c3p0.maxPoolSize}"/>
<property name="minPoolSize" value="${c3p0.minPoolSize}"/>
<property name="autoCommitOnClose" value="${c3p0.autoCommitOnClose}"/>
<property name="checkoutTimeout" value="${c3p0.checkoutTimeout}"/>
<property name="acquireRetryAttempts" value="${c3p0.acquireRetryAttempts}"/>
</bean>
<!-- 配置SqlSessionFactory物件 mybatis整合spring-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 注入資料庫連線池 -->
<property name="dataSource" ref="dataSource"/>
<!-- 掃描model包 使用別名 -->
<property name="typeAliasesPackage" value="com.blast.user.model"/>
<!-- 載入對映檔案 -->
<!-- 掃描sql配置檔案:mapper需要的xml檔案 -->
<property name="mapperLocations">
<!-- 載入的是路徑 -->
<list>
<value>classpath:com/blast/*/sql/*.xml</value>
</list>
</property>
</bean>
<!-- 配置掃描Dao介面包,動態實現Dao介面,注入到spring容器中 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 注入sqlSessionFactory -->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
<!-- 給出需要掃描Dao介面包 -->
<property name="basePackage" value="com.blast.user.dao"/>
</bean>
<!-- 配置事務管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!-- 注入資料庫連線池 -->
<property name="dataSource" ref="dataSource"/>
</bean>
<!-- 配置基於註解的宣告式事務 -->
<tx:annotation-driven transaction-manager="transactionManager"/>
</beans>
九、設定sqlConfig檔案:
<?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.blast.user.model" />
</typeAliases>
<!-- <mappers>
<mapper resource="com.blast.user.dao"/>
</mappers>-->
<!-- mybatis分頁外掛 -->
<plugins>
<plugin interceptor="com.github.pagehelper.PageHelper"></plugin>
</plugins>
</configuration>
接下來是測試,首先建立測試的表格,sql語句如下:
CREATE TABLE USER_TEST(ID NUMBER(11) NOT NULL PRIMARY KEY,
USERNAME varchar(40) NOT NULL,
PASSWORD varchar(255) NOT NULL,
EMAIL varchar(255) NOT NULL,
ROLE varchar(255) NOT NULL ,
STATUS NUMBER(1) NOT NULL ,
REGTIME DATE NOT NULL ,
REGIP varchar(255) NOT NULL);
--註釋
---------------------
-- ----------------------------
--插入資料
-- ----------------------------
INSERT INTO USER_TEST VALUES ('1', '克里斯', '987654','[email protected]', '超級管理員','0', to_date('2018-03-28 09:40:31', 'YYYY-MM-DD HH24:MI:SS'),'127.0.0.1');
INSERT INTO USER_TEST VALUES ('2', '艾克特里', '123456','[email protected]', '普通使用者','0', to_date('2018-03-29 09:40:31', 'YYYY-MM-DD HH24:MI:SS'), '127.0.0.1');
接著建立測試類,首先是UserController:
package com.blast.user.controller;
import com.blast.user.model.User;
import com.blast.user.service.IUserService;
import org.codehaus.jackson.map.ObjectMapper;
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 org.springframework.web.bind.annotation.RequestParam;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.UUID;
@Controller
@RequestMapping("/user")
public class UserController {
/**
* 查詢全部並跳到使用者管理介面
* @param pn
* @param model
* @return
*/
@Autowired
private IUserService userService;
@RequestMapping("userInfo")
public String getUsers(@RequestParam(value="pn",defaultValue="1")Integer pn, Model model){
//從第一條開始 每頁查詢五條資料
PageHelper.startPage(pn, 5);
List<User> users = userService.selectAllUser();
//將使用者資訊放入PageInfo物件裡
PageInfo page = new PageInfo(users,5);
model.addAttribute("pageInfo", page);
return "queryuser";
}
/**
* 測試用
* @param
* @throws IOException
*/
@RequestMapping("/showUser.do")
public void selectUser(HttpServletRequest request, HttpServletResponse response) throws IOException {
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
Integer id = Integer.parseInt(request.getParameter("id"));
User users = this.userService.selectUserById(id);
ObjectMapper mapper = new ObjectMapper();
response.getWriter().write(mapper.writeValueAsString(users));
response.getWriter().close();
}
/**
* 測試用
* @param id
* @param request
* @param response
* @param model
* @return
* @throws IOException
*/
@RequestMapping("/getUser")
public String getUser(int id,HttpServletRequest request,HttpServletResponse response,Model model)throws IOException{
try {
request.setAttribute("user", userService.selectUserById(id));
// List<User> Users = this.userService.selectUserById(id);
// ObjectMapper mapper = new ObjectMapper();
// response.getWriter().write(mapper.writeValueAsString(Users));
// response.getWriter().close();
model.addAttribute("user", userService.selectUserById(id));
// System.out.println(model.addAttribute("user", userService.selectUserById(id)));
}catch (Exception e){
e.printStackTrace();
}
return "editUser";
}
/**
*跳轉到新增使用者介面
*/
@RequestMapping("toAddUser")
public String toAddUser(){
return "addUser";
}
/**
* 新增使用者並重定向
* @param
*/
@RequestMapping("addUser")
public String addUser(User user){
UUID uuid= UUID.randomUUID();
if(user != null){
userService.addUser(user);
}
return "redirect:/user/userInfo";
}
/**
* 根據id刪除使用者
* @param id
* @param
* @param
*/
// @RequestMapping("/delUser")
// public String deleteUser(int id,Model model){
//
// userService.deleteUser(id);
// return "redirect:/user/userInfo";
// }
@RequestMapping("/delUser")
public String deleteUser(Integer id,Model model){
model.addAttribute("user", userService.deleteUser(id));
return "redirect:/user/userInfo";
}
@RequestMapping("updateUser")
public String UpdateUser(Model model,User user){
if(userService.updateUser(user)){
user = (User) userService.selectUserById(user.getId());
model.addAttribute("user", user);
return "redirect:/user/userInfo";
}
return "/error";
}
}
接著是IUserDao:
package com.blast.user.dao;
import com.blast.user.model.User;
import java.util.List;
public interface IUserDao {
List<User> selectAllUser();
User selectUserById(Integer id);
void addUser(User user);
boolean deleteUser(Integer id);
boolean updateUser(User user);
}
接著是User類:
package com.blast.user.model;
import java.util.Date;
public class User {
private Integer id;
private String email;
private String password;
private String username;
private String role;
private int status;
private Date regTime;
private String regIp;
@Override
public String toString() {
return "User{" +
"id=" + id +
", email='" + email + '\'' +
", password='" + password + '\'' +
", username='" + username + '\'' +
", role='" + role + '\'' +
", status=" + status +
", regTime=" + regTime +
", regIp='" + regIp + '\'' +
'}';
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public Date getRegTime() {
return regTime;
}
public void setRegTime(Date regTime) {
this.regTime = regTime;
}
public String getRegIp() {
return regIp;
}
public void setRegIp(String regIp) {
this.regIp = regIp;
}
}
接著是IUserServer類:
package com.blast.user.service;
import com.blast.user.model.User;
import java.util.List;
public interface IUserService {
public List<User> selectAllUser();
public User selectUserById(Integer id);
public void addUser(User user);
public boolean deleteUser(Integer id);
public boolean updateUser(User user);
}
再接著是UserServiceImpl類:
package com.blast.user.service.impl;
import com.blast.user.dao.IUserDao;
import com.blast.user.model.User;
import com.blast.user.service.IUserService;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
@Service("userService")
public class UserServiceImpl implements IUserService {
@Resource
private IUserDao userDao;
public List<User> selectAllUser(){
return this.userDao.selectAllUser();
}
public User selectUserById(Integer id) {
return this.userDao.selectUserById(id);
}
@Override
public void addUser(User user) {
userDao.addUser(user);
}
@Override
public boolean deleteUser(Integer id) {
return userDao.deleteUser(id);
}
@Override
public boolean updateUser(User user) {
return userDao.updateUser(user);
}
}
接著是UserDao.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">
<!-- 設定為IUserDao介面方法提供sql語句配置 -->
<mapper namespace="com.blast.user.dao.IUserDao">
<select id="selectAllUser" resultType="User">
SELECT * FROM USER_TEST
</select>
<select id="selectUserById" parameterType="Integer" resultType="User">
SELECT * FROM USER_TEST WHERE id = #{id}
</select>
<!-- 新增 -->
<insert id="addUser" parameterType="User">
insert into USER_TEST(USERNAME,PASSWORD) values (#{username},#{password})
</insert>
<!-- 刪除 -->
<insert id="deleteUser" parameterType="Integer">
DELETE USER_TEST WHERE id = #{id}
</insert>
<!-- 修改 -->
<update id="updateUser" parameterType="User" >
update USER_TEST set username=#{username},password=#{password} where id=#{id}
</update>
</mapper>
新建個測試類,測試mybatis:
import com.blast.user.model.User;
import com.blast.user.service.IUserService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.util.List;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({"classpath:spring/applicationContext.xml"})
public class IUserDaoTest {
@Autowired
private IUserService userService;
@Test
public void selectUser() {
Integer id = 1;
User student = userService.selectUserById(id);
System.out.println("使用者名稱:"+student.toString());
}
}
執行,說明Mybatis:
接下來是前端頁面,首先是主頁面index.jsp:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
pageContext.setAttribute("path", request.getContextPath());
%>
<!DOCTYPE html>
<html>
<head>
<title>首頁</title>
<style type="text/css">
a {
text-decoration: none;
color: #fff;
font-size: 14px;
}
h3 {
width: 180px;
height: 38px;
margin: 100px auto;
text-align: center;
line-height: 38px;
background: #5BC0DE;
border-radius: 4px;
}
</style>
</head>
<body>
<h3>
<a href="${path }/user/userInfo">進入使用者管理頁</a>
</h3>
</body>
</html>
接著是查詢頁面queryuser.jsp:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%
pageContext.setAttribute("path", request.getContextPath());
%>
<!DOCTYPE HTML>
<html>
<head>
<title>使用者列表</title>
<link
href="${path}/MyStyle/bootstrap-3.3.7-dist/css/bootstrap.min.css"
rel="stylesheet">
<script type="text/javascript"
src="${path}/MyStyle/jquery-3.3.1/jquery-3.3.1.min.js"></script>
<script type="text/javascript"
src="${path}/MyStyle/bootstrap-3.3.7-dist/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<!-- 標題 -->
<div class="row">
<div class="col-md-12">
<h1>使用者管理</h1>
</div>
</div>
<!-- 按鈕 -->
<div class="row">
<div class="col-md-4 col-md-offset-8">
<a class="btn btn-primary" href="${path}/user/toAddUser">新增</a>
</div>
</div>
<!-- 表格 -->
<div class="row">
<div class="col-md-12">
<table class="table table-hover">
<tr>
<th>id</th>
<th>使用者名稱</th>
<th>註冊時間</th>
<th>操作</th>
</tr>
<c:forEach items="${pageInfo.list }" var="user">
<tr>
<td>${user.id}</td>
<td>${user.username }</td>
<td>${user.regTime }</td>
<!-- <td><a class="edit">編輯</a> <a
class="delete">刪除</a></td> -->
<td>
<a type="button" href="${path}/user/getUser?id=${user.id}" class="btn btn-info btn-sm">
<span class="glyphicon glyphicon-pencil" aria-hidden="true"></span>編輯</a>
<a type="button" href="${path}/user/delUser?id=${user.id}" class="btn btn-danger btn-sm">
<span class="glyphicon glyphicon-trash" aria-hidden="true" ></span>刪除</a>
</td>
</tr>
</c:forEach>
</table>
</div>
</div>
<hr style="height:1px;border:none;border-top:1px solid #ccc;" />
<!-- 分頁導航欄 -->
<!-- 分頁資訊 -->
<div class="row">
<!-- 分頁文字資訊,其中分頁資訊都封裝在pageInfo中 -->
<div class="col-md-6">
當前第:${pageInfo.pageNum}頁,總共:${pageInfo.pages}頁,總共:${pageInfo.total}條記錄
</div>
<!-- 分頁條 -->
<div class="col-md-6">
<nav aria-label="Page navigation">
<ul class="pagination">
<li><a href="${path}/user/userInfo?pn=1">首頁</a></li>
<c:if test="${pageInfo.hasPreviousPage }">
<li>
<a href="${path}/user/userInfo?pn=${pageInfo.pageNum-1}" aria-label="Previous">
<span aria-hidden="true">«</span>
</a>
</li>
</c:if>
<c:forEach items="${pageInfo.navigatepageNums }" var="page_Num">
<c:if test="${page_Num == pageInfo.pageNum }">
<li class="active"><a href="#">${ page_Num}</a></li>
</c:if>
<c:if test="${page_Num != pageInfo.pageNum }">
<li><a href="${path}/user/userInfo?pn=${ page_Num}">${ page_Num}</a></li>
</c:if>
</c:forEach>
<c:if test="${pageInfo.hasNextPage }">
<li>
<a href="${path}/user/userInfo?pn=${pageInfo.pageNum+1}" aria-label="Next">
<span aria-hidden="true">»</span>
</a>
</li>
</c:if>
<li><a href="${path}/user/userInfo?pn=${pageInfo.pages}">末頁</a></li>
</ul>
</nav>
</div>
</div>
</div>
</body>
</html>
再接著新增頁面addUser.jsp:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%String path = request.getContextPath();
String basePath = request.getScheme() + "://"
+ request.getServerName() + ":" + request.getServerPort()
+ path + "/";%>
<%pageContext.setAttribute("path", request.getContextPath());%>
<html>
<head>
<title>新增使用者</title>
<title>使用者列表</title>
<link
href="${path}/MyStyle/bootstrap-3.3.7-dist/css/bootstrap.min.css"
rel="stylesheet">
<script type="text/javascript"
src="${path}/MyStyle/jquery-3.3.1/jquery-3.3.1.min.js"></script>
<script type="text/javascript"
src="${path}/MyStyle/bootstrap-3.3.7-dist/js/bootstrap.min.js"></script>
</head>
<body>
<h1>新增使用者</h1>
<form action="" name="userForm">
姓名:<input type="text" name="username"><br>
密碼:<input type="text" name="password"><br>
<input type="button" value="新增" class="btn btn-info btn-sm"
onclick="addUser()">
</form>
<script type="text/javascript">
function addUser() {
var form = document.forms[0];
form.action = "<%=basePath %>user/addUser";
form.method = "post";
form.submit();
}
</script>
</body>
</html>
再接著是修改頁面editUser.jsp:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://"
+ request.getServerName() + ":" + request.getServerPort()
+ path + "/";
%>
<%
pageContext.setAttribute("path", request.getContextPath());
%>
<!DOCTYPE html>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html>
<head>
<title>編輯使用者</title>
<link
href="${path}/MyStyle/bootstrap-3.3.7-dist/css/bootstrap.min.css"
rel="stylesheet">
<script type="text/javascript"
src="${path}/MyStyle/jquery-3.3.1/jquery-3.3.1.min.js"></script>
<script type="text/javascript"
src="${path}/MyStyle/bootstrap-3.3.7-dist/js/bootstrap.min.js"></script>
<script type="text/javascript">
function updateUser() {
var form = document.forms[0];
form.action = "<%=basePath %>user/updateUser";
form.method = "post";
form.submit();
}
</script>
</head>
<body>
<h1>編輯使用者</h1>
<form action="" name="userForm">
<input type="hidden" name="id" value="${user.id}" />
姓名:
<input
type="text" name="username" value=${user.username} /> 密碼:
<input
type="text" name="password" value=${user.password} />
<input type="button" class="btn btn-info btn-sm" value="儲存" onclick="updateUser()" />
</form>
</body>
</html>
還有插入資料時,id實現自增:
建立自動增長序列 :
create sequence my_test_seq minvalue 1 maxvalue 99999999
increment by 1
start with 1;
建立觸發器 :
create or replace trigger my_test_seq
before insert on USER_TEST /*觸發條件:當向表USER_TEST執行插入操作時觸發此觸發器*/
for each row /*對每一行都檢測是否觸發*/
begin /*觸發器開始*/
select my_test_seq.nextval into :new.id from dual;
/*觸發器主題內容,即觸發後執行的動作,在此是取得序列my_test_seq的下一個值插入到表dectuser中的userid欄位中*/
end;
執行啟動專案後點擊進入使用者管理頁:
說明成功了
此文章編輯參考來自以下文章:
https://blog.csdn.net/zxh2075/article/details/78488141
https://blog.csdn.net/qq_30500113/article/details/74995037
https://www.cnblogs.com/huxiuqian/p/7642886.html
https://blog.csdn.net/qq_32113189/article/details/78914286
https://www.cnblogs.com/youzhibing/p/5004619.html
https://blog.csdn.net/qq_35876324/article/details/78910500
https://www.cnblogs.com/jingpeipei/p/6291071.html
https://blog.csdn.net/Zhang_Pengcheng/article/details/80969503
https://www.cnblogs.com/zyw-205520/p/4771253.html