前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Spring、SpringMVC、MyBatis整合

Spring、SpringMVC、MyBatis整合

作者头像
CBeann
发布2023-12-25 16:14:51
1390
发布2023-12-25 16:14:51
举报
文章被收录于专栏:CBeann的博客

项目的目:做一个登陆页面inddex.jsp,然后在数据库中查询用户名和密码,如果匹配成功,跳转到success.jsp,不成功跳转到error.jsp

1创建项目

2加入jar和三个框架的配置文件(注意配置文件的位置)

2.1)applicationContxt.xml

代码语言:javascript
复制
<?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:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop"
	xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
		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-4.0.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">

	<!-- 配置自动扫描的包,使其自动注入到IOC容器 -->
	<context:component-scan base-package="com.imooc.service"></context:component-scan>

	<!-- 导入资源文件 -->
	<context:property-placeholder location="classpath:db.properties" />

	<!-- 配置数据源 -->
	<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
		<property name="user" value="${jdbc.user}"></property>
		<property name="password" value="${jdbc.password}"></property>
		<property name="driverClass" value="${jdbc.driverClass}"></property>
		<property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property>
		<property name="initialPoolSize" value="${jdbc.initPoolSize}"></property>
		<property name="maxPoolSize" value="${jdbc.maxPoolSize}"></property>
	</bean>


	<!-- 配置MyBatis的SqlSession -->
	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		<property name="dataSource" ref="dataSource" />
		<!-- 配置MyBatis的配置的文件 -->
		<property name="configLocation" value="classpath:mybatis.xml"></property>
	</bean>

	<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
	    <!-- 自动扫描 com.imooc.dao下的interface,并加入IOC容器-->
		<property name="basePackage" value="com.imooc.dao" />
		<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
	</bean>

	<!-- 开启事务 -->
	<bean id="transactionManager"
		class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource" ref="dataSource" />
	</bean>


	<!-- 可通过注解控制事务 -->
	<tx:annotation-driven transaction-manager="transactionManager" />


</beans>

2.2)applicationContext-mvc.xml

代码语言:javascript
复制
<?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:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop"
	xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
		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-4.0.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">

	<!-- 配置自动扫描的包,使其自动注入到IOC容器 -->
	<context:component-scan base-package="com.imooc.service"></context:component-scan>

	<!-- 导入资源文件 -->
	<context:property-placeholder location="classpath:db.properties" />

	<!-- 配置数据源 -->
	<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
		<property name="user" value="${jdbc.user}"></property>
		<property name="password" value="${jdbc.password}"></property>
		<property name="driverClass" value="${jdbc.driverClass}"></property>
		<property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property>
		<property name="initialPoolSize" value="${jdbc.initPoolSize}"></property>
		<property name="maxPoolSize" value="${jdbc.maxPoolSize}"></property>
	</bean>


	<!-- 配置MyBatis的SqlSession -->
	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		<property name="dataSource" ref="dataSource" />
		<!-- 配置MyBatis的配置的文件 -->
		<property name="configLocation" value="classpath:mybatis.xml"></property>
	</bean>

	<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
	    <!-- 自动扫描 com.imooc.dao下的interface,并加入IOC容器-->
		<property name="basePackage" value="com.imooc.dao" />
		<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
	</bean>

	<!-- 开启事务 -->
	<bean id="transactionManager"
		class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource" ref="dataSource" />
	</bean>


	<!-- 可通过注解控制事务 -->
	<tx:annotation-driven transaction-manager="transactionManager" />


</beans>

2.3)mybatis.xml

代码语言:javascript
复制
<?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.imooc.entity.User设置为User 
	如果不设置别名<select id="selectDemo" resultType="com.imooc.entity.User"> ***</select>
	设置别名            <select id="selectDemo" resultType="User">***</select>
	 -->
	<typeAliases>
		<package name="com.imooc.entity"></package>
	</typeAliases>

        <!--添加mapper.xml-->
	<mappers>
		<mapper resource="com/imooc/mapper/UserMapper.xml" />
	</mappers>


</configuration>

2.4)db.properties

代码语言:javascript
复制
jdbc.user=root
jdbc.password=root
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.jdbcUrl=jdbc:mysql://localhost:3306/text
jdbc.initPoolSize=5
jdbc.maxPoolSize=10
#...

3将下面的配置加入到web.xml

代码语言:javascript
复制
<!-- 设置字符过滤器,防止乱码,必须加在所有的Filter之前 -->
	<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>
		<init-param>
			<param-name>forceEncoding</param-name>
			<param-value>true</param-value>
		</init-param>
	</filter>
	<filter-mapping>
		<filter-name>characterEncodingFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>


	<!-- SpringMVC -->
	<servlet>
		<servlet-name>springDispatcherServlet</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>classpath:applicationContext-mvc.xml</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
		<servlet-name>springDispatcherServlet</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>

4创建package和class代码

UserMapper.java

代码语言:javascript
复制
package com.imooc.dao;

public interface UserMapper {
	
	//根据username查询password
	String selectPassword(String username);

}

User.java

代码语言:javascript
复制
package com.imooc.entity;

public class User {
	private Integer id;
	private String username;
	private String password;

	public User() {
		super();
	}

	public User(String username, String password) {
		super();
		this.username = username;
		this.password = password;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see java.lang.Object#toString()
	 */
	@Override
	public String toString() {
		return "User [id=" + id + ", username=" + username + ", password=" + password + "]";
	}

	/**
	 * @return the id
	 */
	public Integer getId() {
		return id;
	}

	/**
	 * @param id
	 *            the id to set
	 */
	public void setId(Integer id) {
		this.id = id;
	}

	/**
	 * @return the username
	 */
	public String getUsername() {
		return username;
	}

	/**
	 * @param username
	 *            the username to set
	 */
	public void setUsername(String username) {
		this.username = username;
	}

	/**
	 * @return the password
	 */
	public String getPassword() {
		return password;
	}

	/**
	 * @param password
	 *            the password to set
	 */
	public void setPassword(String password) {
		this.password = password;
	}
}

LoginHandler.java

代码语言:javascript
复制
package com.imooc.handler;

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

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

@Controller
public class LoginHandler {
	
	@Autowired
	private UserService userService;
	
	@RequestMapping("/login.action")
	public String login(User user){
		String password=userService.login(user.getUsername());
		if(!user.getPassword().equals(password)){
			return "error";
		}else{
			return "success";
		}
	}
	
	
	
	
	

	/**
	 * @return the userService
	 */
	public UserService getUserService() {
		return userService;
	}

	/**
	 * @param userService the userService to set
	 */
	public void setUserService(UserService userService) {
		this.userService = userService;
	}
	
	
	

}

UserMapper.xml

代码语言:javascript
复制
<?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.imooc.dao.UserMapper">




	<select id="selectPassword"  resultType="String">
		select password from user where username = #{username}
	</select>
	



</mapper>

UserService.java

代码语言:javascript
复制
package com.imooc.service;

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

import com.imooc.dao.UserMapper;



@Service
public class UserService {
	
	@Autowired
	private UserMapper userDao;
	
	
	public String login(String username){
		return userDao.selectPassword(username);
	}
	
	
	
	
	

	public UserService() {
		super();
	}

	/**
	 * @return the userDao
	 */
	public UserMapper getUserDao() {
		return userDao;
	}

	/**
	 * @param userDao the userDao to set
	 */
	public void setUserDao(UserMapper userDao) {
		this.userDao = userDao;
	}
	
	
	

}

5创建JSP

index.jsp

代码语言:javascript
复制
<%@ 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>

<form action="login.action" method="post">
username<input type="text"  name="username"><br/>
password<input type="password"  name="password"><br/>
<input type="submit" value="Submit">
</form>
</body>
</html>

success.jsp

代码语言:javascript
复制
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!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=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
success.jsp
</body>
</html>

error.jsp

代码语言:javascript
复制
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!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=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
error.jsp
</body>
</html>

6总结

1 jar包问题,如果你的jar包有问题(http://pan.baidu.com/s/1pKOyrBP),当然我也很菜,jar包版本很乱,不报错就好

2还有一种省去MyBatis.xml的的整合方法,其实我感觉还是有比较好,而且这个配置文件你复制一下就好,也没有过繁琐的配置

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2022-03-07,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1创建项目
  • 2加入jar和三个框架的配置文件(注意配置文件的位置)
    • 2.1)applicationContxt.xml
      • 2.2)applicationContext-mvc.xml
        • 2.3)mybatis.xml
          • 2.4)db.properties
          • 3将下面的配置加入到web.xml
          • 4创建package和class代码
            • UserMapper.java
              • User.java
                • LoginHandler.java
                  • UserMapper.xml
                    • UserService.java
                    • 5创建JSP
                      • index.jsp
                        • success.jsp
                          • error.jsp
                          • 6总结
                          相关产品与服务
                          容器服务
                          腾讯云容器服务(Tencent Kubernetes Engine, TKE)基于原生 kubernetes 提供以容器为核心的、高度可扩展的高性能容器管理服务,覆盖 Serverless、边缘计算、分布式云等多种业务部署场景,业内首创单个集群兼容多种计算节点的容器资源管理模式。同时产品作为云原生 Finops 领先布道者,主导开源项目Crane,全面助力客户实现资源优化、成本控制。
                          领券
                          问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档