第一步.Maven框架的搭建
这个很简单,按照网上的搭建步骤进行搭建就能顺利的进行了,可以参考这位博主的文章进行搭建 http://www.cnblogs.com/Sinte-Beuve/p/5730553.html
第二步.搭建完Maven后,我们来进行ssm框架的xml文件配置
1.首先进行spring mvc xml 文件的配置
我把spring mvc 文件放在了WEB-INF文件夹下面新建的一个configs文件夹下面
下面是xml内容
然后我们需要在web.xml中声明spring mvc 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-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>
- <span style="font-family:'Microsoft YaHei';font-size:14px;"><!--配置springmvc DispatcherServlet-->
- <servlet>
- <servlet-name>springMVC</servlet-name>
- <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
- <init-param>
- <!--Sources标注的文件夹下需要新建一个spring文件夹-->
- <param-name>contextConfigLocation</param-name>
- <param-value>/WEB-INF/configs/spring-mvc.xml</param-value>
- </init-param>
- <load-on-startup>1</load-on-startup>
- </servlet>
- <servlet-mapping>
- <servlet-name>springMVC</servlet-name>
- <url-pattern>/</url-pattern>
- </servlet-mapping></span>
在main resources下新建 jdbc.properties 和 log4j.properties 代码如下
- <span style="font-family:'Microsoft YaHei';font-size:14px;">jdbc.driver=com.mysql.jdbc.Driver
- jdbc.url=jdbc:mysql://localhost:3306/ssm?useUnicode=true&characterEncoding=utf-8
- jdbc.username=root
- jdbc.password=你的密码</span>
- <span style="font-family:'Microsoft YaHei';font-size:14px;">#配置根Logger 后面是若干个Appender
- log4j.rootLogger=DEBUG,A1,R
- #log4j.rootLogger=INFO,A1,R
- # ConsoleAppender 输出
- log4j.appender.A1=org.apache.log4j.ConsoleAppender
- log4j.appender.A1.layout=org.apache.log4j.PatternLayout
- log4j.appender.A1.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss,SSS} [%c]-[%p] %m%n
- # File 输出 一天一个文件,输出路径可以定制,一般在根路径下
- log4j.appender.R=org.apache.log4j.DailyRollingFileAppender
- <span style="color:#ff0000;">log4j.appender.R.File=logs/log.txt//log日志文件存储位置</span>
- log4j.appender.R.MaxFileSize=500KB
- log4j.appender.R.MaxBackupIndex=10
- log4j.appender.R.layout=org.apache.log4j.PatternLayout
- log4j.appender.R.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSS} [%t] [%c] [%p] - %m%n</span>
然后在resource下新建 applicationContext.xml 进行spring mybatis 整合配置
下面是我的spring xml 文件配置内容
- <span style="font-family:'Microsoft YaHei';font-size:14px;"><?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:aop="http://www.springframework.org/schema/aop"
- xmlns:context="http://www.springframework.org/schema/context"
- xmlns:p="http://www.springframework.org/schema/p"
- 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/aop
- http://www.springframework.org/schema/aop/spring-aop-4.1.xsd
- http://www.springframework.org/schema/tx
- http://www.springframework.org/schema/tx/spring-tx-4.1.xsd
- http://www.springframework.org/schema/context
- http://www.springframework.org/schema/context/spring-context-4.1.xsd " >
- <!--1.1 引用注解-->
- <context:component-scan base-package="com.frank"/>
- <!--1.1 关联jdbc.properties-->
- <context:property-placeholder location="classpath:jdbc.properties"/>
- <!-- 01.配置数据源 -->
- <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
- <property name="driverClassName" value="${jdbc.driver}"></property>
- <property name="url" value="${jdbc.url}"></property>
- <property name="username" value="${jdbc.username}"></property>
- <property name="password" value="${jdbc.password}"></property>
- </bean>
- <!-- mybatis和spring完美整合,不需要mybatis的配置映射文件 -->
- <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
- <property name="dataSource" ref="dataSource"/>
- <!-- 自动扫描mapping.xml文件 -->
- <property name="mapperLocations" value="classpath:mapping/*.xml"></property>
- </bean>
- <!-- 03.生成dao代理對象-->//<span style="color:#ff0000;">这里没有配置好的话注解找不到对象</span>
- <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
- <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
- <property name="basePackage" value="com.frank.dao"></property>
- </bean>
- </beans></span>
- <span style="font-family:'Microsoft YaHei';font-size:14px;">
- </span>
- <span style="font-family:'Microsoft YaHei';font-size:14px;">
- </span>
- <span style="font-family:'Microsoft YaHei';font-size:14px;"></span>
- <span style="font-family:'Microsoft YaHei';font-size:14px;"><strong>xml配置完成后 在web.xml 进行相同的文件声明</strong></span>
- <span style="font-family:'Microsoft YaHei';font-size:14px;">
- </span>
- <span style="font-family:'Microsoft YaHei';font-size:14px;"><!--配置Spring-->
- <context-param>
- <param-name>contextConfigLocation</param-name>
- <param-value>classpath:applicationContext.xml</param-value>
- </context-param>
- </span>
- <span style="font-family:'Microsoft YaHei';font-size:14px;">
- <!-- 注册ServletContext监听器,创建容器对象,并且将ApplicationContext对象放到Application域中 -->
- <listener>
- <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
- </listener>
- <!-- 防止spring内存溢出监听器,比如quartz -->
- <listener>
- <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
- </listener></span>
- <span style="font-family:'Microsoft YaHei';font-size:14px;"><strong>配置完成后 ,我们的ssm框架算是已经稍微成型了</strong></span>
第三步 搭建mapper 映射
首先创建实体类 User
- <span style="font-family:'Microsoft YaHei';font-size:14px;">public class User {
- private int userID;
- private String userName;
- private String password;
- public String getPassword() {
- return password;
- }
- public void setPassword(String password) {
- this.password = password;
- }
- public int getUserID() {
- return userID;
- }
- public void setUserID(int userID) {
- this.userID = userID;
- }
- public String getUserName() {
- return userName;
- }
- public void setUserName(String userName) {
- this.userName = userName;
- }
- }</span>
- <span style="font-family:'Microsoft YaHei';font-size:14px;">package com.frank.dao;
- import com.frank.bean.User;
- import org.mybatis.spring.annotation.MapperScan;
- import org.springframework.stereotype.Component;
- import org.springframework.stereotype.Repository;
- import java.util.List;
- @Repository<!--这里使用注解-->
- public interface UserMapper {
- public void save(User user);
- public void update(User user);
- public User findById(int id);
- public List<User> findAll();
- public void deleteById(int id);
- }
- </span>
我们在resources文件夹下新建mapping文件夹 ,里面创建我们的UserMapper
这里就包含了用户的增删改查的数据库操作,需要注意的是,在进行用户列表显示时,需要用到ResultMap,需要对里面的对象进行声明,如下 property代表实体类的属性名
而 column显而易见代表的是数据库的列名
下面select等语句中的id代表dao类中的方法名称
- <span style="font-family:'Microsoft YaHei';font-size:14px;"><?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">
- <!--
- namespace:必须与对应的接口全类名一致 UserMapper.java
- id :必须与对应接口的某个对应的方法名一致即必须要和UserMapper.java接口中的方法同名。
- -->
- <mapper namespace="com.frank.dao.UserMapper">
- <resultMap id="StudentList" type="com.frank.bean.User">
- <id property="userID" column="userID"/>
- <result property="userName" column="userName"/>
- <result property="password" column="password"/>
- </resultMap>
- <insert id="save" parameterType="com.frank.bean.User">
- INSERT into user(userName,passWord) VALUES (#{userName},#{password})
- </insert>
- <update id="update" parameterType="com.frank.bean.User">
- UPDATE user SET userName=#{userName},passWord=#{password} where userID=#{userID}
- </update>
- <select id="findByID" parameterType="int" resultType="com.frank.bean.User">
- SELECT * FROM user WHERE userID=#{id}
- </select>
- <select id="findAll" resultMap="StudentList">
- SELECT * from user
- </select>
- <delete id="deleteById" parameterType="int">
- DELETE FROM USER WHERE userID=#{id}
- </delete>
- </mapper></span>
这样我们的dao层已经算是写完了,下面是service层
- <span style="font-family:'Microsoft YaHei';font-size:14px;">package com.frank.service;
- import com.frank.bean.User;
- import com.frank.dao.UserMapper;
- import org.springframework.beans.factory.annotation.Autowired;
- import java.util.List;
- public interface UserService {
- public void save(User user);
- public void update(User user);
- public User findById(int id);
- public List<User> findAll();
- public void deleteById(int id);
- }
- </span>
- <span style="font-family:'Microsoft YaHei';font-size:14px;">package com.frank.servicelmpl;
- import com.frank.bean.User;
- import com.frank.dao.UserMapper;
- import com.frank.service.UserService;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.stereotype.Service;
- import java.util.List;
- @Service
- public class UserServicelmpl implements UserService {
- @Autowired()
- private UserMapper userMapper;
- public void save(User user) {
- userMapper.save(user);
- }
- public void update(User user) {
- userMapper.update(user);
- }
- public User findById(int id) {
- return userMapper.findById(id);
- }
- public List<User> findAll() {
- return userMapper.findAll();
- }
- public void deleteById(int id) {
- userMapper.deleteById(id);
- }
- }
- </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>