关于SSM框架搭建以及简单的增删改查

第一步.Maven框架的搭建

这个很简单,按照网上的搭建步骤进行搭建就能顺利的进行了,可以参考这位博主的文章进行搭建   http://www.cnblogs.com/Sinte-Beuve/p/5730553.html


第二步.搭建完Maven后,我们来进行ssm框架的xml文件配置

1.首先进行spring mvc xml 文件的配置
我把spring mvc 文件放在了WEB-INF文件夹下面新建的一个configs文件夹下面



下面是xml内容
[html] view plain copy
  1.   

<?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-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <!--启用spring的一些annotation --> <context:annotation-config/> <!-- 自动扫描该包,使SpringMVC认为包下用了@controller注解的类是控制器 --> <context:component-scan base-package="com.frank.controller"> <!-- 扫描符合@Service @Repository的类 --> <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan> <!--HandlerMapping 无需配置,springmvc可以默认启动--> <!--但是项目部署到linux下发现WEB-INF的静态资源会出现无法解析的情况,但是本地tomcat访问正常,因此建议还是直接把静态资源放在webapp的statics下,映射配置如下--> <!--<mvc:resources mapping="/css/**" location="/statics/css/"/>--> <!--<mvc:resources mapping="/js/**" location="/statics/js/"/>--> <!--<mvc:resources mapping="/image/**" location="/statics/images/"/>--> <!-- 配置注解驱动 可以将request参数与绑定到controller参数上 --> <mvc:annotation-driven/> <!-- 对模型视图名称的解析,即在模型视图名称添加前后缀(如果最后一个还是表示文件夹,则最后的斜杠不要漏了) 使用JSP--> <!-- 默认的视图解析器 在上边的解析错误时使用 (默认使用html)- --> <bean id="defaultViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/> <property name="prefix" value="/WEB-INF/views/"/><!--设置JSP文件的目录位置--> <property name="suffix" value=".jsp"/> </bean> <!--springmvc文件上传需要配置的节点--> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="maxUploadSize" value="20971500"/> <property name="defaultEncoding" value="UTF-8"/> <property name="resolveLazily" value="true"/><!-- 是否使用延迟加载--> </bean></beans>



然后我们需要在web.xml中声明spring mvc xml 文件


[html] view plain copy
  1. <span style="font-family:'Microsoft YaHei';font-size:14px;"><!--配置springmvc DispatcherServlet-->  
  2.   <servlet>  
  3.     <servlet-name>springMVC</servlet-name>  
  4.     <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>  
  5.     <init-param>  
  6.       <!--Sources标注的文件夹下需要新建一个spring文件夹-->  
  7.       <param-name>contextConfigLocation</param-name>  
  8.       <param-value>/WEB-INF/configs/spring-mvc.xml</param-value>  
  9.     </init-param>  
  10.     <load-on-startup>1</load-on-startup>  
  11.   </servlet>  
  12.   <servlet-mapping>  
  13.     <servlet-name>springMVC</servlet-name>  
  14.     <url-pattern>/</url-pattern>  
  15.   </servlet-mapping></span>  
2.进行spring mybatis 的配置


在main resources下新建 jdbc.properties  和 log4j.properties 代码如下




[html] view plain copy
  1. <span style="font-family:'Microsoft YaHei';font-size:14px;">jdbc.driver=com.mysql.jdbc.Driver  
  2. jdbc.url=jdbc:mysql://localhost:3306/ssm?useUnicode=true&characterEncoding=utf-8  
  3. jdbc.username=root  
  4. jdbc.password=你的密码</span>  

[html] view plain copy
  1. <span style="font-family:'Microsoft YaHei';font-size:14px;">#配置根Logger 后面是若干个Appender  
  2. log4j.rootLogger=DEBUG,A1,R  
  3. #log4j.rootLogger=INFO,A1,R  
  4.   
  5. # ConsoleAppender 输出  
  6. log4j.appender.A1=org.apache.log4j.ConsoleAppender  
  7. log4j.appender.A1.layout=org.apache.log4j.PatternLayout  
  8. log4j.appender.A1.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss,SSS} [%c]-[%p] %m%n  
  9.   
  10. # File 输出 一天一个文件,输出路径可以定制,一般在根路径下  
  11. log4j.appender.R=org.apache.log4j.DailyRollingFileAppender  
  12. <span style="color:#ff0000;">log4j.appender.R.File=logs/log.txt//log日志文件存储位置</span>  
  13. log4j.appender.R.MaxFileSize=500KB  
  14. log4j.appender.R.MaxBackupIndex=10  
  15. log4j.appender.R.layout=org.apache.log4j.PatternLayout  
  16. log4j.appender.R.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSS} [%t] [%c] [%p] - %m%n</span>  
[html] view plain copy
  1.   
然后在resource下新建 applicationContext.xml 进行spring mybatis 整合配置
下面是我的spring xml 文件配置内容
[html] view plain copy
  1. <span style="font-family:'Microsoft YaHei';font-size:14px;"><?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  4.        xmlns:aop="http://www.springframework.org/schema/aop"  
  5.        xmlns:context="http://www.springframework.org/schema/context"  
  6.        xmlns:p="http://www.springframework.org/schema/p"  
  7.        xmlns:tx="http://www.springframework.org/schema/tx"  
  8.        xsi:schemaLocation="  
  9.         http://www.springframework.org/schema/beans  
  10.         http://www.springframework.org/schema/beans/spring-beans.xsd  
  11.          http://www.springframework.org/schema/aop  
  12.          http://www.springframework.org/schema/aop/spring-aop-4.1.xsd  
  13.          http://www.springframework.org/schema/tx  
  14.          http://www.springframework.org/schema/tx/spring-tx-4.1.xsd  
  15.            http://www.springframework.org/schema/context  
  16.          http://www.springframework.org/schema/context/spring-context-4.1.xsd  " >  
  17.     <!--1.1 引用注解-->  
  18.     <context:component-scan base-package="com.frank"/>  
  19.   
  20.     <!--1.1 关联jdbc.properties-->  
  21.     <context:property-placeholder location="classpath:jdbc.properties"/>  
  22.   
  23.     <!-- 01.配置数据源 -->  
  24.         <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">  
  25.             <property name="driverClassName" value="${jdbc.driver}"></property>  
  26.             <property name="url" value="${jdbc.url}"></property>  
  27.             <property name="username" value="${jdbc.username}"></property>  
  28.             <property name="password" value="${jdbc.password}"></property>  
  29.         </bean>  
  30.   
  31.   
  32.   
  33.     <!-- mybatis和spring完美整合,不需要mybatis的配置映射文件 -->  
  34.     <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">  
  35.         <property name="dataSource" ref="dataSource"/>  
  36.         <!-- 自动扫描mapping.xml文件 -->  
  37.         <property name="mapperLocations" value="classpath:mapping/*.xml"></property>  
  38.     </bean>  
  39.   
  40.   
  41.                    <!-- 03.生成dao代理對象-->//<span style="color:#ff0000;">这里没有配置好的话注解找不到对象</span>  
  42.                   <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">  
  43.                       <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>  
  44.                       <property name="basePackage" value="com.frank.dao"></property>  
  45.                   </bean>  
  46.    
  47. </beans></span>  
[html] view plain copy
  1. <span style="font-family:'Microsoft YaHei';font-size:14px;">  
  2. </span>  
[html] view plain copy
  1. <span style="font-family:'Microsoft YaHei';font-size:14px;">  
  2. </span>  
[html] view plain copy
  1. <span style="font-family:'Microsoft YaHei';font-size:14px;"></span>  
[html] view plain copy
  1. <span style="font-family:'Microsoft YaHei';font-size:14px;"><strong>xml配置完成后 在web.xml 进行相同的文件声明</strong></span>  

[html] view plain copy
  1. <span style="font-family:'Microsoft YaHei';font-size:14px;">  
  2. </span>  
[html] view plain copy
  1.   
[html] view plain copy
  1. <span style="font-family:'Microsoft YaHei';font-size:14px;"><!--配置Spring-->  
  2.   <context-param>  
  3.     <param-name>contextConfigLocation</param-name>  
  4.     <param-value>classpath:applicationContext.xml</param-value>  
  5.   </context-param>  
  6. </span>  
[html] view plain copy
  1. <span style="font-family:'Microsoft YaHei';font-size:14px;">  
  2.   <!-- 注册ServletContext监听器,创建容器对象,并且将ApplicationContext对象放到Application域中 -->  
  3.   <listener>  
  4.     <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  
  5.   </listener>  
  6.   <!-- 防止spring内存溢出监听器,比如quartz -->  
  7.   <listener>  
  8.     <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>  
  9.   </listener></span>  


[html] view plain copy
  1. <span style="font-family:'Microsoft YaHei';font-size:14px;"><strong>配置完成后 ,我们的ssm框架算是已经稍微成型了</strong></span>  


第三步  搭建mapper 映射
首先创建实体类 User


[html] view plain copy
  1. <span style="font-family:'Microsoft YaHei';font-size:14px;">public class User {  
  2.     private  int userID;  
  3.         private String userName;  
  4.         private String password;  
  5.   
  6.     public String getPassword() {  
  7.         return password;  
  8.     }  
  9.   
  10.     public void setPassword(String password) {  
  11.         this.password = password;  
  12.     }  
  13.   
  14.     public int getUserID() {  
  15.         return userID;  
  16.     }  
  17.   
  18.     public void setUserID(int userID) {  
  19.         this.userID = userID;  
  20.     }  
  21.   
  22.     public String getUserName() {  
  23.         return userName;  
  24.     }  
  25.   
  26.     public void setUserName(String userName) {  
  27.         this.userName = userName;  
  28.     }  
  29.   
  30.   
  31.   
  32.   
  33. }</span>  

创建dao层 

[html] view plain copy
  1. <span style="font-family:'Microsoft YaHei';font-size:14px;">package com.frank.dao;  
  2.   
  3. import com.frank.bean.User;  
  4. import org.mybatis.spring.annotation.MapperScan;  
  5. import org.springframework.stereotype.Component;  
  6. import org.springframework.stereotype.Repository;  
  7.   
  8. import java.util.List;  
  9.   
  10.   
  11. @Repository<!--这里使用注解-->  
  12. public interface UserMapper {  
  13.   
  14.     public void save(User user);  
  15.     public void update(User user);  
  16.     public User findById(int id);  
  17.     public List<User> findAll();  
  18.     public void deleteById(int id);  
  19.   
  20. }  
  21. </span>  
我认为ssm 利用mapper 省去了 物理实现层的接口类 而是在mapping中直接进行数据库操作,这样更加的简便了(个人观点)
我们在resources文件夹下新建mapping文件夹 ,里面创建我们的UserMapper




这里就包含了用户的增删改查的数据库操作,需要注意的是,在进行用户列表显示时,需要用到ResultMap,需要对里面的对象进行声明,如下 property代表实体类的属性名
而 column显而易见代表的是数据库的列名
下面select等语句中的id代表dao类中的方法名称

[html] view plain copy
  1. <span style="font-family:'Microsoft YaHei';font-size:14px;"><?xml version="1.0" encoding="UTF-8"?>  
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"  
  3.  "http://mybatis.org/dtd/mybatis-3-mapper.dtd">  
  4.         <!--  
  5.             namespace:必须与对应的接口全类名一致  UserMapper.java  
  6.             id :必须与对应接口的某个对应的方法名一致即必须要和UserMapper.java接口中的方法同名。  
  7.          -->  
  8.   
  9. <mapper namespace="com.frank.dao.UserMapper">  
  10.     <resultMap id="StudentList" type="com.frank.bean.User">  
  11.         <id property="userID" column="userID"/>  
  12.         <result property="userName" column="userName"/>  
  13.         <result property="password" column="password"/>  
  14.   
  15.   
  16.     </resultMap>  
  17.   
  18.     <insert id="save" parameterType="com.frank.bean.User">  
  19.   
  20.         INSERT  into user(userName,passWord)  VALUES (#{userName},#{password})  
  21.     </insert>  
  22.   
  23.     <update id="update" parameterType="com.frank.bean.User">  
  24.         UPDATE  user SET userName=#{userName},passWord=#{password} where userID=#{userID}  
  25.   
  26.     </update>  
  27.     <select id="findByID" parameterType="int" resultType="com.frank.bean.User">  
  28.         SELECT * FROM  user WHERE userID=#{id}  
  29.   
  30.     </select>  
  31. <select id="findAll" resultMap="StudentList">  
  32.     SELECT  * from user  
  33.   
  34. </select>  
  35.     <delete id="deleteById" parameterType="int">  
  36.   
  37.         DELETE  FROM USER  WHERE userID=#{id}  
  38.     </delete>  
  39.   
  40. </mapper></span>  

这样我们的dao层已经算是写完了,下面是service层

[html] view plain copy
  1. <span style="font-family:'Microsoft YaHei';font-size:14px;">package com.frank.service;  
  2.   
  3. import com.frank.bean.User;  
  4. import com.frank.dao.UserMapper;  
  5. import org.springframework.beans.factory.annotation.Autowired;  
  6.   
  7. import java.util.List;  
  8.   
  9. public interface UserService {  
  10.   
  11.     public void save(User user);  
  12.     public void update(User user);  
  13.     public User findById(int id);  
  14.     public List<User> findAll();  
  15.     public void deleteById(int id);  
  16. }  
  17. </span>  


 servicelmpl


[html] view plain copy
  1. <span style="font-family:'Microsoft YaHei';font-size:14px;">package com.frank.servicelmpl;  
  2.   
  3. import com.frank.bean.User;  
  4. import com.frank.dao.UserMapper;  
  5. import com.frank.service.UserService;  
  6. import org.springframework.beans.factory.annotation.Autowired;  
  7. import org.springframework.stereotype.Service;  
  8.   
  9. import java.util.List;  
  10.   
  11. @Service  
  12. public class UserServicelmpl implements UserService {  
  13.     @Autowired()  
  14.     private UserMapper userMapper;  
  15.     public void save(User user) {  
  16. userMapper.save(user);  
  17.     }  
  18.   
  19.     public void update(User user) {  
  20. userMapper.update(user);  
  21.     }  
  22.   
  23.     public User findById(int id) {  
  24.         return userMapper.findById(id);  
  25.     }  
  26.   
  27.     public List<User> findAll() {  
  28.         return userMapper.findAll();  
  29.     }  
  30.   
  31.     public void deleteById(int id) {  
  32.         userMapper.deleteById(id);  
  33.     }  
  34. }  
  35. </span>  

第四步 Controller层进行url管理

我的controller类
package com.frank.controller;

import com.frank.bean.User;
import com.frank.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;



@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private   UserService userService;

    private static final Logger logger= LoggerFactory.getLogger(UserController.class);
    @RequestMapping("/person")
    public String getPage(){

        return "/user/add";
    }

    @RequestMapping(value = "/add",method = RequestMethod.POST)
    public String addUser(@RequestParam("username") String username, @RequestParam("pwd") String pwd, Model model)
    {

        User user=new User();
        user.setUserName(username);
        user.setPassword(pwd);
        logger.info(username+"!!!!!!!!!");
        userService.save(user);
        return "redirect:/user/list";

    }


    @RequestMapping("/list")
public String getList(Model model){

        List<User> list=userService.findAll();

        if(list!=null){
            logger.info("list has been filled");
            logger.info(list.get(0).getUserName());
        }

        else
            logger.info("list is null");

        model.addAttribute("list",list);
        return "/user/userList";

    }

    @RequestMapping("/delete/{id}")
    public String doDelete(@PathVariable("id") Integer id){
userService.deleteById(id);
logger.info("this user has been deleted");
return "redirect:/user/list";

    }

}

1.展示用户列表

jsp代码

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<table style="margin: auto;">
    <tr>
        <td>ID</td>
        <td>userName</td>
    <td>password</td>
    </tr>

    <c:forEach items="${list}" var="user">
<tr>
    <td>${user.userID}</td>
    <td>${user.userName}</td>
    <td>${user.password}</td>
    <td><a href="/user/edit/${user.userID}">编辑</a></td>//这个就不写啦,思路都一样的
    <td><a href="/user/delete/${user.userID}">删除</a></td>
</tr>

    </c:forEach>


</table>


</body>
</html>



2.添加用户


<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>

<form action="/user/add" method="post">

    username:<input type="text" name="username"/><br>
    password:<input type="password" name="pwd"/><br>
    <input type="submit" value="click"/>

</form>
</body>
</html>


添加完成后 通过redirect 重定向 跳转到list页面  


3.删除操作

删除第二个用户后重定向跳转页面

本人也是刚学习ssm,只是对自己的代码认识做了一个总结,有不对的地方希望大家能一起交流,谢谢。

顺便把我使用的dependecy 发给大家


<dependency>
  <groupId>junit</groupId>
  <artifactId>junit</artifactId>
  <version>3.8.1</version>
  <scope>test</scope>
</dependency>

<!--日志包-->
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-log4j12</artifactId>
      <version>1.7.21</version>
    </dependency>

    <!--j2ee相关包 servlet、jsp、jstl-->
<dependency>
  <groupId>javax.servlet</groupId>
  <artifactId>javax.servlet-api</artifactId>
  <version>3.1.0</version>
</dependency>
<dependency>
  <groupId>javax.servlet.jsp</groupId>
  <artifactId>jsp-api</artifactId>
  <version>2.2</version>
</dependency>
<dependency>
  <groupId>javax.servlet</groupId>
  <artifactId>jstl</artifactId>
  <version>1.2</version>
</dependency>

<!--mysql驱动包-->
<dependency>
  <groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.35</version>
</dependency>

<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-pool2 -->
<dependency>
  <groupId>org.apache.commons</groupId>
  <artifactId>commons-pool2</artifactId>
  <version>2.4.2</version>
</dependency>


<!-- https://mvnrepository.com/artifact/commons-dbcp/commons-dbcp -->
<dependency>
  <groupId>commons-dbcp</groupId>
  <artifactId>commons-dbcp</artifactId>
  <version>1.4</version>
</dependency>


<!--spring相关包-->

<!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-jdbc</artifactId>
  <version>4.3.7.RELEASE</version>
</dependency>


<!-- https://mvnrepository.com/artifact/org.springframework/spring-aop -->
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-aop</artifactId>
  <version>4.3.7.RELEASE</version>
</dependency>

<!-- https://mvnrepository.com/artifact/org.springframework/spring-beans -->
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-beans</artifactId>
  <version>4.3.7.RELEASE</version>
</dependency>

<!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-context</artifactId>
  <version>4.3.7.RELEASE</version>
</dependency>

<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-web</artifactId>
  <version>4.3.7.RELEASE</version>
</dependency>
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-webmvc</artifactId>
  <version>4.3.7.RELEASE</version>
</dependency>

<!--myBatis-->
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
  <groupId>org.mybatis</groupId>
  <artifactId>mybatis</artifactId>
  <version>3.4.1</version>
</dependency>


<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
<dependency>
  <groupId>org.mybatis</groupId>
  <artifactId>mybatis-spring</artifactId>
  <version>1.3.0</version>
</dependency>



<!--其他需要的包-->
<dependency>
  <groupId>org.apache.commons</groupId>
  <artifactId>commons-lang3</artifactId>
  <version>3.4</version>
</dependency>
<dependency>
  <groupId>commons-fileupload</groupId>
  <artifactId>commons-fileupload</artifactId>
  <version>1.3.1</version>
</dependency>

<!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
<dependency>
  <groupId>commons-io</groupId>
  <artifactId>commons-io</artifactId>
  <version>2.4</version>
</dependency>

<!-- json-->
<dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-core</artifactId>
  <version>${jackson.version}</version>
</dependency>
<dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-databind</artifactId>
  <version>${jackson.version}</version>
</dependency>
<dependency>
  <groupId>org.codehaus.jackson</groupId>
  <artifactId>jackson-core-asl</artifactId>
  <version>1.9.13</version>
</dependency>
<dependency>
  <groupId>org.codehaus.jackson</groupId>
  <artifactId>jackson-mapper-asl</artifactId>
  <version>1.9.13</version>
</dependency>


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值