學習了一陣子的SSM框架,一直在各種博客,簡書,慕課網(wǎng)學習,最后終于自己擼出來一個簡單的個人相冊。
目前成都創(chuàng)新互聯(lián)已為上千家的企業(yè)提供了網(wǎng)站建設(shè)、域名、網(wǎng)頁空間、網(wǎng)站托管運營、企業(yè)網(wǎng)站設(shè)計、舟曲網(wǎng)站維護等服務(wù),公司將堅持客戶導(dǎo)向、應(yīng)用為本的策略,正道將秉承"和諧、參與、激情"的文化,與客戶和合作伙伴齊心協(xié)力一起成長,共同發(fā)展。
項目的演示效果:
開發(fā)的工具及環(huán)境:
項目流程(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ī)范/接口 日志實現(xiàn):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> <!--實現(xiàn)slf4j接口并整合--> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-classic</artifactId> <version>1.1.1</version> </dependency> <!--1.數(shù)據(jù)庫相關(guān)依賴--> <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自身實現(xiàn)的spring整合依賴--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.2.3</version> </dependency> <!--3.Servlet web相關(guān)依賴--> <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相關(guān)依賴--> <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相關(guān)依賴--> <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的值賦到對應(yīng)實體的title屬性中 --> <setting name="useColumnLabel" value="true"/> <!--開啟駝峰命名轉(zhuǎn)換Table:create_time到 Entity(createTime)--> <setting name="mapUnderscoreToCamelCase" value="true"/> </settings> </configuration>
這里最好去官網(wǎng)看最新配置文件的頭配置http://www.mybatis.org/mybatis-3/zh/index.html
然后編寫dao層的代碼:
相冊實體類
public interface PictureDao { /** * @return 返回所有圖片 */ List<Picture> getAllPictures(); /**上傳圖片,并且將圖片名,圖片描述信息插入數(shù)據(jù)庫 * @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數(shù)據(jù)庫被修改的行數(shù) */ 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.配置數(shù)據(jù)庫相關(guān)參數(shù)--> <context:property-placeholder location="classpath:jdbc.properties"/> <!--2.數(shù)據(jù)庫連接池--> <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"/> <!--關(guān)閉連接后不自動commit--> <property name="autoCommitOnClose" value="false"/> <!--獲取連接超時時間--> <property name="checkoutTimeout" value="1000"/> <!--當獲取連接失敗重試次數(shù)--> <property name="acquireRetryAttempts" value="2"/> </bean> <!--約定大于配置--> <!--3.配置SqlSessionFactory對象--> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <!--往下才是mybatis和spring真正整合的配置--> <!--注入數(shù)據(jù)庫連接池--> <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)實現(xiàn)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里面有些屬性要連接到我們的數(shù)據(jù)庫,所以我們把我們的數(shù)據(jù)庫的連接驅(qū)動,用戶名什么鬼都寫在一個叫
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層編寫結(jié)束(表示寫blog比敲代碼還累23333)!
3.編寫Service層
因為這是個小Demo(博主剛學不久,還是一只小菜雞)。所以Service的實現(xiàn)大抵跟dao差不多。
先寫兩個Service接口:
UserService
public interface UserService { /**本次中我們只需要對用戶身份做出判斷然后給予url * @return 數(shù)據(jù)庫查詢到為1 */ User CheckUser(String username, String pwd); }
PictureService
public interface PictureService { /**查詢所有照片 * @return 所有照片 */ List<Picture> getAllPicture(); /** * 這個服務(wù)就是PictureDao中的InsertP * @param picName * @param content * @return 數(shù)據(jù)庫成功返回1,失敗返回0 */ int InsertPicture(String picName, String content); }
然后再寫兩個實現(xiàn)Service接口的實現(xiàn)類: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"/> <!--配置事務(wù)管理器--> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <!--注入數(shù)據(jù)庫連接池--> <property name="dataSource" ref="dataSource"/> </bean> <!--配置基于注解的聲明式事務(wù) 默認使用注解來管理事務(wù)行為--> <tx:annotation-driven transaction-manager="transactionManager"/>
到此Service層就寫好了,這個比較簡單。
3.web層的編寫:
現(xiàn)在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數(shù)據(jù)庫不允許插入 } //圖片類的名字保存為路徑+名字方便后期前端提取 //將圖片名字用時間戳保存,反正上傳圖片為中文亂碼等問題 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
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持創(chuàng)新互聯(lián)。
文章題目:基于SSM框架之個人相冊示例代碼
轉(zhuǎn)載來于:http://jinyejixie.com/article36/jjgdsg.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供電子商務(wù)、用戶體驗、自適應(yīng)網(wǎng)站、App開發(fā)、網(wǎng)站策劃、響應(yīng)式網(wǎng)站
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)