入门级的SSM架构搭建解析

这里没有用到项目管理工具例如SVN和maven


1.导入相关jar包
这里不做多余的解释了下载Spring和SpringMvc相关jar包
log4j,mysql相关包以及与mybatis-spring整合包,jstl包,数据源包,就可以了
2.编写目录层级
eg:
com.demo.controller
IndexController.java
com.demo.dao
UserMapper.java
UserMapper.xml
com.demo.entity
User.java
com.demo.service
UserService.java
UserServiceImpl.java
com.demo.test(用来进行测试)

如果任务需要还可以写一层VO
(com.demo.vo
QueryVo.java

3.创建source文件夹管理xml和一些数据库配置文件以及log4j
eg:
applicationContext-dao.xml (dao层管理)

    <bean
        //引用db.properties配置文件
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
        p:location="classpath:db.properties" />

        /*这段代码<import resource="applicationContext-service.xml"/>是用来做测试用的,如果确定没有问题不导入也行,区别在于是在哪里看一种在页面上调试一种在IDE控制台中代码上调试*/
        <import resource="applicationContext-service.xml"/>


        //dbcp数据源找到BasicDataSource类路径
        <bean name="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
            <property name="driverClassName"  value="${driver}"/>
            <property name="url"              value="${url}"/> 
            <property name="username"         value="${username}"/>
            <property name="password"         value="${password}"/>
        </bean>

        //通过Spring框架管理sqlsession并注入dataSource,配置一些mybatis中的配置
        <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"
        p:dataSource-ref="dataSource"
        p:typeAliasesPackage="com.demo.entity"
        p:configLocation="classpath:mybatis-config.xml"
        />

        //开启mapper接口扫描只要mapper接口和mapper.xml在一起默认会采用当前mapper接口名开头小写
        <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer" 
        p:basePackage="com.demo.dao" />

applicationContext-service.xml (service层管理)

  //扫描service层spring注解
  <context:component-scan base-package="com.demo.service" />

applicationContext-trans.xml (事物管理)

<!-- 事务管理器 -->
//开启事物管理器
    <bean id="transactionManager"
        class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!-- 引入数据源 ,因为web.xml中配置了Spring配置扫描,所以这里可以用ref引用-->
        <property name="dataSource" ref="dataSource" />
    </bean>

    <!-- 通知 -->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <!-- 传播行为 -->
            <tx:method name="save*" propagation="REQUIRED" />
            <tx:method name="insert*" propagation="REQUIRED" />
            <tx:method name="delete*" propagation="REQUIRED" />
            <tx:method name="update*" propagation="REQUIRED" />
            <tx:method name="find*" propagation="SUPPORTS" read-only="true" />
            <tx:method name="get*" propagation="SUPPORTS" read-only="true" />
        </tx:attributes>
    </tx:advice>

    <!-- 切面 -->
    <aop:config>
        <aop:advisor advice-ref="txAdvice"
        //定义切面
            pointcut="execution(* com.demo.service.*.*(..))" />
    </aop:config>

mybatis-config.xml (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>
<!-- 加入自己想配置的代码   基础搭建代码为空也即可,前面dao配置已经配置过了-->
</configuration>

db.properties (数据库配置文件)
log4j.properties (log4j文件)
SpringMvc.xml (SpringMvc的配置控制controller层)

    <!-- 注解扫描 -->
  <context:component-scan base-package="com.demo.controller" />
   <!-- 注解驱动,帮我们配置最新的   处理器适配器  和   处理器解析器 -->
   <mvc:annotation-driven />
        <!-- 视图解析器 ,InternalResourceViewResolver常用于.jsp视图解析-->
        <bean 
        class="org.springframework.web.servlet.view.InternalResourceViewResolver"
        p:prefix="/WEB-INF/jsp/"
        p:suffix=".jsp"
        />
        <!--/WEB-INF/jsp/下   以.jsp结尾的文件 -->

4.编写web.xml
(1)首先要进行加载Spring容器加入监听器

<!-- 加载spring容器 -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        /*扫描applicationContext-*.xml  (*通配符) */
        <param-value>classpath:applicationContext-*.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

(2)配置SpringMvc前端控制器

<?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_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>SpringProject4</display-name>
  <welcome-file-list>//程序默认地址
    <welcome-file>/WEB-INF/jsp/login.jsp</welcome-file>
  </welcome-file-list>

<!-- SpringMvc配置前端控制器 -->
    <servlet>
        <servlet-name>Spring</servlet-name>
         /*指定SpringMvc前端控制器*/
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

        <init-param>
            <param-name>contextConfigLocation</param-name>
            /*扫面Spring-mvc配置文件,只要是spring配置文件路径全使用classpath: 形式*/
            <param-value>classpath:SpringMvc.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>Spring</servlet-name>
        <url-pattern>*.action</url-pattern>//路径方式可自定义只要符合规格即可eg:/*
    </servlet-mapping>

(3)配置基本的 Filter过滤器

<!-- Filter过滤器 配置post请求乱码 -->
    <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>

    </filter>
    <filter-mapping>
        <filter-name>CharacterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    </web-app>

到此web.xml配置完毕。


5.编写各个包
(1)pojo包

package com.demo.entity;

public class User {
    private int userId;
    private String userName;
    private String password;
    private String email;
    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;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    public String getAddress() {
        return address;
    }
    public void setAddress(String address) {
        this.address = address;
    }
    private String address;
}

(2)dao

package com.demo.dao;

import org.apache.ibatis.annotations.Param;

import com.demo.entity.User;
import com.demo.vo.QueryVo;

public interface UserMapper {


    User selectLogin1(User user);

    User selectLogin2(@Param("userName")String userName,@Param("password")String password);

    User selectLogin3(QueryVo queryVo);

}

同包下的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.demo.dao.UserMapper">

<select id="selectLogin1" parameterType="user" resultType="user">

select * from user where userName=#{userName} and password=#{password}
</select>
<select id="selectLogin2" resultType="user">

select * from user where userName=#{userName} and password=#{password}

</select>

<select id="selectLogin3" resultType="user" parameterType="com.demo.vo.QueryVo">

select * from user where userName=#{user.userName} and password=#{user.password}

</select>
</mapper>   

(3)service下

package com.demo.service;

import org.apache.ibatis.annotations.Param;

import com.demo.entity.User;
import com.demo.vo.QueryVo;

public interface UserService {

    User selectLogin1(User user);

    User selectLogin2(@Param("userName")String userName,@Param("password")String password);


    User selectLogin3(QueryVo queryVo);

}

service实现类

package com.demo.service;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.demo.dao.UserMapper;
import com.demo.entity.User;
import com.demo.vo.QueryVo;

@Transactional
@Service(value="userService")
public class UserServiceImpl implements UserService {

    @Resource(name="userMapper")
    private UserMapper userMapper;

    @Override
    public User selectLogin1(User user) {
        // TODO Auto-generated method stub
        return userMapper.selectLogin1(user);
    }

    @Override
    public User selectLogin2(String userName, String password) {
        // TODO Auto-generated method stub
        return userMapper.selectLogin2(userName, password);
    }

    @Override
    public User selectLogin3(QueryVo queryVo) {
        // TODO Auto-generated method stub
        return userMapper.selectLogin3(queryVo);
    }

}

(4)controller

package com.demo.controller;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.demo.entity.User;
import com.demo.service.UserService;
import com.demo.vo.QueryVo;
//Spring框架Controller注解也就是action
@Controller
@RequestMapping("/user")        //访问地址路径
public class IndexController {

    @Resource(name="userService")//jdk自带注解
    private UserService userService;


    @RequestMapping("/log1")    //访问地址路径/user/log1
    public String login1(User user,Model model){
        User user1 = userService.selectLogin1(user);
        if(user1!=null){
            model.addAttribute("msg", "登录成功");
        }else{
            model.addAttribute("msg", "登录失败");
        }
        return "msg";  //返回String类型SpringMvc把这个String当成逻辑视图的地址
        //返回值也可以是ModelAndView
    }

    //SpringMvc会自动转换基本数据类型但是要求表单name值与下面属性名相同
    @RequestMapping("/log2")
    public String login2(@RequestParam String userName,@RequestParam String password
            ,Model model){
            //RequestParamp配置一些传参数的要求其中有一个默认属性required为true即必须填写
        User user = userService.selectLogin2(userName, password);
        if(user!=null){
            model.addAttribute("msg", "登录成功");
        }else{
            model.addAttribute("msg", "登录失败");
        }
        return "msg";
    }

    //
    @RequestMapping("/log3")
    public String login3(QueryVo queryVo,Model model){

        User user = userService.selectLogin3(queryVo);
        if(user!=null){
            model.addAttribute("msg", "登录成功");
        }else{
            model.addAttribute("msg", "登录失败");
        }
        return "msg";
    }
}

(5)Vo

package com.demo.vo;

import com.demo.entity.User;

/*Vo的作用比较好
本人理解:
SpringMvc会自动帮你进行【拆】与【装】
拆:Mapper.xml中通常传入对象引用直接写对象的属性即可,
而用了Vo这个类会帮拆除一层那么就到了Vo中的属性
在mapper.xml中自己写入条件
eg:userName=#{user.userName}
装:form表单input标签中的name为Vo属性的属性的属性的属性......
eg:name="user.userName"
他就会帮你装入Vo属性中的User类中的userName属性
*/
public class QueryVo {

    private User user;

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }
}

(6)自定义的测试

package com.test;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.demo.entity.User;
import com.demo.service.UserService;

public class UserTest {

//这里面能狗调用applicationContext-dao.xml是因为上面部分导入了service层的XML为了做测试成没成功

    @Test
    public void run1(){
        ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext-dao.xml");
        UserService userService = (UserService)ac.getBean("userService");

        User user = userService.selectLogin2("1141193930","12312300a");
        if(user==null){
            System.out.println("用户名密码错误");
        }else{
            System.out.println("登录成功");
        }

    }
}

WEB-INF/jsp/jsp简单页面
login.jsp


    <form action="${pageContext.request.contextPath }/user/log1" method="post">

    账号:<input type="text" name="userName"/><br>
    密码:<input type="text" name="password"/><br>
    <input type="submit" value="登录"/>

    </form>

    <hr/>

    <form action="${pageContext.request.contextPath }/user/log2" method="post">

    账号:<input type="text" name="userName"/><br>
    密码:<input type="text" name="password"/><br>
    <input type="submit" value="登录"/>

    </form>
    <hr/>

    <form action="${pageContext.request.contextPath }/user/log3" method="post">

    账号:<input type="text" name="user.userName"/><br>
    密码:<input type="text" name="user.password"/><br>
    <input type="submit" value="登录"/>

    </form>

msg.jsp页面测试是否接收成功

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!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>
</head>
<body>
消息:${msg}

</body>
</html>

层级目录:
这里写图片描述
这里写图片描述


启动程序进行测试
开启concat服务器

这里写图片描述

打开页面成功
这里写图片描述

页面跳转并判断成功
这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值