欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

基于SSM框架之个人相册示例代码

程序员文章站 2024-03-02 16:52:52
学习了一阵子的ssm框架,一直在各种博客,简书,慕课网学习,最后终于自己撸出来一个简单的个人相册。 项目的演示效果: 开发的工具及环境: intell...

学习了一阵子的ssm框架,一直在各种博客,简书,慕课网学习,最后终于自己撸出来一个简单的个人相册。

项目的演示效果:

基于SSM框架之个人相册示例代码

开发的工具及环境:

  1. intellij idea: 2016
  2. maven :3.0x
  3. hbuilder(前端部分,可以用记事本代替2333)
  4. 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:是规范/接口
      日志实现: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>

这里最好去官网看最新配置文件的头配置

然后编写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);
}

实体类创建好,我们就在resource文件夹下创建一个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文件夹下创建一个spring文件夹,并且创建一个文件名为:

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接口包,动态实现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文件夹下创建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文件夹创建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"/>
  <!--静态资源(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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。