第一个SSM框架的搭建-eclipse亲测成功运行

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Apple_hzc/article/details/82725626

今天抽空学习快速搭建第一个SSM框架,需要的所有jar包在以下百度云链接中请自行下载。

链接:https://pan.baidu.com/s/18IDmHvByrrGTXBu023U15Q 密码:wufn

一、创建Dynamic Web项目,并导入jar包

创建一个Dynamic Web Project并命名为SSM,先看一下该项目的整个框架结构:

先将下载好的jar包全部粘贴到WebContent下WEB-INF里的lib文件夹中,然后开始配置相关文件。


二、相关包及配置文件的编写

com.model(与数据库表中的成员以及属性一一对应)

新建一个java文件,用来存储数据库中对应的admin属性:

package com.model;

public class User {
	private String id = null;
	private String username = null;
	private String password = null;
	private int age = 0;
	private String sex = null;
	public String getId() {
		return id;
	}
	public void setId(String 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 int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public String getSex() {
		return sex;
	}
	public void setSex(String sex) {
		this.sex = sex;
	}
	
}

com.mapper(Mabatis逆向工程根据数据库表生成model属性以及mapper.xml文件)

UserMapper.java

package com.mapper;
import java.util.List;
import com.model.*;

public interface UserMapper {
	public int findAgeById(String id);
	public String findNameById(String id);
}

UserMapper.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.mapper.UserMapper">

    <select id="findAgeById" parameterType="String" resultType="int">
        select age from admin WHERE id=#{id} 
    </select>
    <select id = "findNameById" parameterType="String" resultType="String">
    	select username from admin where id=#{id}
    </select>

</mapper>

com.service(业务层,调用UserMapper接口对数据库进行操作)

UserService.java

package com.service;
import java.util.List;
import com.model.*;

public interface UserService {
	public int findAgeById(String id);
	public String findNameById(String id);
}

UserServiceImpl.java

package com.service;
import java.util.List;

import javax.annotation.Resource;

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

import com.mapper.UserMapper;
import com.model.User;
import com.service.UserService;

@Service
@Transactional
public class UserServiceImpl implements UserService{
	@Resource
	public UserMapper userMapper;
	@Override
	public int findAgeById(String id) {
		// TODO Auto-generated method stub
		int age = userMapper.findAgeById(id);
        return age;
	}
	@Override
	public String findNameById(String id) {
		// TODO Auto-generated method stub
		String username = userMapper.findNameById(id);
		return username;
	}
	
}

com.controller(控制器统一管理)

package com.controller;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.model.User;
import com.service.UserService;

@Controller
public class UserCotroller {
	@Autowired
    private UserService userService;

    @RequestMapping(value="/hello.do")
    public String findAgeById(HttpServletRequest request)
    {
        int age=userService.findAgeById("1410313114");
        System.out.println(age);//如果实验成功,在控制台会打印年龄21
        return "index";
    }
    
    @RequestMapping(value="/hello1.do")
    public String findNameById(HttpServletRequest request)
    {
    	String id = request.getParameter("id");
        String username = userService.findNameById(id);
        System.out.println(username);
        return "index";
    }
}

config包(相关配置文件)

1.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:p="http://www.springframework.org/schema/p"
    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-4.0.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-4.0.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">

    <!-- 1. 数据源 : DriverManagerDataSource -->
    <bean id="dataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://localhost:3306/easyvideo" />
        <property name="username" value="root" />
        <property name="password" value="123456" />
    </bean>

    <!--
        2. mybatis的SqlSession的工厂: SqlSessionFactoryBean dataSource:引用数据源

        MyBatis定义数据源,同意加载配置
    -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"></property>
        <property name="configLocation" value="classpath:config/mybatis-config.xml" /> 
    </bean>

    <!--
        3. mybatis自动扫描加载Sql映射文件/接口 : MapperScannerConfigurer sqlSessionFactory

        basePackage:指定sql映射文件/接口所在的包(自动扫描)
    -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.mapper"></property>
        <property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
    </bean>

    <!--
        4. 事务管理 : DataSourceTransactionManager dataSource:引用上面定义的数据源
    -->
    <bean id="txManager"
        class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>

    <!-- 5. 使用声明式事务
         transaction-manager:引用上面定义的事务管理器
     -->
    <tx:annotation-driven transaction-manager="txManager" />

</beans>

注:如果想通过数据库连接池对数据库进行操作,除了将上述数据源相关代码换成以下代码,还应在lib中添加相应的druid jar包:

<!-- 数据库连接池 -->
	<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" destroy-method="close">
		<property name="driverClassName" value="com.mysql.jdbc.Driver" />
		<property name="url" value="jdbc:mysql://localhost:3306/easyvideo?useUnicode=true&amp;characterEncoding=UTF-8" />
		<property name="username" value="root" />
		<property name="password" value="150000" />
		<property name="maxActive" value="20" />
		<property name="minIdle" value="5" />
	</bean>

2.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>
    <typeAliases>
        <typeAlias alias="User" type="com.model.User"/>
    </typeAliases>
    <mappers>
        <mapper resource="com/mapper/UserMapper.xml" />
    </mappers>
</configuration>

3.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.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-4.0.xsd
    http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">

    <!-- 注解扫描包 -->
    <context:component-scan base-package="com" />

    <!-- 开启注解 -->
    <mvc:annotation-driven />

    <!-- 定义跳转的文件的前后缀 ,视图模式配置-->
    <bean id="viewResolver"
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!-- 这里的配置我的理解是自动给后面action的方法return的字符串加上前缀和后缀,变成一个 可用的url地址 -->
        <property name="prefix" value="/" />
        <property name="suffix" value=".jsp" />
    </bean>
</beans>

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_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>SSM</display-name>
  <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>hello.jsp</welcome-file>
  </welcome-file-list>
  
   <!-- 加载Spring容器配置 -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <!-- 设置Spring容器加载所有的配置文件的路径 -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath*:config/applicationContext.xml</param-value>
    </context-param>

    <!-- 配置SpringMVC核心控制器 -->
    <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*:config/spring-mvc.xml</param-value>
        </init-param>
        <!-- 启动加载一次 -->  
        <load-on-startup>1</load-on-startup>
    </servlet>

    <!--为DispatcherServlet建立映射 -->
    <servlet-mapping>
        <servlet-name>springMVC</servlet-name>
        <!-- 此处可以可以配置成*.do -->
        <url-pattern>*.do</url-pattern>
    </servlet-mapping>

    <!-- 防止Spring内存溢出监听器 -->
    <listener>
        <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
    </listener>

    <!-- 解决工程编码过滤器 -->
    <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>
        <init-param>
            <param-name>forceEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>

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

到这里,所有的配置文件均已完成。


三、简单jsp页面与数据库的交互

写一个简单的hello.jsp页面,用来提交一个简单的表单:

<body>
	<form action="hello1.do" method="post">
    	hello:<input type="text" name="id"/>
    	<input type="submit" value="提交" /> 
	</form>
</body>

写一个index.jsp页面用于提交后的跳转,若成功跳转,则显示ok。

通过测试,在input中输入数据库中admin表的任一行中的id属性,点击提交,则成功跳转到index.jsp页面,并在控制台成功输出该id属性对应的username。

在以后的时间里,会慢慢深入了解框架的底层原理,并及时总结与分享。

猜你喜欢

转载自blog.csdn.net/Apple_hzc/article/details/82725626
今日推荐