投稿 资料上传 搜索
您现在的位置是: 首页 > 文章 > 正文

javaWeb开发ssm框架搭建步骤详解

ssm框架搭建详细步骤介绍

介绍

    在学习javaweb开发中,常用框架的学习是很重要的,通过使用框架进行开发,可以很大程度的提升开发效率,减少开发者的工作量。随着互联网高速发展,软件开发中使用的框架也是层出不穷,目前使用最广的框架应该是属于ssm这三大框架,下面就来收悉一下ssm框架的使用。

注:在使用SSM搭建框架之前,需要收悉一下springmvc、spring、mybatis。

SSM框架搭建步骤

注:本文采用idea开发工具搭建,eclipse工具都差不多

1.创建一个javaweb maven项目,具体创建方式可参考上一篇“IDEA通过maven构建JavaWeb项目步骤详解

2.修改项目结构,如下图:


3.根据上图结构添加mybatis-config.xml 文件

<?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>
    <!--开启驼峰命名自动转换
    一般数据库命名规则一般是user_name,而我们实体类中一般使用userName,
    开启后就可以自动映射了
    -->
    <settings>
        <setting name="mapUnderscoreToCamelCase" value="true"></setting>
    </settings>
</configuration>

4.添加mapper.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.cn.itcdns.mapper.UserMapper">
    <!--id的值:要和接口UserMapper下的方法名一致
    resultType:1.要和方法返回值类型一样,或者是返回值类型的集合
               2.原本需要写返回值类型的权限定名路径,
                但是我们在applicationContext里配置了别名所属的包
               所以只要写类名即可     -->
    <select id="findAllUsers" resultType="User">
		select * from user
	</select>
</mapper>

5.添加jdbc.properties 文件

jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssm_db
jdbc.username=root
jdbc.password=root

6.添加applicationContext.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:aop="http://www.springframework.org/schema/aop"
       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/aop
        http://www.springframework.org/schema/aop/spring-aop.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">

    <!-- 引入外部的属性资源文件,把我们刚刚配置的jdbc配置文件引入进来 -->
    <context:property-placeholder location="classpath:jdbc.properties"/>
    <!-- 扫包,只需要扫service的即可,Controller的包springMVC会扫描,
        mapper层的,下面类会帮我们扫描 -->
    <context:component-scan base-package="com.cn.itcdns.service">
    </context:component-scan>
    <!-- 使用专门扫描mapper接口的类 -->
    <bean>
        <property name="basePackage" value="com.cn.itcdns.mapper"></property>
    </bean>

    <!-- 配置数据源 ,这里了用的是阿里巴巴的德鲁伊数据源-->
    <bean id="dataSource">
        <property name="driverClassName" value="${jdbc.driverClass}"></property>
        <property name="url" value="${jdbc.url}"></property>
        <property name="username" value="${jdbc.username}"></property>
        <property name="password" value="${jdbc.password}"></property>
    </bean>
    <!--sqlSession工厂,我们对数据库增删改查就靠他-->
    <bean id="sqlSessionFactory">
        <!-- 注入配置的数据源 -->
        <property name="dataSource" ref="dataSource"></property>
        <!-- 注入mybatis-config配置文件 -->
        <property name="configLocation" 
            value="classpath:mybatis/mybatis-config.xml">
        </property>
        <!-- 注入mapper.xml文件位置,
        这里的/**/*.xml写法,只要是/mybatis/mapper下的都可以注入进来,
        哪怕里面又加了几个文件夹-->
        <property name="MapperLocations" value="classpath:mybatis/mapper/**/*.xml">
        </property>
        <!-- 配置别名所属的包名,配置了这个,我们UserMapper.xml文件下的
            resultType就只需要写类名即可-->
        <property name="typeAliasesPackage" value="com.cn.itcdns.domain">
        </property>
    </bean>


    <!-- 配置事务管理器 -->
    <bean id="transactionManager" 
         >
        <property name="dataSource" ref="dataSource"></property>
    </bean>
    <!-- 配置事务属性 -->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <!--配置事务的属性,如果方法名是find开头,只允许查询业务,
            不允许增删改业务,这样可以防错,如果写了删除或者增加功能,
            则会抛出异常,提醒开发人员-->
            <tx:method name="find*" read-only="true"/>
            <!--其他方法做增删改功能-->
            <tx:method name="*"/>
        </tx:attributes>
    </tx:advice>
    <!-- 配置切面
    配置了事务后,我们肯定要告诉spring,哪些方法需要加上事务 -->
    <aop:config>
        <!--配置切点-->
        <aop:pointcut expression="execution(* com.agu.service.impl.*.*(..))" 
            id="pointcut"/>
        <!--将advice注入程序中pointcut位置的代码-->
        <aop:advisor advice-ref="txAdvice" pointcut-ref="pointcut"/>
    </aop:config>
</beans>

7.添加springmvc-servlet.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:mvc="http://www.springframework.org/schema/mvc"
       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/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">
    <!-- 开启注解扫描,扫描controller包 -->
    <context:component-scan base-package="com.cn.itcdns.controller">
    </context:component-scan>

    <!-- mvc注解驱动 -->
    <mvc:annotation-driven></mvc:annotation-driven>

    <!-- 配置springMVC视图解析器 -->
    <bean>
        <!--有时我们需要将数据响应到某个页面,例如响应到/jsp/users.jsp,
            controller只需要返回"users"-->
        <!--url路径的前缀-->
        <property name="prefix" value="/WEB-INF/jsp/"></property>
        <!--url路径的后缀-->
        <property name="suffix" value=".jsp"></property>
    </bean>

    <!-- 处理静态资源拦截问题,如果是静态资源的请求,则默认服务器的servlet处理,
     如果不是,则交给DispatcherServlet处理-->
    <mvc:default-servlet-handler/>
</beans>

8.修改web.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns="http://java.sun.com/xml/ns/javaee"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">

  <!-- 配置字节码过滤器 -->
  <filter>
    <filter-name>encodingFilter</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>
  </filter>
  <filter-mapping>
    <filter-name>encodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

  <!-- 指定spring配置文件名 -->
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:spring/applicationContext.xml</param-value>
  </context-param>
  <!-- 工程启动时,创建IOC容器 -->
  <listener>
    <listener-class>
        org.springframework.web.context.ContextLoaderListener
    </listener-class>
  </listener>

  <!-- springmvc入口 -->
  <servlet>
    <servlet-name>springmvc</servlet-name>
    <servlet-class>
        org.springframework.web.servlet.DispatcherServlet
    </servlet-class>
    <!-- 指定springmvc配置文件路径 -->
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:spring/springmvc-servlet.xml</param-value>
    </init-param>
    <!--项目启动时,就加载此servlet  -->
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>springmvc</servlet-name>
    <!-- 拦截除了jsp以外的所有请求(不是/*) -->
    <url-pattern>/</url-pattern>
  </servlet-mapping>

</web-app>

9.创建实体Bean,例如:User.java

package com.cn.itcdns.domain;
import java.io.Serializable;
import java.util.Date;

import org.springframework.format.annotation.DateTimeFormat;

public class User implements Serializable {

    private static final long serialVersionUID = 1L;

    private Long id;

    // 用户名
    private String userName;

    // 密码
    private String password;

    // 姓名
    private String name;

    // 年龄
    private Integer age;

    // 性别,1男性,2女性
    private Integer sex;

    // 出生日期
    @DateTimeFormat(pattern = "yyyy-MM-dd")
    private Date birthday;

    // 创建时间
    private Date created;

    // 更新时间
    private Date updated;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public Integer getSex() {
        return sex;
    }

    public void setSex(Integer sex) {
        this.sex = sex;
    }

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    public Date getCreated() {
        return created;
    }

    public void setCreated(Date created) {
        this.created = created;
    }

    public Date getUpdated() {
        return updated;
    }

    public void setUpdated(Date updated) {
        this.updated = updated;
    }

    @Override
    public String toString() {
        return "User [id=" + id + ", userName=" + userName 
                +".password=" + password + ", name=" + name
                + ", age=" + age + ", sex=" + sex
                +",birthday=" + birthday + ", created=" + created
                + ", updated=" + updated + "]";
    }

}

10.创建DAO,例如:UserMapper.java

package com.cn.itcdns.mapper;

import com.cn.itcdns.domain.User;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface UserMapper{

     List<User> findAllUsers();

}

11.定义service接口,例如:UserService.java

package com.cn.itcdns.service;

import com.cn.itcdns.domain.User;

import java.util.List;

public interface UserService {
    /**
     * 查询所有用户信息
     * @return
     */
    List<User> findAllUsers();


}

12.定义UserService接口实现,例如:UserServiceImpl.java

package com.cn.itcdns.service.impl;

import com.cn.itcdns.domain.User;
import com.cn.itcdns.mapper.UserMapper;
import com.cn.itcdns.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public List<User> findAllUsers() {
        List<User> list = userMapper.findAllUsers();
        return list;
    }

}

13.定义controller控制器,例如:UserController.java

package com.cn.itcdns.controller;

import java.util.List;

import com.cn.itcdns.domain.User;
import com.cn.itcdns.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("user")
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping("list")
    public String test1(Model model) {
        List<User> users = userService.findAllUsers();
        model.addAttribute("userList", users);
        return "userList";
    }
}

14.创建jsp页面,例如:userList.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Insert title here</title>
    <link rel="stylesheet" type="text/css" href="/css/user.css"/>
</head>
<body>
<table id="customers" border="1px">
    <tr>
        <th>编号</th>
        <th>用户名</th>
        <th>姓名</th>
        <th>年龄</th>
        <th>性别</th>
        <th>出生日期</th>
        <th>创建时间</th>
        <th>更新时间</th>
    </tr>
    <c:forEach items="${userList}" var="user">
        <tr>
            <td>${user.id}</td>
            <td>${user.userName}</td>
            <td>${user.name}</td>
            <td>${user.age}</td>
            <td>
                <c:choose>
                    <c:when test="${user.sex==1}">男</c:when>
                    <c:otherwise>女</c:otherwise>
                </c:choose>
            </td>
            <td>
                <fmt:formatDate value="${user.birthday}" pattern="yyyy-MM-dd"/>
            </td>
            <td>
                <fmt:formatDate value="${user.created}" pattern="yyyy-MM-dd HH:mm:ss"/>
            </td>
            <td>
                <fmt:formatDate value="${user.updated}" pattern="yyyy-MM-dd HH:mm:ss"/>
            </td>
        </tr>
    </c:forEach>
</table>
</body>
</html>

到此,项目创建完毕,将项目编译后打包放入到tomcat中启动,访问得到如下结果:



转载于:

文章标签:
阿里云服务器采购季
给作者打赏,鼓励TA抓紧创作!
评论