SSM 電影后臺管理專案
概述
通過對資料庫中一張表的CRUD,將相應的操作結果渲染到頁面上。
筆者通過這篇部落格還原了專案(當然有一些隱藏的坑),然後將該專案上傳到了Github、Gitee,在末尾會附上有原始碼地址,讀者可參考。
該專案使用的是Spring+SpringMVC+Mybaits(SSM)後端架構,POJO---Dao---Service---Controller的結構,簡單易懂。
- POJO:實體類層,封裝的是資料中的設計的表對應的元素。
- Dao:Mapper的介面以及Mapper.xml檔案,實現sql操作。
- Service:服務實現層,呼叫Dao層方法進行實現。
- Controller:控制層,呼叫一個個Service層的實現方法完成一個個具體功能。
專案使用了前端JS檢錯和後端JSR303引數校驗,能把絕大部分的問題都包括其中。類似於輸入資訊錯誤以及輸入資訊不合法,違規跳轉等,也加入了過濾器,使使用者可以有更好的體驗。
電影后臺管理系統的管理員在工作中需要查閱和管理如下資訊:後臺管理的管理員、電影資訊、新聞資訊以及型別資訊。如下圖:
準備
- 環境:
- IDEA
- MySQL 5.1.47
- Tomcat 9
- Maven 3.6
- 要求:
- 掌握MySQL資料庫
- 掌握Spring
- 掌握MyBatis
- 掌握SpringMVC
- 掌握簡單的前端知識
實現
1.前置準備
1.1 建立資料庫film
CREATE DATABASE `film`;
USE `film`;
-- ----------------------------
-- Table structure for film
-- ----------------------------
DROP TABLE IF EXISTS `film`;
CREATE TABLE `film` (
`ISDN` int(20) NOT NULL,
`name` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`director` varchar(10) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`actor` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`type` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`country` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`language` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`score` double(10, 0) NULL DEFAULT NULL,
`photo` varchar(150) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`href` varchar(150) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`description` varchar(150) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
PRIMARY KEY (`ISDN`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Compact;
-- ----------------------------
-- Records of film
-- ----------------------------
INSERT INTO `film` VALUES (1, '神奇女俠', '派蒂·傑金斯', '蓋爾·加朵', '科幻', '美國', '英語', 7, 'http://localhost:8080/video/\\sq.png', 'http://localhost:8080/video/\\匯入視訊.mp4', '故事背景設定在五光十色...');
INSERT INTO `film` VALUES (2, '緊急救援', '林超賢', '彭于晏', '動作', '中國大陸', '漢語普通話', 6, 'http://localhost:8080/video/\\jj.png', 'http://localhost:8080/video/\\匯入視訊.mp4', '傾覆沉沒的鑽井平臺...');
INSERT INTO `film` VALUES (3, '333333333', '3', '3', '科幻', '3', '4', 3, 'http://localhost:8080/video/\\Snipaste_2020-10-11_00-02-07.png', 'http://localhost:8080/video/\\匯入視訊.mp4', '111');
-- ----------------------------
-- Table structure for news
-- ----------------------------
DROP TABLE IF EXISTS `news`;
CREATE TABLE `news` (
`ISDN` int(11) NOT NULL,
`title` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`author` varchar(10) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`date` date NULL DEFAULT NULL,
`description` varchar(150) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
PRIMARY KEY (`ISDN`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Compact;
-- ----------------------------
-- Records of news
-- ----------------------------
INSERT INTO `news` VALUES (1, 'test1', 'zczc', '2009-01-13', '這是一個測試');
INSERT INTO `news` VALUES (2, 'test2', 'zctoo', '2001-02-15', '這也是一個測試');
-- ----------------------------
-- Table structure for types
-- ----------------------------
DROP TABLE IF EXISTS `types`;
CREATE TABLE `types` (
`id` int(11) NOT NULL,
`type` varchar(10) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Compact;
-- ----------------------------
-- Records of types
-- ----------------------------
INSERT INTO `types` VALUES (1, '科幻');
INSERT INTO `types` VALUES (2, '戰爭');
INSERT INTO `types` VALUES (3, '歷史');
INSERT INTO `types` VALUES (4, '動作');
INSERT INTO `types` VALUES (5, '愛情');
INSERT INTO `types` VALUES (6, '喜劇');
INSERT INTO `types` VALUES (7, '冒險');
INSERT INTO `types` VALUES (8, '恐怖');
-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` int(100) NOT NULL AUTO_INCREMENT,
`username` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
`paw` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`tele` int(20) NULL DEFAULT NULL,
`email` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 3 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Compact;
-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES (1, '111111', '123456', 111, 'moyu_zc@13.com');
INSERT INTO `user` VALUES (2, '111zc', 'zc123', 1111111111, '1437101473@qq.com');
SET FOREIGN_KEY_CHECKS = 1;
1.2 匯入需要的依賴
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.6</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.8.RELEASE</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>5.2.8.RELEASE</version>
</dependency>
<dependency>
<groupId>com.jhlabs</groupId>
<artifactId>filters</artifactId>
<version>2.0.235</version>
</dependency>
<dependency>
<groupId>com.github.penggle</groupId>
<artifactId>kaptcha</artifactId>
<version>2.3.2</version>
</dependency>
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.2</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.4</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.1.9.RELEASE</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp.jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
<dependency>
<groupId>org.apache.taglibs</groupId>
<artifactId>taglibs-standard-spec</artifactId>
<version>1.2.5</version>
</dependency>
<dependency>
<groupId>org.apache.taglibs</groupId>
<artifactId>taglibs-standard-impl</artifactId>
<version>1.2.5</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.2.1-b03</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.2.2.Final</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>1.4</version>
</dependency>
</dependencies>
1.3 Maven資源過濾以及JDK設定
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
1.4 建立好專案架構
先建立好com.zc.xxx路徑下的檔案;resources資原始檔夾下的檔案可以先不建立,下面會逐步建立。
2.Mybaits
2.1 資料庫配置檔案
資料庫配置檔案 db.properties
jabc.driver=com.mysql.jdbc.Driver
jabc.url=jdbc:mysql://localhost:3306/film?useUnicode=true&characterEncoding=UTF-8
jabc.username=root
jabc.password=root
2.2 關聯資料庫
IDEA關聯資料庫,用idea登陸上自己的資料庫
2.3 編寫MyBatis的核心配置檔案
MyBatis的核心配置檔案:mybatis-config.xml
<?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>
<mappers>
<mapper resource="xxxx"/> <!-- 寫好了Mapper.xml檔案,記得第一時間繫結 -->
</mappers>
</configuration>
3.Spring
配置Spring整合MyBatis,我們這裡資料來源使用c3p0連線池;
3.1 Spring整合Dao層
配置檔名:spring-dao.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<!-- 配置整合mybatis -->
<!-- 1.關聯資料庫檔案 -->
<context:property-placeholder location="classpath:db.properties"/>
<!-- 2.資料庫連線池 -->
<!--資料庫連線池
dbcp 半自動化操作 不能自動連線
c3p0 自動化操作(自動的載入配置檔案 並且設定到物件裡面)
-->
<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}"/>
<!-- c3p0連線池的私有屬性 -->
<property name="maxPoolSize" value="30"/>
<property name="minPoolSize" value="10"/>
<!-- 關閉連線後不自動commit -->
<property name="autoCommitOnClose" value="false"/>
<!-- 獲取連線超時時間 -->
<property name="checkoutTimeout" value="10000"/>
<!-- 當獲取連線失敗重試次數 -->
<property name="acquireRetryAttempts" value="2"/>
</bean>
<!-- 3.配置SqlSessionFactory物件 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 注入資料庫連線池 -->
<property name="dataSource" ref="dataSource"/>
<!-- 配置MyBaties全域性配置檔案:mybatis-config.xml -->
<property name="configLocation" value="classpath:mybatis-config.xml"/>
</bean>
<!-- 4.配置掃描Dao介面包,動態實現Dao介面注入到spring容器中 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 注入sqlSessionFactory -->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
<!-- 給出需要掃描Dao介面包 -->
<property name="basePackage" value="com.Dao"/>
</bean>
</beans>
3.2 Spring整合Service層
配置檔名:spring-service.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
<!-- 掃描service相關的bean -->
<context:component-scan base-package="com.Service" />
<!--BookServiceImpl注入到IOC容器中-->
<bean id="BookServiceImpl" class="com.Service.BookServiceImpl">
<property name="bookMapper" ref="bookMapper"/>
</bean>
<!-- 配置事務管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!-- 注入資料庫連線池 -->
<property name="dataSource" ref="dataSource" />
</bean>
</beans>
如果這個檔案出錯,是因為Spring的幾個配置檔案沒有整合在一起,有兩個方法:
一、手動關聯
File---Project Structure中:
如果三個不在同一個裡面,點 “+” 新增檔案。
二、語句引用
在配置檔案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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<import resource="classpath:spring-service.xml"/>
<import resource="classpath:spring-dao.xml"/>
</beans>
這樣這三個xml檔案就關聯起來了。
4.SpringMVC層
4.1 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_4_0.xsd"
version="4.0">
<!--DispatcherServlet-->
<servlet>
<servlet-name>DispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<!--一定要注意:我們這裡載入的是總的配置檔案-->
<param-value>classpath:applicationContext.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>DispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!--編碼配置-->
<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>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!--Session過期時間-->
<session-config>
<session-timeout>15</session-timeout>
</session-config>
</web-app>
4.2 springmvc.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: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
https://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- 1.開啟SpringMVC註解驅動 -->
<mvc:annotation-driven />
<!-- 2.靜態資源預設servlet配置-->
<mvc:default-servlet-handler/>
<!-- 3.配置jsp 顯示ViewResolver檢視解析器 這部分加不加自行決定
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
-->
<!-- 4.掃描web相關的bean -->
<context:component-scan base-package="com.Controller" />
</beans>
4.3 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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<import resource="spring-dao.xml"/>
<import resource="spring-service.xml"/>
<import resource="spring-mvc.xml"/>
</beans>
以上SSM架構,搭建完成
5.POJO層
因為設計的資料庫中有4個表,分別是:user
、type
、news
、film
所以對應建立四個實體類
public class user {
private Integer id;
private String username;
private String paw;
private Integer tele;
private String email;
// 有參\有參方法
// Get\Set方法
// toString()
}
public class types {
private Integer id;
private String type;
// 有參\有參方法
// Get\Set方法
// toString()
}
news實體類中使用了JSR303檢驗機制,不加註解也是可以的
public class news {
@NotNull
private Integer ISDN;
@NotNull
private String title;
@NotNull
private String author;
@DateTimeFormat(pattern = "yyyy-MM-dd")
@Past
private Date date;
@NotNull
private String description;
// 有參\有參方法
// Get\Set方法
// toString()
}
public class film {
private Integer ISDN;
private String name;
private String director;
private String actor;
private String type;
private String country;
private String language;
private Double score;
private String photo;
private String href;
private String description;
// 有參\有參方法
// Get\Set方法
// toString()
}
在這些實體類中,我使用的是直接新增構造方法;如果覺得麻煩,可以使用Lombok外掛
6.Dao層
每一個Dao類都分別對應著一個實體類的操作
Mapper介面+Mapper.xml
6.1 UserMapper
public interface UserMapper {
/**
* 獲取使用者列表
* @return
*/
public List<user> getUserList();
/**
* id查使用者
* @return
*/
public user getUserById(int id);
/**
* 新增使用者
* @param user
* @return
*/
public int insertUser(user user);
/**
* 修改使用者個人資訊
* @return
*/
public int upUser(user user);
/**
* 修改密碼
* @param user
* @return
*/
public int uppaw(user user);
}
<?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.zc.Dao.UserMapper">
<select id="getUserList" resultType="com.zc.pojo.user">
select * from film.user
</select>
<select id="getUserById" resultType="com.zc.pojo.user">
select * from film.user where id=#{id}
</select>
<insert id="insertUser" parameterType="com.zc.pojo.user" >
insert into film.user (username,paw,tele,email) values (#{username},#{paw},#{tele},#{email})
</insert>
<update id="upUser" parameterType="com.zc.pojo.user">
update film.user set username = #{username},tele = #{tele},email = #{email} where id = #{id}
</update>
<update id="uppaw" parameterType="com.zc.pojo.user">
update film.user set paw=#{paw} where id = #{id}
</update>
</mapper>
6.2 TypesMapper
public interface TypesMapper {
/**
* 通過ID查詢type
* @param id
* @return
*/
public types selectTypeByID(int id);
/**
* 查詢全部
* @return
*/
public List<types> Alltypes();
/**
* 通過id刪除type
* @param id
* @return
*/
public int DeletetypeById(int id);
/**
* 更新type
* @param types
* @return
*/
public int Updatetype(types types);
/**
* 新增type
* @param types
* @return
*/
public int addtype(types types);
}
6.3 NewsMapper
public interface NewsMapper {
/**
* 通過 ISDN 查詢 new
* @param ISDN
* @return
*/
public news selectNewById(int ISDN);
/**
* 查詢全部新聞
* @return
*/
public List<news> Allnews();
/**
* 新增新聞
* @param news
* @return
*/
public int addNew(news news);
/**
* 更新新聞
* @param news
* @return
*/
public int upNew(news news);
/**
* 通過 ISDN 刪除新聞
* @param ISDN
* @return
*/
public int DelnewById(int ISDN);
}
6.4 FilmMapper
public interface FilmMapper {
/**
* 查詢全部電影
* @return
*/
public List<film> AllFilm();
/**
* 通過ISDN查電影
* @param ISDN
* @return
*/
public List<film> selectfilmByISDN(int ISDN);
/**
* 通過導演查電影
* @param director
* @return
*/
public List<film> selectfilmByDir(String director);
/**
* 通過型別查電影
* @param type
* @return
*/
public List<film> selectfilmBytype(String type);
/**
* 新增電影
* @param film
* @return
*/
public int AddFilm(film film);
/**
* 修改電影
* @param film
* @return
*/
public int upFilm(film film);
/**
* 通過ISDN 刪除電影
* @param ISDN
* @return
*/
public int DelFilm(int ISDN);
}
7.Service層
每個Dao層也會有一個對應的Service實現層
7.1 UserService
public interface UserService {
/**
* 得到全部User資料
* @return
*/
public List<user> getUserList();
/**
* 插入一個User
* @param user
* @return
*/
public int insertUser(user user);
/**
* 更新使用者資訊
* @param user
* @return
*/
public int upUser(user user);
/**
* 更新使用者密碼
* @param user
* @return
*/
public int uppaw(user user);
/**
* 通過id查詢使用者
* @param id
* @return
*/
public user getUserById(int id);
}
@Service
public class UserServiceimpl implements UserService{
@Autowired
private UserMapper userMapper;
@Override
public List<user> getUserList() {
return userMapper.getUserList();
}
@Override
public int insertUser(user user) {
return userMapper.insertUser(user);
}
@Override
public int upUser(user user) {
return userMapper.upUser(user);
}
@Override
public int uppaw(user user) {
return userMapper.uppaw(user);
}
@Override
public user getUserById(int id) {
return userMapper.getUserById(id);
}
}
7.2 TypesService
public interface TypesService {
/**
* 通過ID查詢type
* @param id
* @return
*/
public types selectTypeByID(int id);
/**
* 查詢全部
* @return
*/
public List<types> Alltypes();
/**
* 通過id刪除type
* @param id
* @return
*/
public int DeletetypeById(int id);
/**
* 更新type
* @param types
* @return
*/
public int Updatetype(types types);
/**
* 新增type
* @param types
* @return
*/
public int addtype(types types);
}
7.3 NewsService
public interface NewsService {
/**
* 通過 ISDN 查詢 new
* @param ISDN
* @return
*/
public news selectNewById(int ISDN);
/**
* 查詢全部新聞
* @return
*/
public List<news> Allnews();
/**
* 新增新聞
* @param news
* @return
*/
public int addNew(news news);
/**
* 更新新聞
* @param news
* @return
*/
public int upNew(news news);
/**
* 通過 ISDN 刪除新聞
* @param ISDN
* @return
*/
public int DelnewById(int ISDN);
}
7.4 FilmService
public interface FilmService {
/**
* 查詢全部電影
* @return
*/
public List<film> AllFilm();
/**
* 通過ISDN查電影
* @param ISDN
* @return
*/
public List<film> selectfilmByISDN(int ISDN);
/**
* 通過導演查電影
* @param director
* @return
*/
public List<film> selectfilmByDir(String director);
/**
* 通過型別查電影
* @param type
* @return
*/
public List<film> selectfilmBytype(String type);
/**
* 新增電影
* @param film
* @return
*/
public int AddFilm(film film);
/**
* 修改電影
* @param film
* @return
*/
public int upFilm(film film);
/**
* 通過ISDN 刪除電影
* @param ISDN
* @return
*/
public int DelFilm(int ISDN);
}
8.Controller層
Controller層的程式碼都是實現具體功能的程式碼
因為程式碼過長,在此只舉例User、types的Controller層程式碼
@Controller
public class UserController {
@Autowired
private HttpServletRequest request;
@Autowired
@Qualifier("userServiceimpl")
private UserService userService;
/**
* 登入
* @param username
* @param password
* @param code
* @return
*/
@RequestMapping("/Login")
public String getUserList(String username, String password, String code){
List<user> userList = userService.getUserList();
for (user user : userList) {
System.out.println(user);
if(user.getUsername().equals(username)&&user.getPaw().equals(password)){
HttpSession session = request.getSession();
Object attribute = session.getAttribute(Constants.KAPTCHA_SESSION_KEY);
if(code.equals(attribute)){
session.setAttribute("user",user);
return "main.jsp";
}else {
request.setAttribute("mgs", "驗證碼錯誤");
return "index.jsp";
}
}
}
// System.out.println(user.getUsername()+"-----"+user.getPaw());
request.setAttribute("mgs", "使用者名稱或密碼錯誤");
return "index.jsp";
}
/**
* 登出
* @return
*/
@RequestMapping("/exit")
public String exit(){
request.getSession().removeAttribute("user");
return "index.jsp";
}
/**
* 註冊
* @param user
* @return
*/
@RequestMapping("/register")
public String insertUser(user user){
List<user> userList = userService.getUserList();
for (user user1 : userList) {
if (user1.getUsername().equals(user.getUsername())){
request.setAttribute("mgs1", "已經存在該使用者");
return "index.jsp";
}else {
System.out.println(user);
userService.insertUser(user);
return "index.jsp";
}
}
return "index.jsp";
}
/**
* 修改使用者資訊
* @param user
* @return
*/
@RequestMapping("/upUser")
public String upUser(user user){
int i = userService.upUser(user);
System.out.println(user+"-----"+i);
if (i>0){
user user1 = userService.getUserById(user.getId());
request.getSession().setAttribute("user",user1);
request.setAttribute("mgs4","修改成功");
return "person/person_info.jsp";
}else{
request.setAttribute("mgs4","修改失敗");
return "person/person_info.jsp";
}
}
/**
* 修改密碼
* @param user
* @return
*/
@RequestMapping("/uppaw")
public String uppaw(user user, String paw1){
user userById = userService.getUserById(user.getId());
System.out.println(user+"----------"+paw1);
if(userById.getPaw().equals(paw1)){
userService.uppaw(user);
user user1 = userService.getUserById(user.getId());
request.getSession().setAttribute("user",user1);
request.setAttribute("mgs3","修改密碼成功");
return "person/updatepwd.jsp";
}else{
request.setAttribute("mgs3","輸入原始密碼不對");
return "person/updatepwd.jsp";
}
}
}
@Controller
public class TypesController {
@Autowired
private HttpServletRequest request;
@Autowired
@Qualifier("typesServiceimpl")
private TypesService typesService;
/**
* 查詢全部種類
* @param model
* @return
*/
@RequestMapping("/alltypes")
public String Alltypes(Model model){
List<types> alltypes = typesService.Alltypes();
model.addAttribute("alltypes",alltypes);
return "film/File_cate.jsp";
}
/**
* 新增種類
* @param types
* @return
*/
@RequestMapping("/addtype")
public String addtype(types types){
System.out.println(types);
List<types> alltypes = typesService.Alltypes();
for (com.zc.pojo.types alltype : alltypes) {
if (alltype.getId().equals(types.getId())){
request.setAttribute("addtype","已經存在該電影類別編號");
return "forward:/alltypes";
}
else if (alltype.getType().equals(types.getType())){
request.setAttribute("addtype","已經存在該電影類別");
return "forward:/alltypes";
}
}
int i = typesService.addtype(types);
if(i>0){
request.setAttribute("addtype","新增成功");
return "forward:/alltypes";
}else{
request.setAttribute("addtype","新增失敗");
return "forward:/alltypes";
}
}
/**
* 更新種類
* @param types
* @return
*/
@RequestMapping("/uptype")
public String Updatetype(types types){
List<types> alltypes = typesService.Alltypes();
for (com.zc.pojo.types alltype : alltypes) {
if (alltype.getType().equals(types.getType())) {
request.setAttribute("addtype", "已經存在該電影類別");
return "forward:/alltypes";
}
else {
int i = typesService.Updatetype(types);
if(i>0){
request.setAttribute("addtype","新增成功");
return "forward:/alltypes";
}else{
request.setAttribute("addtype","新增失敗");
return "forward:/alltypes";
}
}
}
//System.out.println(types);
return "forward:/alltypes";
}
/**
* 刪除種類
* @param id
* @return
*/
@RequestMapping("/deltype")
public String Deltype(int id){
int i = typesService.DeletetypeById(id);
if(i>0){
request.setAttribute("addtype","刪除成功");
return "forward:/alltypes";
}else{
request.setAttribute("addtype","刪除失敗");
return "forward:/alltypes";
}
}
}
9.過濾器、攔截器
9.1 過濾器
public class LoginFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest)servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse;
String servletPath = request.getServletPath(); //獲取客戶端所請求的指令碼檔案的檔案路徑
if(servletPath.equals("/index.jsp") ||servletPath.equals("/Login")||servletPath.equals(".js")||servletPath.equals(".css")||servletPath.equals(".png"))
{
filterChain.doFilter(request,response);
}else {
HttpSession session = request.getSession();
if (session.getAttribute("user") == null) {
// 沒有登入
response.sendRedirect(request.getContextPath() + "/index.jsp");
}else {
filterChain.doFilter(request,response);
}
}
}
@Override
public void destroy() {
}
}
9.2 攔截器
public class LoginInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException, ServletException {
if (request.getRequestURI().contains(".js")||request.getRequestURI().contains(".css")
||request.getRequestURI().contains(".png")||request.getRequestURI().contains(".jpg")) {
return true;
}
HttpSession session = request.getSession();
if (session.getAttribute("user")!= null) {
return true;
}
request.getRequestDispatcher(request.getContextPath()+"/index.jsp").forward(request,response);
return false;
}
@Override
public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
}
}
在ApplicationContext.xml中配置:
<mvc:interceptors>
<mvc:interceptor>
<!--預設攔截的連線-->
<mvc:mapping path="/**"/>
<!--不攔截的連線-->
<mvc:exclude-mapping path="/Login"/>
<bean class="com.zc.Fliter.LoginInterceptor"/>
</mvc:interceptor>
</mvc:interceptors>
10.專案展示
該專案地址為:
個人部落格為:
MoYu's HomePage
MoYu's Gitee Blog