查看: 6579|回复: 9

Building Java Web Application Using MyBatis With Spring

[复制链接]
招聘 : 系统架构师
论坛徽章:
142
摩羯座
日期:2016-03-30 23:01:17秀才
日期:2015-07-31 14:17:16秀才
日期:2015-07-31 09:12:09秀才
日期:2015-07-28 10:22:54秀才
日期:2015-07-24 09:00:17秀才
日期:2015-07-20 08:54:46秀才
日期:2015-07-15 12:49:25秀才
日期:2015-07-09 09:23:47秀才
日期:2015-07-06 10:44:32秀才
日期:2015-07-06 10:34:54
发表于 2014-3-1 16:26 | 显示全部楼层 |阅读模式
This post will show how to create a Student Enrollment Application using MYSQL DB with MyBatis framework in a Spring environment. This is a simple application that aims to collect the input details from the user during signup, save the details in the MYSQL DB and authenticate the same during login.
  
  
1. Create Java Web Application Project using Maven TemplateTo begin with, in the IDE, create a Java Maven project with the template of maven-archetype-webapp (Filter the catalog based on the string “webapp”) by providing appropriate values for GroupId and Artifact Id for the project. The sample web application directory structure is shown below with a standard deployment descriptor web.xml and Maven pom.xml



招聘 : 系统架构师
论坛徽章:
142
摩羯座
日期:2016-03-30 23:01:17秀才
日期:2015-07-31 14:17:16秀才
日期:2015-07-31 09:12:09秀才
日期:2015-07-28 10:22:54秀才
日期:2015-07-24 09:00:17秀才
日期:2015-07-20 08:54:46秀才
日期:2015-07-15 12:49:25秀才
日期:2015-07-09 09:23:47秀才
日期:2015-07-06 10:44:32秀才
日期:2015-07-06 10:34:54
 楼主| 发表于 2014-3-1 16:28 | 显示全部楼层
2. Update pom.xmlTo make the above Maven Java Web Application project support the MyBatis framework, add the following dependencies to the existing pom.xml:
  • mybatis (for MyBatis support)
  • mybatis-spring (for MyBatis-Spring integration support)
  • jstl, spring-webmvc, servlet-api and spring-context-support (for Spring support)
  • spring-test (may be optional, needed if Spring-test support is needed)
  • mysql-connector-java (for MYSQL support
  1. 01        <dependency>
  2. 02              <groupId>org.mybatis</groupId>
  3. 03              <artifactId>mybatis</artifactId>
  4. 04              <version>3.1.1</version>
  5. 05            </dependency>
  6. 06            <dependency>
  7. 07              <groupId>org.mybatis</groupId>
  8. 08              <artifactId>mybatis-spring</artifactId>
  9. 09              <version>1.1.1</version>
  10. 10            </dependency>
  11. 11            <dependency>
  12. 12              <groupId>org.springframework</groupId>
  13. 13              <artifactId>spring-context-support</artifactId>
  14. 14              <version>3.1.1.RELEASE</version>
  15. 15            </dependency>
  16. 16            <dependency>
  17. 17              <groupId>org.springframework</groupId>
  18. 18              <artifactId>spring-test</artifactId>
  19. 19              <version>3.1.1.RELEASE</version>
  20. 20              <scope>test</scope>
  21. 21            </dependency>
  22. 22            <dependency>
  23. 23              <groupId>mysql</groupId>
  24. 24              <artifactId>mysql-connector-java</artifactId>
  25. 25              <version>5.1.21</version>
  26. 26            </dependency>
  27. 27            <dependency>
  28. 28              <groupId>javax.servlet</groupId>
  29. 29              <artifactId>jstl</artifactId>
  30. 30              <version>1.2</version>
  31. 31            </dependency>
  32. 32            <dependency>
  33. 33              <groupId>org.springframework</groupId>
  34. 34              <artifactId>spring-webmvc</artifactId>
  35. 35              <version>3.2.4.RELEASE</version>
  36. 36            </dependency>
  37. 37            <dependency>
  38. 38              <groupId>javax.servlet</groupId>
  39. 39              <artifactId>servlet-api</artifactId>
  40. 40              <version>2.5</version>
  41. 41            </dependency>
复制代码

3. Modify web.xmlModify the contents of the web.xml to include the following:
  • A servlet and specify the location of the configuration file for the same. In this sample, a configuration file named springConfig.xml is created under WEB-INF/config folder in the project layout.
  • A servlet-mapping to map the servlet created in the above step that should be invoked when the client specifies the url matching the url pattern.

  1. 01        <?xml version="1.0" encoding="UTF-8"?>
  2. 02        <web-app version="2.5"
  3. 03        xmlns="http://java.sun.com/xml/ns/javaee"
  4. 04        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  5. 05        xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  6. 06         
  7. 07        <servlet>
  8. 08          <servlet-name>myBatisServlet</servlet-name>
  9. 09          <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  10. 10          <init-param>
  11. 11              <param-name>contextConfigLocation</param-name>
  12. 12              <param-value>/WEB-INF/config/springConfig.xml</param-value>
  13. 13          </init-param>
  14. 14        </servlet>
  15. 15         
  16. 16        <servlet-mapping>
  17. 17          <servlet-name>myBatisServlet</servlet-name>
  18. 18          <url-pattern>*.html</url-pattern>
  19. 19        </servlet-mapping>
  20. 20         
  21. 21          <display-name>Archetype Created Web Application</display-name>
  22. 22        </web-app>
复制代码


使用道具 举报

回复
招聘 : 系统架构师
论坛徽章:
142
摩羯座
日期:2016-03-30 23:01:17秀才
日期:2015-07-31 14:17:16秀才
日期:2015-07-31 09:12:09秀才
日期:2015-07-28 10:22:54秀才
日期:2015-07-24 09:00:17秀才
日期:2015-07-20 08:54:46秀才
日期:2015-07-15 12:49:25秀才
日期:2015-07-09 09:23:47秀才
日期:2015-07-06 10:44:32秀才
日期:2015-07-06 10:34:54
 楼主| 发表于 2014-3-1 16:30 | 显示全部楼层
4. Create the Spring Configuration FileCreate a Spring Bean Configuration file under the folder WEB-INF/config. If STS(Spring Tool Suite) is the IDE, go ahead and enable the context, mvc and tx namespaces. The springConfig.xml will be as shown below
  1. 01        <?xml version="1.0" encoding="UTF-8"?>
  2. 02        <beans xmlns="http://www.springframework.org/schema/beans"
  3. 03          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. 04          xmlns:context="http://www.springframework.org/schema/context"
  5. 05          xmlns:mvc="http://www.springframework.org/schema/mvc"
  6. 06          xmlns:tx="http://www.springframework.org/schema/tx"
  7. 07          xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
  8. 08              http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
  9. 09              http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
  10. 10              http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd">
  11. 11         
  12. 12        </beans>
复制代码
After enabling the required namespaces, include the following (in between the <beans> and </beans> tags) to indicate that the application is annotation driven and base package for the context component scan.
  1. 1        <mvc:annotation-driven />
  2. 2         
  3. 3        <context:component-scan base-package="com.github.elizabetht" />
复制代码

Include the bean InternalResourceViewResolver of Spring to locate the jsp files
  1. 1        <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  2. 2          <property name="prefix" value="/WEB-INF/jsp/" />
  3. 3          <property name="suffix" value=".jsp" />
  4. 4        </bean>
复制代码

nclude the bean for data source, where the properties of the MYSQL DB like url, username and password can be specified. Replace <include connection url> with the actual connection url for connecting to the MYSQL DB. Likewise, replace <include username> and <include password> with the actual username and password values.
  1. 1        <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
  2. 2          <property name="driverClassName" value="com.mysql.jdbc.Driver" />
  3. 3          <property name="url" value="jdbc:mysql//<include connection url>:3306/studentEnrollment?autoReconnect=true&createDatabaseIfNotExist=true&" />
  4. 4          <property name="username" value="<include username>" />
  5. 5          <property name="password" value="<include password>" />
  6. 6        </bean>
复制代码

Include the bean for transaction manager for scoping/controlling the transactions, that takes the data source defined above as reference (dependent)
1        <tx:annotation-driven transaction-manager="transactionManager" />
2        <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
3          <property name="dataSource" ref="dataSource" />
4        </bean>

Coming to the MyBatis specific configurations, include the bean for sqlSessionFactory which is the central configuration in a MyBatis application. This bean takes in three properties – dataSource (already configured above)  – typeAliasesPackage (location where the model classes of this application resides)  – mapperLocations (location where the mapper xml files for the model resides – this is not needed here as annotation based configurations are used instead)
More details of this can be read at http://mybatis.github.io/mybatis-3/
1        <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
2          <property name="dataSource" ref="dataSource" />
3          <property name="typeAliasesPackage" value="com.github.elizabetht.model"/>
4          <property name="mapperLocations" value="classpath*:com/github/elizabetht/mappers/*.xml" />
5        </bean>
Include the bean for sqlSession
1        <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
2          <constructor-arg index="0" ref="sqlSessionFactory" />
3        </bean>

Next and finally, include the bean for MapperScannerConfigurer
1        <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
2          <property name="basePackage" value="com.github.elizabetht.mappers" />
3        </bean>




使用道具 举报

回复
招聘 : 系统架构师
论坛徽章:
142
摩羯座
日期:2016-03-30 23:01:17秀才
日期:2015-07-31 14:17:16秀才
日期:2015-07-31 09:12:09秀才
日期:2015-07-28 10:22:54秀才
日期:2015-07-24 09:00:17秀才
日期:2015-07-20 08:54:46秀才
日期:2015-07-15 12:49:25秀才
日期:2015-07-09 09:23:47秀才
日期:2015-07-06 10:44:32秀才
日期:2015-07-06 10:34:54
 楼主| 发表于 2014-3-1 16:32 | 显示全部楼层
7. Create classes for Model TierCreate a POJO class named Student.java inside the package com.github.elizabetht.model to include the details of the Student model entity during signup. Create another POJO class named StudentLogin.java inside the same package com.github.elizabetht.model to include the Student Login details.
A reference link to the files for the Model classes can be found at https://github.com/elizabetht/StudentEnrollmentWithMyBatis/tree/master/src/main/java/com/github/elizabetht/model
8. Create classes for MyBatis MapperA Mapper in MyBatis framework is similar to the Repository tier in a Spring environment. Crude SQL queries takes its place here. Create an interface class named StudentMapper.java inside the package com.github.elizabetht.mapper to support the database operations.
There are two interface methods needed for the application’s purpose.
  • To Insert the Student Signup details into the Database
  • To Verify the Student Login details from the Databas
  1. 01        public interface StudentMapper {
  2. 02          @Insert("INSERT INTO student(userName, password, firstName,"
  3. 03                  + "lastName, dateOfBirth, emailAddress) VALUES"
  4. 04                  + "(#{userName},#{password}, #{firstName}, #{lastName},"
  5. 05                  + "#{dateOfBirth}, #{emailAddress})")
  6. 06          @Options(useGeneratedKeys=true, keyProperty="id", flushCache=true, keyColumn="id")
  7. 07          public void insertStudent(Student student);
  8. 08         
  9. 09          @Select("SELECT USERNAME as userName, PASSWORD as password, "
  10. 10                  + "FIRSTNAME as firstName, LASTNAME as lastName, "
  11. 11                  + "DATEOFBIRTH as dateOfBirth, EMAILADDRESS as emailAddress "
  12. 12                  + "FROM student WHERE userName = #{userName}")
  13. 13          public Student getStudentByUserName(String userName);
  14. 14         
  15. 15        }
复制代码


使用道具 举报

回复
招聘 : 系统架构师
论坛徽章:
142
摩羯座
日期:2016-03-30 23:01:17秀才
日期:2015-07-31 14:17:16秀才
日期:2015-07-31 09:12:09秀才
日期:2015-07-28 10:22:54秀才
日期:2015-07-24 09:00:17秀才
日期:2015-07-20 08:54:46秀才
日期:2015-07-15 12:49:25秀才
日期:2015-07-09 09:23:47秀才
日期:2015-07-06 10:44:32秀才
日期:2015-07-06 10:34:54
 楼主| 发表于 2014-3-2 20:16 | 显示全部楼层
10. Create class for Controller TierCreate a Controller tier POJO class named StudentController.java inside the package com.github.elizabetht.controller. This is where the routing logic of the application goes – whether a signup or login action is called.
  1. 01        @Controller
  2. 02        @SessionAttributes("student")
  3. 03        public class StudentController {
  4. 04         
  5. 05          @Autowired
  6. 06          private StudentService studentService;
  7. 07         
  8. 08          @RequestMapping(value="/signup", method=RequestMethod.GET)
  9. 09          public String signup(Model model) {
  10. 10              Student student = new Student();
  11. 11              model.addAttribute("student", student);
  12. 12              return "signup";
  13. 13          }
  14. 14         
  15. 15          @RequestMapping(value="/signup", method=RequestMethod.POST)
  16. 16          public String signup(@ModelAttribute("student") Student student, Model model) {
  17. 17              if(studentService.getStudentByUserName(student.getUserName())) {
  18. 18                  model.addAttribute("message", "User Name exists. Try another user name");
  19. 19                  return "signup";
  20. 20              } else {
  21. 21                  studentService.insertStudent(student);
  22. 22                  model.addAttribute("message", "Saved student details");
  23. 23                  return "redirect:login.html";
  24. 24              }
  25. 25          }
  26. 26         
  27. 27          @RequestMapping(value="/login", method=RequestMethod.GET)
  28. 28          public String login(Model model) {
  29. 29              StudentLogin studentLogin = new StudentLogin();
  30. 30              model.addAttribute("studentLogin", studentLogin);
  31. 31              return "login";
  32. 32          }
  33. 33         
  34. 34          @RequestMapping(value="/login", method=RequestMethod.POST)
  35. 35          public String login(@ModelAttribute("studentLogin") StudentLogin studentLogin) {
  36. 36              boolean found = studentService.getStudentByLogin(studentLogin.getUserName(), studentLogin.getPassword());
  37. 37              if (found) {               
  38. 38                  return "success";
  39. 39              } else {               
  40. 40                  return "failure";
  41. 41              }
  42. 42          }
  43. 43        }
复制代码


使用道具 举报

回复
招聘 : 系统架构师
论坛徽章:
142
摩羯座
日期:2016-03-30 23:01:17秀才
日期:2015-07-31 14:17:16秀才
日期:2015-07-31 09:12:09秀才
日期:2015-07-28 10:22:54秀才
日期:2015-07-24 09:00:17秀才
日期:2015-07-20 08:54:46秀才
日期:2015-07-15 12:49:25秀才
日期:2015-07-09 09:23:47秀才
日期:2015-07-06 10:44:32秀才
日期:2015-07-06 10:34:54
 楼主| 发表于 2014-3-2 20:17 | 显示全部楼层
11. Create the DB Schema in a MYSQL DBConnect to the MySQL DB which is to be used for this application and create a new DB Schema named studentEnrollment using the MySQL Workbench. This is necessary as the DB Schema name of studentEnrollment is specified in the dataSource bean in springConfig.xml
Once the studentEnrollment DB Schema is created, create a table named student inside the DB Schema using the CREATE TABLE statement as follows:

  1. 01        CREATE TABLE `student` (
  2. 02          `id` bigint(20) NOT NULL AUTO_INCREMENT,
  3. 03          `dateOfBirth` datetime NOT NULL,
  4. 04          `emailAddress` varchar(255) NOT NULL,
  5. 05          `firstName` varchar(255) NOT NULL,
  6. 06          `lastName` varchar(255) NOT NULL,
  7. 07          `password` varchar(8) NOT NULL,
  8. 08          `userName` varchar(20) NOT NULL,
  9. 09          PRIMARY KEY (`id`)
  10. 10        ) ENGINE=InnoDB AUTO_INCREMENT=43 DEFAULT CHARSET=latin1;
复制代码


使用道具 举报

回复
招聘 : 系统架构师
论坛徽章:
142
摩羯座
日期:2016-03-30 23:01:17秀才
日期:2015-07-31 14:17:16秀才
日期:2015-07-31 09:12:09秀才
日期:2015-07-28 10:22:54秀才
日期:2015-07-24 09:00:17秀才
日期:2015-07-20 08:54:46秀才
日期:2015-07-15 12:49:25秀才
日期:2015-07-09 09:23:47秀才
日期:2015-07-06 10:44:32秀才
日期:2015-07-06 10:34:54
 楼主| 发表于 2014-3-2 20:17 | 显示全部楼层
12. Deploying the Application on Tomcat ServerOnce the above steps are complete and the project is successfully built, the Java web application is ready to deployed on the Tomcat Server 7.
The Java web application can be deployed locally by right clicking on the project and choosing the “Run As->Run on Server” option.
The same can be deployed remotely on any native server that supports Tomcat by copying the WAR file (Right click on the project and choose Export as WAR File option) to /var/lib/tomcat7 folder (or appropriate tomcat directory) and restarting the tomcat server.
This application is available for a demo here: http://ec2-23-20-137-135.compute-1.amazonaws.com:8080/StudentEnrollmentWithMyBatis/
13. Clone or Download codeIf using git, clone a copy of this project here: https://github.com/elizabetht/StudentEnrollmentWithMyBatis.git
In case of not using git, download the project as ZIP or tar.gz file here: https://github.com/elizabetht/StudentEnrollmentWithMyBatis/releases/tag/1.7

来自

使用道具 举报

回复
论坛徽章:
350
2006年度最佳版主
日期:2007-01-24 12:56:49NBA大富翁
日期:2008-04-21 22:57:29地主之星
日期:2008-11-17 19:37:352008年度最佳版主
日期:2009-03-26 09:33:53股神
日期:2009-04-01 10:05:56NBA季后赛大富翁
日期:2009-06-16 11:48:01NBA季后赛大富翁
日期:2009-06-16 11:48:01ITPUB年度最佳版主
日期:2011-04-08 18:37:09ITPUB年度最佳版主
日期:2011-12-28 15:24:18ITPUB年度最佳技术原创精华奖
日期:2012-03-13 17:12:05
发表于 2014-3-3 22:06 | 显示全部楼层
good

使用道具 举报

回复

您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

TOP技术积分榜 社区积分榜 徽章 团队 统计 知识索引树 积分竞拍 文本模式 帮助
  ITPUB首页 | ITPUB论坛 | 数据库技术 | 企业信息化 | 开发技术 | 微软技术 | 软件工程与项目管理 | IBM技术园地 | 行业纵向讨论 | IT招聘 | IT文档
  ChinaUnix | ChinaUnix博客 | ChinaUnix论坛
CopyRight 1999-2011 itpub.net All Right Reserved. 北京盛拓优讯信息技术有限公司版权所有 联系我们 
京ICP备09055130号-4  北京市公安局海淀分局网监中心备案编号:11010802021510 广播电视节目制作经营许可证:编号(京)字第1149号
  
快速回复 返回顶部 返回列表