MyBatis整合spring、spring MVC实现简单登陆,并在控制台添加sql语句打印

时间:2024-10-30 12:07:35

新建项目

1,使用eclipse创建动态web工程,取工程名MyBatisTest。我的环境是tomcat8.5,jdk1.8

2,添加项目需要的jar包


项目配置

打开WebContent(WebRoot)/WEB-INF下的文件,配置如下:
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <web-app xmlns:xsi="http:///2001/XMLSchema-instance"
  3. xmlns="/xml/ns/javaee"
  4. xsi:schemaLocation="/xml/ns/javaee /xml/ns/javaee/web-app_3_1.xsd"
  5. id="WebApp_ID" version="3.1">
  6. <display-name>MyBatisTest</display-name>
  7. <welcome-file-list>
  8. <welcome-file></welcome-file>
  9. </welcome-file-list>
  10. <!-- Spring配置文件 -->
  11. <context-param>
  12. <param-name>contextConfigLocation</param-name>
  13. <param-value>classpath:</param-value>
  14. </context-param>
  15. <!-- 编码过滤器 -->
  16. <filter>
  17. <filter-name>encodingFilter</filter-name>
  18. <filter-class></filter-class>
  19. <async-supported>true</async-supported>
  20. <init-param>
  21. <param-name>encoding</param-name>
  22. <param-value>UTF-8</param-value>
  23. </init-param>
  24. </filter>
  25. <filter-mapping>
  26. <filter-name>encodingFilter</filter-name>
  27. <url-pattern>/*</url-pattern>
  28. </filter-mapping>
  29. <!-- Spring监听器 -->
  30. <listener>
  31. <listener-class></listener-class>
  32. </listener>
  33. <!-- 添加对springmvc的支持 -->
  34. <servlet>
  35. <servlet-name>springMVC</servlet-name>
  36. <servlet-class></servlet-class>
  37. <init-param>
  38. <param-name>contextConfigLocation</param-name>
  39. <param-value>classpath:</param-value>
  40. </init-param>
  41. <load-on-startup>1</load-on-startup>
  42. <async-supported>true</async-supported>
  43. </servlet>
  44. <servlet-mapping>
  45. <servlet-name>springMVC</servlet-name>
  46. <url-pattern>/</url-pattern>
  47. </servlet-mapping>
  48. </web-app>
在src目录下新建如下配置文件:

配置如下:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="/schema/beans"
  3. xmlns:xsi="http:///2001/XMLSchema-instance" xmlns:p="/schema/p"
  4. xmlns:aop="/schema/aop" xmlns:context="/schema/context"
  5. xmlns:jee="/schema/jee" xmlns:tx="/schema/tx"
  6. xsi:schemaLocation="
  7. /schema/aop /schema/aop/spring-aop-4.
  8. /schema/beans /schema/beans/spring-beans-4.
  9. /schema/context /schema/context/spring-context-4.
  10. /schema/jee /schema/jee/spring-jee-4.
  11. /schema/tx /schema/tx/spring-tx-4.">
  12. <!-- 加载配置属性文件 -->
  13. <context:property-placeholder
  14. ignore-unresolvable="true" location="classpath:" />
  15. <!-- 使用Annotation自动注册Bean,在主容器中不扫描@Controller注解,在SpringMvc中只扫描@Controller注解。 -->
  16. <context:component-scan base-package="">
  17. <context:exclude-filter type="annotation"
  18. expression="" />
  19. </context:component-scan>
  20. <!-- 数据源配置, 不使用连接池 -->
  21. <bean id="dataSource"
  22. class="">
  23. <property name="driverClassName" value="${}" />
  24. <property name="url" value="${}" />
  25. <property name="username" value="${}" />
  26. <property name="password" value="${}" />
  27. </bean>
  28. <!-- 配置mybatis的sqlSessionFactory -->
  29. <bean id="sqlSessionFactory" class="">
  30. <property name="dataSource" ref="dataSource" />
  31. <!-- 自动扫描文件 -->
  32. <property name="mapperLocations" value="classpath:com/zby/mappers/*.xml"></property>
  33. <!-- mybatis配置文件 -->
  34. <property name="configLocation" value="classpath:"></property>
  35. </bean>
  36. <!-- DAO接口所在包名,Spring会自动查找其下的类 -->
  37. <bean class="">
  38. <property name="basePackage" value="" />
  39. <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
  40. </bean>
  41. <!-- 定义事务 -->
  42. <bean id="transactionManager"
  43. class="">
  44. <property name="dataSource" ref="dataSource" />
  45. </bean>
  46. </beans>
配置如下:
  1. =
  2. =jdbc:mysql://127.0.0.1:3306/mybatis_test?serverTimezone=UTC&characterEncoding=utf8&useSSL=true
  3. =root
  4. =root
log4j.properties配置如下:
  1. =info,appender1,appender2
  2. .appender1=.
  3. .appender2=.
  4. .=D:/
  5. .=.
  6. .=.
配置如下:

  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE configuration
  3. PUBLIC "-////DTD Config 3.0//EN"
  4. "/dtd/">
  5. <configuration>
  6. <settings>
  7. <setting name="logImpl" value="STDOUT_LOGGING"/>
  8. </settings>
  9. <!-- 别名 -->
  10. <typeAliases>
  11. <package name="" />
  12. </typeAliases>
  13. </configuration>
配置如下:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="/schema/beans"
  3. xmlns:xsi="http:///2001/XMLSchema-instance"
  4. xmlns:p="/schema/p"
  5. xmlns:aop="/schema/aop"
  6. xmlns:context="/schema/context"
  7. xmlns:jee="/schema/jee"
  8. xmlns:tx="/schema/tx"
  9. xsi:schemaLocation="
  10. /schema/aop /schema/aop/spring-aop-4.
  11. /schema/beans /schema/beans/spring-beans-4.
  12. /schema/context /schema/context/spring-context-4.
  13. /schema/jee /schema/jee/spring-jee-4.
  14. /schema/tx /schema/tx/spring-tx-4.">
  15. <!-- 使用Annotation自动注册Bean,只扫描@Controller -->
  16. <context:component-scan base-package="" use-default-filters="false"><!-- base-package 如果多个,用“,”分隔 -->
  17. <context:include-filter type="annotation" expression=""/>
  18. </context:component-scan>
  19. <!-- 定义视图文件解析 -->
  20. <bean class="">
  21. <property name="prefix" value="/"/>
  22. <property name="suffix" value=".jsp"/>
  23. </bean>
  24. </beans>

创建数据库

使用mysql5.7,创建数据库mybatis_test,创建表t_user
  1. CREATE TABLE `t_user` (
  2. `id` int(11) NOT NULL AUTO_INCREMENT,
  3. `user_name` varchar(20) DEFAULT NULL,
  4. `user_pwd` varchar(20) DEFAULT NULL,
  5. PRIMARY KEY (`id`)
  6. ) ENGINE=InnoDB
插入数据
insert into t_user(user_name,user_pwd) values("java","1234");

编码实现

jsp文件:,
系统欢迎页面是,输入用户名和密码,若用户名密码正确,跳转至页面,错误则给出提示
内容:
  1. <%@ page language="java" contentType="text/html; charset=UTF-8"
  2. pageEncoding="UTF-8"%>
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http:///TR/html4/">
  4. <html>
  5. <head>
  6. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  7. <title>Insert title here</title>
  8. </head>
  9. <body>
  10. <form action="${ }/user/login" method="post">
  11. userName:<input type="text" name="userName" value="${ }"/><br/>
  12. password:<input type="password" name="userPwd" value="${ }"><br/>
  13. <input type="submit" value="login"/><font color="red">${errorMsg }</font>
  14. </form>
  15. </body>
  16. </html>
内容如下:
  1. <%@ page language="java" contentType="text/html; charset=UTF-8"
  2. pageEncoding="UTF-8"%>
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http:///TR/html4/">
  4. <html>
  5. <head>
  6. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  7. <title>Insert title here</title>
  8. </head>
  9. <body>
  10. 欢迎:${ }
  11. </body>
  12. </html>



entity层:
  1. package ;
  2. public class User {
  3. private Integer id;
  4. private String userName;
  5. private String userPwd;
  6. public Integer getId() {
  7. return id;
  8. }
  9. public void setId(Integer id) {
  10. this.id = id;
  11. }
  12. public String getUserName() {
  13. return userName;
  14. }
  15. public void setUserName(String userName) {
  16. this.userName = userName;
  17. }
  18. public String getUserPwd() {
  19. return userPwd;
  20. }
  21. public void setUserPwd(String userPwd) {
  22. this.userPwd = userPwd;
  23. }
  24. }
映射文件:
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE mapper
  3. PUBLIC "-////DTD Mapper 3.0//EN"
  4. "/dtd/">
  5. <mapper namespace="">
  6. <resultMap type="User" id="UserMap">
  7. <result property="id" column="id"/>
  8. <result property="userName" column="user_name"/>
  9. <result property="userPwd" column="user_pwd"/>
  10. </resultMap>
  11. <select id="login" parameterType="User" resultMap="UserMap">
  12. select * from t_user where user_name = #{userName} and user_pwd = #{userPwd}
  13. </select>
  14. </mapper>
dao层:
  1. package ;
  2. import ;
  3. public interface UserDao {
  4. public User login(User user);
  5. }
service层:
  1. package ;
  2. import ;
  3. import ;
  4. import ;
  5. import ;
  6. @Service
  7. public class UserService {
  8. @Autowired
  9. private UserDao userDao;
  10. public User login(User user) {
  11. return (user);
  12. }
  13. }
controller层:
  1. package ;
  2. import ;
  3. import ;
  4. import ;
  5. import ;
  6. import ;
  7. import ;
  8. import ;
  9. @Controller
  10. @RequestMapping("/user")
  11. public class UserController {
  12. @Autowired
  13. private UserService userService;
  14. @RequestMapping("/login")
  15. public String login(User user,HttpServletRequest request) {
  16. User userResult = (user);
  17. if (userResult == null) {
  18. ("user", userResult);
  19. ("errorMsg", "用户名或密码错误!!");
  20. return "index";
  21. }
  22. else {
  23. HttpSession httpSession = ();
  24. ("currentUser", userResult);
  25. return "success";
  26. }
  27. }
  28. }

启动项目

将项目添加到tomcat,启动tomcat,在浏览器输入http://localhost:8080/MyBatisTest,回车,浏览器显示如下:

输入用户名java,密码1234,点击login,系统跳转至页面


输入用户名java,密码1111,系统提示用户名或密码错误

mybatis配置文件实现控制台打印sql
配置如下红框内容即可

注意
settings必须配置在typeAliases前面,否则会提示
  1. The content of element type "configuration" must match
  2. "(properties?,settings?,typeAliases?,typeHandlers?,objectFactory?,objectWrapperFactory?,reflectorFactory?,plugins?,environments?,databaseIdProvider?,mappers?)".
即配置项必须按照上面提示顺序配置

控制台显示