springmvc-spring-mybatis框架整合

     最近整合框架真的遇到了很多麻烦,以前没有做笔记的习惯,但是这一次感觉真的该好好记录一下这个过程,因为网上其实蛮多ssm框架教程的,但是我还是遇到很多麻烦,所以好不容易弄好的框架还是想好好整理一下.希望自己以后遇到问题的时候能够积极的去解决,而不是像这次一样烦躁然后不想弄,问题是一直在的,逃不掉.好好学习,加油.


1 .创建项目:我创建的是Maven项目,之后添加各种文件夹,最后的项目框架是这样的:


2. 配置pom.xml 由于我在网上找了很多项目学习,所以pom.xml中的依赖也是学习他们的,具体的一些插件的新版本要是有兴趣再去查一下,暂时我先用着这些

<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/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.hualu</groupId>
  <artifactId>trainee</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>trainee Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <spring.version>5.0.4.RELEASE</spring.version>
    <jackson.version>2.5.0</jackson.version>
  </properties>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    
    <!-- spring配置 -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-core</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-beans</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-tx</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
      <version>${spring.version}</version>
      <scope>test</scope>
    </dependency>

    <!-- mybatis 包 -->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.2.8</version>
    </dependency>

    <!--mybatis spring 插件 -->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>1.2.2</version>
    </dependency>

    <!-- mysql连接 -->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.34</version>
    </dependency>

    <!-- 数据源 -->
    <dependency>
      <groupId>com.mchange</groupId>
      <artifactId>c3p0</artifactId>
      <version>0.9.5-pre8</version>
    </dependency>

    <dependency>
      <groupId>org.aspectj</groupId>
      <artifactId>aspectjweaver</artifactId>
      <version>1.8.4</version>
    </dependency>
    <!-- log4j -->
    <dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
      <version>1.2.17</version>
    </dependency>

    <!-- servlet -->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>servlet-api</artifactId>
      <version>3.0-alpha-1</version>
    </dependency>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>jstl</artifactId>
      <version>1.2</version>
    </dependency>
    <!-- json -->
    <dependency>
      <groupId>org.codehaus.jackson</groupId>
      <artifactId>jackson-mapper-asl</artifactId>
      <version>1.9.13</version>
    </dependency>
    <!-- 文件上传 -->
    <dependency>
      <groupId>commons-io</groupId>
      <artifactId>commons-io</artifactId>
      <version>2.4</version>
    </dependency>

    <dependency>
      <groupId>commons-fileupload</groupId>
      <artifactId>commons-fileupload</artifactId>
      <version>1.2.2</version>
    </dependency>
  </dependencies>
  <build>
    <finalName>trainee</finalName>
  </build>
</project>

3. 在config包下创建以下配置文件


3.1 jdbc.properties:

jdbc_driverClassName=com.mysql.jdbc.Driver
jdbc_url=jdbc:mysql://localhost:3306/hualu?useUnicode=true&characterEncoding=utf-8
jdbc_username=root
jdbc_password=1234

3.2 applicationContext.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
      http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
      http://www.springframework.org/schema/context
      http://www.springframework.org/schema/context/spring-context.xsd">

    <!--引入jdbc配置 -->
    <context:property-placeholder location="classpath*:config/jdbc.properties"/>
    <!--  扫描文件(自动将service层注入)-->
    <context:component-scan base-package="com.hualu.service"/>
    <!--配置数据源-->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${jdbc_driverClassName}"/>
        <property name="jdbcUrl" value="${jdbc_url}"/>
        <property name="user" value="${jdbc_username}"/>
        <property name="password" value="${jdbc_password}"/>
        <!--连接池中保存的最大连接数目-->
        <property name="maxPoolSize" value="20"/>
        <!--连接池中保存的最少连接数目-->
        <property name="minPoolSize" value="2"/>
        <!-- 初始化连接大小 -->
        <property name="initialPoolSize" value="2"/>
        <!-- 获取连接最大等待时间 -->
        <property name="maxConnectionAge" value="6000"/>
        <!-- 连接池最大空闲 -->
        <property name="maxIdleTime" value="60"/>
    </bean>

    <!--配置sqlSessionFactory 并将数据源注入-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!--注入数据源-->
        <property name="dataSource" ref="dataSource"/>
        <!--指定要使用到到mybatis配置文件-->
        <property name="configLocation" value="classpath:config/config.xml"/>
        <!--用于配置mapper映射xml-->
        <property name="mapperLocations" value="classpath*:com/hualu/mapper/*.xml"/>
    </bean>
    <!-- 创建数据映射器-->
    <bean  class="org.mybatis.spring.mapper.MapperScannerConfigurer">
          <property name="basePackage" value="com.hualu.dao"/>

    </bean>
    <!-- 对数据源进行事务管理 -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>

</beans>

3.3 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>
    <!--为com.hualu.model.User设置别名 User 方便调用-->
    <typeAliases>
        <typeAlias alias="User" type="com.hualu.model.User"/>
    </typeAliases>


</configuration>

3.4  spring-mvc.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
      xmlns:context="http://www.springframework.org/schema/context"
      xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="
       http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context-3.0.xsd
       http://www.springframework.org/schema/mvc
       http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

    <!--扫描控制器,当配置了它后,Spring会自动的到com.hualu.controller
    下扫描带有@controller @service @component等注解等类,将他们自动实例化-->
    <context:component-scan base-package="com.hualu.controller" />

    <!--<mvc:annotation-driven /> 会自动注册DefaultAnnotationHandlerMapping与
    AnnotationMethodHandlerAdapter 两个bean,它解决了一些@controllerz注解使用时的提前配置-->
   <mvc:annotation-driven />

   <!--配置 页面控制器-->
     <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsps/"/>
        <property name="suffix" value=".jsp" />

     </bean>

</beans>

4. 各种类的编写


(备注:关于数据库:

数据库超级简单,贴一下表结构:

users:

)

(注意::: 如果不是很清楚项目目录,一定要注意每个类的所属包,这样就不容易搞混了)

 4.1  com.hualu.model 下的User.java

package com.hualu.model;

public class User {
	private String users_id;
	private String password;
	public String getUsers_id() {
		return users_id;
	}
	public void setUsers_id(String users_id) {
		this.users_id = users_id;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}

}

4.2 com.hualu.dao下的!!!接口!!!IUserDao.java(是接口!接口)

package com.hualu.dao;

import com.hualu.model.User;

public interface IUserDao {

	public User selectById(String users_id);
}

4.3 com.hualu.service下的!!!接口!!!:UserService.java  和该接口实现类:UserServiceImpl.java

package com.hualu.service;

public interface UserService {

	public boolean login(String username,String password);
}

实现类:

package com.hualu.service;

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

import com.hualu.dao.IUserDao;
import com.hualu.model.User;

@Service("UserService")
public class UserServiceImpl implements UserService {

	@Autowired
	IUserDao Mapper;
	public boolean login(String username, String password) {
		//System.out.println("输入的账号:"+username+"输入的密码:"+password);
		// TODO Auto-generated method stub
		User user=Mapper.selectById(username);
		if(user!=null) {
			//System.out.println("查询出来的账号:"+user.getUsers_id()+"查询出来的密码"+user.getPassword());
			if(user.getPassword().equals(password))
				return true;
		}
		return false;
	}

}

4.4 com.hualu.mapper下的User.xml

(注意:命名空间一定要和对应的接口名称一样,不然会出错.

select的id也要和接口中的抽象方法相同!!!

)
<?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.hualu.dao.IUserDao">
    <select id="selectById" parameterType="string" resultType="User">
        select * from users where users_id=#{users_id}
    </select>

</mapper>

4.5 com.hualu.controller下的UserController.java
package com.hualu.controller;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

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

@Controller
@RequestMapping("/user")
@Scope("prototype")
public class UserController {

	@Autowired
	 UserService userService;
	
	@RequestMapping("/login")
	public String login(User user,HttpServletRequest request) {
		boolean loginType=userService.login(user.getUsers_id(), user.getPassword());
		if(loginType) {
			request.setAttribute("user", user);
			return "success";
		}
		else {
			request.setAttribute("message", "用户名或密码错误");
			return "fail";
		}
	}
}

5 到现在可以写一个测试类来测试数据库是否有错:



Test.java:

package test;

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

import com.hualu.dao.IUserDao;
import com.hualu.model.User;

public class Test {

	private static ApplicationContext ac;
	static {
		ac=new ClassPathXmlApplicationContext("config/applicationContext.xml");
	}
	public static void main(String[] args) {
		IUserDao mapper=(IUserDao)ac.getBean("IUserDao");
		System.out.println("获取资料");
		User user=mapper.selectById("1614813726@qq.com");
		
		System.out.println(user.getUsers_id()+user.getPassword());
	}
}
运行如果没错,继续下面的内容,如果有错的话好好改吧,不要生气,不要急躁,不要生气,不要生气

6  web.xml:

<?xml version="1.0" encoding="utf-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee" version="2.4" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
   <!-- Spring配置 -->
   <!-- 配置Spring配置文件路径,好让ContextLoaderListener对其加载与解析-->
      <context-param>
    <param-name>contextConfigLocation</param-name>
     <param-value>
           classpath*:config/applicationContext.xml
       </param-value>
   </context-param>
    <!-- 配置Spring上下文监听器,它的作用就是在启动WEB容器时,就会自动装在我们applicationContext.xml配置-->
    <listener>
     <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
   </listener>
    <!-- 配置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>
      <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>
    
    <!-- Spring MVC 核心控制器 DispatcherServlet 配置 -->
  <servlet>
    <servlet-name>dispatcher</servlet-name>
     <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
      <init-param>
         <!--用于标明spring-mvc.xml配置的位置,我是存放在config文件夹下-->
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath*:config/spring-mvc.xml</param-value>
   </init-param>
     <load-on-startup>1</load-on-startup>
   </servlet>
    <servlet-mapping>
       <servlet-name>dispatcher</servlet-name>
      <!-- 拦截所有*.do 的请求,交给DispatcherServlet处理,性能最好 -->
       <url-pattern>*.do</url-pattern>
   </servlet-mapping>
       <!--用于设定默认首页-->
   <welcome-file-list>
        <welcome-file>login.jsp</welcome-file>
    </welcome-file-list>
 </web-app>

7 .网页相关:



7.1 login.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">
<%
    String path = request.getContextPath();
    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
 %>

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" >
<title>Insert title here</title>

</head>
<body>
<br>
<br>
<br>
<br>
<form name="form1" action="<%=basePath%>user/login.do" method="post">
   <table>
       <tr>
         <td colspan="2">登入窗口</td>
       </tr>
       <tr>
          <td>用户名:</td>
          <td><input type="text" name="users_id">
          </td>
       </tr>
       <tr>
         <td>密码:</td>
         <td><input type="password" name="password"/>
         </td>
       </tr>
       <tr>
          <td colspan="2">
            <input type="submit" name="submit" value="登录">
          </td>
       </tr>
    </table>
</form>
</body>
</html>

7.2 fail.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">
<%
  String path = request.getContextPath();
  String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
 %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
 登入失败!
${message}
 <br>
<a href="<%=path%>/login.jsp">返回</a>
</body>
</html>

7.3 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 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>
登入成功!
 <br>
您好!${user.users_id}
<br>
<a href="/login.jsp">返回</a>
</body>
</html>

8.代码完成了,接下来部署项目测试啦啦啦啦啦啦啦啦啦



登录失败:


登录成功:



由于能力有限,这个项目非常简单.如果有错误,欢迎大家指正.


哇卡卡卡卡,人生中第一篇博客,虽然很简单但是还是很开心啊

可是昨天关于英法助美对叙动手.....哪有什么白与黑啊!

peace and love




阅读更多
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页