基于SSM框架之個人相冊示例代碼
學習了一陣子的SSM框架,一直在各種博客,簡書,慕課網學習,最后終于自己擼出來一個簡單的個人相冊。
項目的演示效果:
開發(fā)的工具及環(huán)境:
- IntelliJ IDEA: 2016
- Maven :3.0x
- Hbuilder(前端部分,可以用記事本代替2333)
- Java 8
項目流程(dao->service->web):
1.添加所有依賴:
<dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <scope>test</scope> </dependency> <!--補全項目依賴--> <!--1.日志 java日志有:slf4j,log4j,logback,common-logging slf4j:是規(guī)范/接口 日志實現:log4j,logback,common-logging 使用:slf4j+logback --> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.7.12</version> </dependency> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-core</artifactId> <version>1.1.1</version> </dependency> <!--實現slf4j接口并整合--> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-classic</artifactId> <version>1.1.1</version> </dependency> <!--1.數據庫相關依賴--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.35</version> <scope>runtime</scope> </dependency> <dependency> <groupId>c3p0</groupId> <artifactId>c3p0</artifactId> <version>0.9.1.1</version> </dependency> <!--2.dao框架:MyBatis依賴--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.3.0</version> </dependency> <!--mybatis自身實現的spring整合依賴--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.2.3</version> </dependency> <!--3.Servlet web相關依賴--> <dependency> <groupId>taglibs</groupId> <artifactId>standard</artifactId> <version>1.1.2</version> </dependency> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.5.4</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> </dependency> <!--4:spring依賴--> <!--1)spring核心依賴--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>4.1.7.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>4.1.7.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>4.1.7.RELEASE</version> </dependency> <!--2)spring dao層依賴--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>4.1.7.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>4.1.7.RELEASE</version> </dependency> <!--3)springweb相關依賴--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>4.1.7.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>4.1.7.RELEASE</version> </dependency> <!--4)spring test相關依賴--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>4.1.7.RELEASE</version> </dependency> <!--添加redis依賴--> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>2.7.3</version> </dependency> <!--prostuff序列化依賴--> <dependency> <groupId>com.dyuproject.protostuff</groupId> <artifactId>protostuff-core</artifactId> <version>1.0.8</version> </dependency> <dependency> <groupId>com.dyuproject.protostuff</groupId> <artifactId>protostuff-runtime</artifactId> <version>1.0.8</version> </dependency> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.1</version> </dependency>
2.添加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> <!--配置全局屬性--> <settings> <!--使用jdbc的getGeneratekeys獲取自增主鍵值--> <setting name="useGeneratedKeys" value="true"/> <!--使用列別名替換列名 默認值為true select name as title(實體中的屬性名是title) form table; 開啟后mybatis會自動幫我們把表中name的值賦到對應實體的title屬性中 --> <setting name="useColumnLabel" value="true"/> <!--開啟駝峰命名轉換Table:create_time到 Entity(createTime)--> <setting name="mapUnderscoreToCamelCase" value="true"/> </settings> </configuration>
這里最好去官網看最新配置文件的頭配置http://www.mybatis.org/mybatis-3/zh/index.html
然后編寫dao層的代碼:
相冊實體類
public interface PictureDao { /** * @return 返回所有圖片 */ List<Picture> getAllPictures(); /**上傳圖片,并且將圖片名,圖片描述信息插入數據庫 * @param picName * @param content * @return插入成功返回1,失敗0 */ int InsertPicture(@Param("picName") String picName, @Param("content") String content); }
用戶實體類
public interface UserDao { /**如果查詢到該用戶就會返回1 * @param username,pwd * @return數據庫被修改的行數 */ User getUserByName(@Param("username") String username, @Param("pwd") String pwd); }
實體類創(chuàng)建好,我們就在resource文件夾下創(chuàng)建一個mapper文件夾,放我們dao層的映射文件。
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"> <mapper namespace="com.koali.dao.UserDao"> <select id="getUserByName" resultType="com.koali.entity.User" > SELECT * FROM USER WHERE username=#{username} AND pwd=#{pwd} </select> </mapper>
PictureDao.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"> <mapper namespace="com.koali.dao.PictureDao"> <select id="getAllPictures" resultType="com.koali.entity.Picture"> SELECT * FROM PICTURE </select> <insert id="InsertPicture"> INSERT INTO `picture` (`picname`,`content`) VALUES (#{picName},#{content}) </insert> </mapper> </mapper>
最后整合到Spring里面。所以我再次在resource文件夾下創(chuàng)建一個spring文件夾,并且創(chuàng)建一個文件名為:
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 http://www.springframework.org/schema/context/spring-context.xsd"> <!--配置整合mybatis過程 1.配置數據庫相關參數--> <context:property-placeholder location="classpath:jdbc.properties"/> <!--2.數據庫連接池--> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <!--配置連接池屬性--> <property name="driverClass" value="${jdbc.driver}"/> <!-- 基本屬性 url、user、password --> <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="1000"/> <!--當獲取連接失敗重試次數--> <property name="acquireRetryAttempts" value="2"/> </bean> <!--約定大于配置--> <!--3.配置SqlSessionFactory對象--> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <!--往下才是mybatis和spring真正整合的配置--> <!--注入數據庫連接池--> <property name="dataSource" ref="dataSource"/> <!--配置mybatis全局配置文件:mybatis-config.xml--> <property name="configLocation" value="classpath:mybatis-config.xml"/> <!--掃描entity包,使用別名,多個用;隔開--> <property name="typeAliasesPackage" value="com.elric.entity"/> <!--掃描sql配置文件:mapper需要的xml文件--> <property name="mapperLocations" value="classpath:mapper/*.xml"/> </bean> <!--4:配置掃描Dao接口包,動態(tài)實現DAO接口,注入到spring容器--> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <!--注入SqlSessionFactory--> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/> <!-- 給出需要掃描的Dao接口--> <property name="basePackage" value="com.koali.dao"/> </bean> </beans>
因為spring-dao.xml里面有些屬性要連接到我們的數據庫,所以我們把我們的數據庫的連接驅動,用戶名什么鬼都寫在一個叫
jdbc.properties
jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/picture?useUnicode=true&characterEncoding=utf-8 jdbc.username=Elric jdbc.password=881010
dao層編寫結束(表示寫blog比敲代碼還累23333)!
3.編寫Service層
因為這是個小Demo(博主剛學不久,還是一只小菜雞)。所以Service的實現大抵跟dao差不多。
先寫兩個Service接口:
UserService
public interface UserService { /**本次中我們只需要對用戶身份做出判斷然后給予url * @return 數據庫查詢到為1 */ User CheckUser(String username, String pwd); }
PictureService
public interface PictureService { /**查詢所有照片 * @return 所有照片 */ List<Picture> getAllPicture(); /** * 這個服務就是PictureDao中的InsertP * @param picName * @param content * @return 數據庫成功返回1,失敗返回0 */ int InsertPicture(String picName, String content); }
然后再寫兩個實現Service接口的實現類:PictureServiceImpl
@Service public class PictureServiceImpl implements PictureService { @Autowired private PictureDao pictureDao; public List<Picture> getAllPicture() { return pictureDao.getAllPictures(); } public int InsertPicture(String picName, String content) { return pictureDao.InsertPicture(picName,content); } }
UserServiceImpl
PictureServiceImpl
@Service public class UserServiceImpl implements com.koali.service.UserService { @Autowired private UserDao userDao; public User CheckUser(String username, String pwd) { return userDao.getUserByName(username,pwd); } }
然后寫配置文件:
在resource中的spring文件夾下創(chuàng)建spring-service.xml
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" 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:component-scan base-package="com.koali.service"/> <!--配置事務管理器--> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <!--注入數據庫連接池--> <property name="dataSource" ref="dataSource"/> </bean> <!--配置基于注解的聲明式事務 默認使用注解來管理事務行為--> <tx:annotation-driven transaction-manager="transactionManager"/>
到此Service層就寫好了,這個比較簡單。
3.web層的編寫:
現在web.xml添加spring-mvc的前端控制器:
<servlet> <servlet-name>seckill-dispatcher</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring/spring-*.xml</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>seckill-dispatcher</servlet-name> <!--默認匹配所有請求--> <url-pattern>/</url-pattern> </servlet-mapping> <!--去除亂碼的過濾器--> <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> <init-param> <param-name>forceEncoding</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>characterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
然后在resourced的spring文件夾創(chuàng)建spring-web.xml
spring-web.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 http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <!--指明controller所在包,并掃描其中的注解--> <context:component-scan base-package="com.koali.web"/> <!--靜態(tài)資源(js,image等)的訪問--> <mvc:default-servlet-handler/> <!--開啟注解--> <mvc:annotation-driven/> <!--ViewResolver視圖解析器--> <!--用于支持Servlet,JSP視圖解析--> <bean id="jspViewResolver" 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> <!--200*1024*1024即200M resolveLazily屬性啟用是為了推遲文件解析,以便捕獲文件的異常--> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="maxUploadSize" value="209715200" /> <property name="resolveLazily" value="true" /> <property name="defaultEncoding" value="UTF-8"></property> </bean> <mvc:resources location="/WEB-INF/jsp/css/" mapping="/css/**" /> <mvc:resources location="/WEB-INF/jsp/fonts/" mapping="/fonts/**" /> <mvc:resources location="/WEB-INF/jsp/images/" mapping="/images/**" /> <mvc:resources location="/WEB-INF/jsp/js/" mapping="/js/**"/> </beans>
最后編寫我們的前端控制器:
MainController
@Controller public class MainController { @Autowired private PictureService pictureService; @Autowired private UserService userService; @RequestMapping(value = "/") public String index(Model model){ List<Picture> pictures =pictureService.getAllPicture(); System.out.println(pictures.size()); model.addAttribute("pictures",pictures); return "index"; } @RequestMapping(value = "login") public String login(){ return "login"; } @RequestMapping(value = "checkandRedict") public String checkAndRedict(@Param("username") String username,@Param("pwd") String pwd){ User user = userService.CheckUser(username,pwd); System.out.println(user); if (user!=null){ return "upload"; }else { return "index"; } } @RequestMapping(value = "upload",method = RequestMethod.POST) public String upload(@RequestParam("file") MultipartFile file,@Param("content") String content, HttpServletRequest request,Model model) throws IOException{ //獲取項目的根路徑,將上傳圖片的路徑與我們的資源路徑在一起,才能顯示 HttpSession session= request.getSession(); String path = session.getServletContext().getRealPath("/"); System.out.println("getRealPath('/'):"+path); int end = path.indexOf("t",19); String prePath = path.substring(0,end); String realPath = prePath+"target\\demo\\WEB-INF\\jsp\\images"; System.out.println("DEBUG:"+realPath); String picName = new Date().getTime()+".jpg"; if (!file.isEmpty()){ FileUtils.copyInputStreamToFile(file.getInputStream(),new File(realPath,new Date().getTime()+".jpg")); }else if(content==null){ content = "";//如果輸入為null數據庫不允許插入 } //圖片類的名字保存為路徑+名字方便后期前端提取 //將圖片名字用時間戳保存,反正上傳圖片為中文亂碼等問題 int code = pictureService.InsertPicture("images/"+picName,content); if (code==1) { List<Picture> pictures = pictureService.getAllPicture(); model.addAttribute("pictures", pictures); return "index"; }else return "index"; } }
至此項目就到此為止!
最后獻上我的項目的地址:SSM_jb51.rar
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
從零搭建SpringBoot+MyBatisPlus快速開發(fā)腳手架
這篇文章主要為大家介紹了從零搭建SpringBoot+MyBatisPlus快速開發(fā)腳手架示例教程,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-06-06java對象對比之comparable和comparator的區(qū)別
今天給大家?guī)淼氖顷P于Java的相關知識,文章圍繞著comparable和comparator的區(qū)別展開,文中有非常詳細的介紹及代碼示例,需要的朋友可以參考下2021-06-06SpringBoot實現WebSocket服務并讓客戶端實時接收
使用SpringBoot和WebSocket可創(chuàng)建實時消息推送服務,首先添加WebSocket依賴至pom.xml,配置WebSocket端點和邏輯處理器,通過WebSocketHandler處理消息,使用AnnouncementController模擬消息推送,支持HTML和微信小程序客戶端接收消息,感興趣的可以了解一下2024-10-10