SSM 框架搭建

 

 

 

1、在pom.xml中加入spring/springmvc、mybatis的依赖jar包等

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>SSM06</groupId>
    <artifactId>SSM06</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>
    <build>
        <sourceDirectory>src</sourceDirectory>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.5.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
            <plugin>
                <artifactId>maven-war-plugin</artifactId>
                <version>3.0.0</version>
                <configuration>
                    <warSourceDirectory>WebContent</warSourceDirectory>
                </configuration>
            </plugin>
        </plugins>
    </build>
    <dependencies>
        <!-- mybatis依赖 -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.3.1</version>
        </dependency>
        <!-- 数据库连接池 -->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-dbcp2</artifactId>
            <version>2.1.1</version>
        </dependency>
        <!-- spring及springmvc的依赖 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>4.1.9.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>4.1.9.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.3.1</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>4.1.9.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</artifactId>
            <version>4.1.9.RELEASE</version>
        </dependency>
        <!-- 标准标签库 -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
        <!-- 对json数据的支持jar -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.8.10</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.8.10</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>2.8.10</version>
        </dependency>
    </dependencies>
</project>

2、在web.xml中加入spring监听器,并将其指向配置文件spring-mvc.xml、spring-mybatis.xml

  加入springmvc的核心拦截器Servlet,加入对字符集的过滤器filter

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
  <display-name>SSM06</display-name>
      <listener>
        <description>spring监听器</description>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring-mvc.xml;classpath:spring-mybatis.xml</param-value>
    </context-param>

    <!--     spring提供的字符集的过滤器 -->
    <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>

    <!--   springmvc的核心拦截器是一个servlet -->
    <servlet>
          <servlet-name>springmvc</servlet-name>
          <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
          <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath: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>

    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
        <welcome-file>index.htm</welcome-file>
        <welcome-file>index.jsp</welcome-file>
        <welcome-file>default.html</welcome-file>
        <welcome-file>default.htm</welcome-file>
        <welcome-file>default.jsp</welcome-file>
    </welcome-file-list>
</web-app>

3、创建springmvc的配置文件spring-mvc.xml,并配置对注解的扫描、对模型视图的解析、对json数据的支持、对静态资源的拦截放过;

  创建spring管理数据库的配置文件spring-mybatis.xml,并配置对链接资源的引入及获取、扫描映射文件及dao文件的位置、对事物的管理(服务层方法)。

  spring-mvc.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:p="http://www.springframework.org/schema/p" 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 
http://www.springframework.org/schema/mvc 
http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <!-- 自动扫描controller包下的所有类,使其认为spring mvc的控制器 -->
    <context:component-scan base-package="com" />
    <!--spring对注解的支持 这个配置和  <mvc:annotation-driven /> 是同一个意思,只不过是来自于不同的包 -->
    <!-- <context:annotation-config></context:annotation-config> -->
    <!-- 对模型视图名称的解析,即在模型视图名称添加前后缀 -->
    <bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver"
        p:prefix="/" p:suffix=".jsp" />
    
    <!-- 让springmvc放过对静态资源的拦截 -->
    <mvc:annotation-driven /> 
    <mvc:resources location="/js/" mapping="/js/**"></mvc:resources>
    <mvc:resources location="/css/" mapping="/css/**"></mvc:resources>
    <mvc:resources location="/img/" mapping="/img/**"></mvc:resources>

    <!-- 对josn数据的支持 -->
    <bean id="jsonConverter"
        class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"></bean>
    <bean id="stringConverter"
        class="org.springframework.http.converter.StringHttpMessageConverter">
        <property name="supportedMediaTypes">
            <list>
                <value>text/plain;charset=UTF-8</value>
            </list>
        </property>
    </bean>
    <bean
        class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
        <property name="messageConverters">
            <list>
                <ref bean="stringConverter" />
                <ref bean="jsonConverter" />
            </list>
        </property>
    </bean>
</beans>

  spring-mybatis.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:tx="http://www.springframework.org/schema/tx"
    xmlns:aop="http://www.springframework.org/schema/aop" 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/tx 
http://www.springframework.org/schema/tx/spring-tx.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
">
    <!-- 引入属性文件 -->
    <context:property-placeholder location="classpath:jdbc.properties" />

    <!-- spring管理数据库链接 -->
    <bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource"
        destroy-method="close">
        <property name="driverClassName" value="${jdbc.driverClassName}" />
        <property name="url" value="${jdbc.url}" />
        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
        <!-- 配置连接池的初始值 -->
        <property name="initialSize" value="1" />
        <!-- 连接池的最大值 -->
        <!-- <property name="maxActive" value="500"/> -->
        <!-- 最大空闲时,当经过一个高峰之后,连接池可以将一些用不到的连接释放,一直减少到maxIdle为止 -->
        <!-- <property name="maxIdle" value="2"/> -->
        <!-- 当最小空闲时,当连接少于minIdle时会自动去申请一些连接 -->
        <property name="minIdle" value="1" />
        <property name="maxTotal" value="100" />
        <property name="maxIdle" value="20" />
        <property name="maxWaitMillis" value="1000" />
    </bean>

    <!-- Mybatis映射文件的位置 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <!-- 自动扫描entity目录, 省掉Configuration.xml里的手工配置 -->
        <property name="mapperLocations" value="classpath:com/mapping/*.xml" />
    </bean>

    <!-- DAO接口文件的位置 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.dao" />
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
    </bean>

    <!-- 配置Spring的事务处理  声明式事务- -->
        <!-- 配置事务管理器 -->
        <bean id="transactionManager"
            class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
            <property name="dataSource" ref="dataSource" />
        </bean>

        <!-- 注解方式配置事物 -->
        <tx:annotation-driven transaction-manager="transactionManager" />

        <!-- 拦截器方式配置事物 -->
        <tx:advice id="transactionAdvice" transaction-manager="transactionManager">
            <tx:attributes>
                <tx:method name="add*" propagation="REQUIRED" />
                <tx:method name="append*" propagation="REQUIRED" />
                <tx:method name="insert*" propagation="REQUIRED" />
                <tx:method name="save*" propagation="REQUIRED" />
                <tx:method name="update*" propagation="REQUIRED" />
                <tx:method name="modify*" propagation="REQUIRED" />
                <tx:method name="edit*" propagation="REQUIRED" />
                <tx:method name="delete*" propagation="REQUIRED" />
                <tx:method name="remove*" propagation="REQUIRED" />
                <tx:method name="repair" propagation="REQUIRED" />
                <tx:method name="delAndRepair" propagation="REQUIRED" />

                <tx:method name="get*" propagation="SUPPORTS"/>
                <tx:method name="find*" propagation="SUPPORTS" />
                <tx:method name="load*" propagation="SUPPORTS" />
                <tx:method name="search*" propagation="SUPPORTS" />
                <tx:method name="datagrid*" propagation="SUPPORTS" />

                <tx:method name="*" propagation="SUPPORTS" read-only="true"/>
            </tx:attributes>
        </tx:advice>

        <!-- 配置AOP,Spring是通过AOP来进行事务管理的,将事务切入点控制在服务层的方法中 -->
        <aop:config>
            <aop:pointcut id="transactionPointcut"
                expression="execution(* com.service.*.*(..))" />
            <aop:advisor pointcut-ref="transactionPointcut"
                advice-ref="transactionAdvice" />
        </aop:config>
    
</beans>

  jdbc.properties

jdbc.driverClassName = oracle.jdbc.driver.OracleDriver
jdbc.url = jdbc:oracle:thin:@localhost:1521:orcl
jdbc.username = java
jdbc.password = java123

 4、创建pojo层实体类

Student.java
package com.pojo;

import java.util.Date;
//学员和专业  多对一 多方
public class Student {
    int stuid;
    String stuName;
    int stuAge;
    Date stuDate;
    String stuSex;
    String stuProfess;//专业外键字段,可以保留
    String status;
    String professName;//为了方便业务,补充一个专业名字的属性
    Profess profess;//专业对象,做级联查询
    
    public int getStuid() {
        return stuid;
    }
    public void setStuid(int stuid) {
        this.stuid = stuid;
    }
    public String getStuName() {
        return stuName;
    }
    public void setStuName(String stuName) {
        this.stuName = stuName;
    }
    public int getStuAge() {
        return stuAge;
    }
    public void setStuAge(int stuAge) {
        this.stuAge = stuAge;
    }
    public Date getStuDate() {
        return stuDate;
    }
    public void setStuDate(Date stuDate) {
        this.stuDate = stuDate;
    }
    public String getStuSex() {
        return stuSex;
    }
    public void setStuSex(String stuSex) {
        this.stuSex = stuSex;
    }
    public String getStuProfess() {
        return stuProfess;
    }
    public void setStuProfess(String stuProfess) {
        this.stuProfess = stuProfess;
    }
    public String getStatus() {
        return status;
    }
    public void setStatus(String status) {
        this.status = status;
    }
    public String getProfessName() {
        return professName;
    }
    public void setProfessName(String professName) {
        this.professName = professName;
    }
    public Profess getProfess() {
        return profess;
    }
    public void setProfess(Profess profess) {
        this.profess = profess;
    }
}

  Profess.java

package com.pojo;
//一对多 一方

import java.util.List;

public class Profess {
    int proid;
    String professName;
    List<Student> stus;

    public int getProid() {
        return proid;
    }
    public void setProid(int proid) {
        this.proid = proid;
    }
    public String getProfessName() {
        return professName;
    }
    public void setProfessName(String professName) {
        this.professName = professName;
    }
    public List<Student> getStus() {
        return stus;
    }
    public void setStus(List<Student> stus) {
        this.stus = stus;
    }
}

5、创建dao层接口

IStudentDAO.java
package com.dao;

import java.util.List;

import com.pojo.Student;

public interface IStudentDAO {

    List<Student> manyToOne();
}

6、创建Mapping层映射文件

  Student.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.dao.IStudentDAO">
    <!--     学员和专业的多对一映射 -->
    <resultMap type="com.pojo.Student" id="stu_profess">
        <id property="stuid" column="stuid"/>
        <result property="stuName" column="stuName"/>
        <result property="stuAge" column="stuAge"/>
        <result property="stuDate" column="stuDate"/>
        <result property="stuSex" column="stuSex"/>
        <result property="stuProfess" column="stuProfess"/>
        <!--多对一 -->
        <association property="profess" javaType="com.pojo.Profess">
            <id property="proid" column="proid"></id>
            <result property="professName" column="professName"/>
        </association>
    </resultMap>

    <!--     多对一的查询,查询学员同时查出专业信息 -->
    <select id="manyToOne" resultMap="stu_profess">
        select * from student a,profess b where a.stuProfess=b.proid
    </select>
</mapper>

7、创建service层服务接口+实现类

IStudentService.java
package com.service;

import java.util.List;

import com.pojo.Student;

public interface IStudentService {

    List<Student> findStudent();

}

  StudentService.java

package com.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.dao.IStudentDAO;
import com.pojo.Student;

@Service
public class StudentService implements IStudentService {

    @Autowired
    IStudentDAO stuDAO;
    
    public List<Student> findStudent(){
        List<Student> stus = stuDAO.manyToOne();
        return stus;
    }
}

8、创建controller层控制器

  LoginController.java

package com.controller;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.pojo.User;

@Controller
public class LoginController {
    @RequestMapping("/login")
    public String login(User user,HttpServletRequest req){
        System.out.println(user.getUsername());
        System.out.println(req.getRequestURI());
        return "redirect:success";//重定向
    }
    
    @RequestMapping(value="/login2", method = RequestMethod.POST)
    public ModelAndView login2(User user){
        ModelAndView mav = new ModelAndView();
        mav.setViewName("success");//设置要跳转的视图名
        mav.addObject("user", user);//在request范围保存数据

        return mav;//默认是转发
    }
}

  StudentController.java

package com.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.pojo.Student;
import com.service.IStudentService;

@Controller
public class StudentController {
    @Autowired
    IStudentService stuSer;
    
    public void setStuSer(IStudentService stuSer) {
        this.stuSer = stuSer;
    }

    @RequestMapping("/findstu")
    public ModelAndView findStu(){
        ModelAndView mav = new ModelAndView();

        List<Student> stus = stuSer.findStudent();

        mav.addObject("list", stus);
        mav.setViewName("student");

        return mav;
    }
}

9、创建登录页面、登录成功页面、学员信息展示页面

  login.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE html>
<html>
<head>
<base href="<%=basePath%>"/>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
    <form action="login2" method="post">
        用户名:<input name="username"><br>
        密码:<input type="password" name="pwd"><br>
        <input type="submit" value="登录">
    </form>
</body>
</html>

  success.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE html>
<html>
<head>
<base href="<%=basePath%>"/>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
    欢迎${user.username}登录
    <p>
        <a href="findstu">查询学员信息</a>
    </p>
</body>
</html>

  student.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE html>
<html>
<head>
<base href="<%=basePath%>"/>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
    <table style="width: 500px">
        <c:forEach items="${list }" var="stu">
            <tr>
                <td>${stu.stuName }</td>
                <td>${stu.profess.professName }</td>
            </tr>
        </c:forEach>
    </table>
</body>
</html>

10、运行项目。

登录页面==>点击登录==>登录控制器==>登录成功页面==>点击查询学员信息==>学员管理控制器==>学员信息展示页面

posted @ 2019-05-05 11:42  五柳先生柳三变  阅读(276)  评论(0编辑  收藏  举报