从最开始搭框架谈起,而且,我不仅仅会讲how,还会努力讲why。因为对于web开发,由于有太多好的框架、组件、工具,使得how往往不是那么深刻,背后的why更值得专研。如果有初学者关注我这个系列,也一定会对你有很大帮助。因为我要做的就是从起步阶段,独立一人开发一个网站。而且这是一个非常简洁清晰的网站。

本篇相关代码已上传github:sonne game

第一步,jar包

以上这些jar包并不算多,spring的jar包、mybatis的两个jar包、一个mysql数据库连接的jar包,剩下一些commons jar包。

这篇文章介绍了spring相关的jar包,我觉得很不错:spring各jar包作用

此外,commons-collections.jar的作用:为Java标准的Collections API提供了相当好的补充。在此基础上对其常用的数据结构操作进行了很好的封装、抽象和补充。保证性能的同时大大简化代码。spring是要依赖这个包的。

commons-codec.jar是Apache开源组织提供的用于摘要运算、编码的包。DES、SHA1、MD5、Base64,URL,Soundx等等。

commons-dbcp.jar是主流数据库连接池之一,之前日向博客用的是c3p0。

commons-pool.jar是用于实现对象池,用这个包可以减少创建对象次数。

commons-logging.jar 日志相关,是spring的必备包。

第二步,数据库的准备

我使用的是mysql数据库。关于最基本的mysql使用就不必说了。mysql的安装我博客园的日志有总结:sql 笔记(mysql)介绍了windows、linux的ubuntu和centos下的安装方法。另外还介绍了mysql数据库的导入导出等。

windows下安装mysql,zip包的方式很简单,解压后做一些相应配置即可。

在安装好mysql的基础上,创建一个数据库,create database sonne_game; use sonne_game;

创建表,目前只是搭建框架,并且实验的阶段,所以这个表只有三个字段,用户名、密码、id:create table User(id int primary key,usrname varchar(20),passwd varchar(20));

向表中插入:

insert into User values (1,'sonne','passwd123');

insert into User values(2,'whoami','passwd321');

第三步,mybatis mapper

创建实体类,这是每个java web项目必须的过程。该实体类对应着刚才建的那个数据库表。

  1. package sonn.web.entity;
  2.  
  3. /**
  4. * @ClassName: User
  5. * @Description: entity class of Usr.
  6. * @author sonne
  7. * @date 2017-1-6 21:24:00 create the class
  8. * @version 1.0
  9. */
  10. public class User {
  11. private int id;
  12. private String usrname;
  13. private String passwd;
  14. //private String nick_name;
  15. //private String register_date;
  16. //private String profile_pic_path;
  17. public int getId() {
  18. return id;
  19. }
  20. public void setId(int id) {
  21. this.id = id;
  22. }
  23. public String getUsrname() {
  24. return usrname;
  25. }
  26. public void setUsrname(String usrname) {
  27. this.usrname = usrname;
  28. }
  29. public String getPasswd() {
  30. return passwd;
  31. }
  32. public void setPasswd(String passwd) {
  33. this.passwd = passwd;
  34. }
  35. }

在该实体类同一个目录下,建mapper的xml。这是mybatis的写法。下面xml中有一条sql语句,会由mybatis为我们执行。众所周知,mybatis和hibernate不同一点,是要自己写sql语句的,在某些方面更加灵活。那么问题是,既然是要自己写sql语句,与不使用mybatis又有何区别呢。我认为这样至少实现了sql和代码的分离,是种更好的设计。代码统一写在xml里,也方便统一管理。

我之前的日向博客是使用的open jpa。写法有很大不同。那种是真正的orm。有兴趣的可以去我github上看看:日向博客代码

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE mapper
  3. PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  4. "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  5. <mapper namespace = "sonn.web.mapper.UserMapper">
  6. <select id = "findAll" resultType = "sonn.web.entity.User">
  7. select ID,USRNAME,PASSWD from USER
  8. </select>
  9. </mapper>

上述只是一个实体类,和一个xml文件,xml里面配置了查询的sql语句。

User是entity层,那么那个xml应该是实现dao的功能,但设想我们在controller里要进行查询的动作的话,该如何写?用java代码怎么调用xml文件里的sql ?

顺理成章的,我们会发现这时需要一个java的接口:

  1. package sonn.web.mapper;
  2.  
  3. import java.util.List;
  4.  
  5. import sonn.web.entity.User;
  6.  
  7. /**
  8. * @ClassName: UserMapper
  9. * @Description: User Mapper Interface
  10. * @author sonne
  11. * @date 2017-1-7 15:51:11
  12. * @version 1.0
  13. */
  14. public interface UserMapper {
  15. public List<User> findAll();
  16. }

至于该接口与实体类和xml的对应关系,是由mybatis来替我们做。

第四步,spring基本配置,并测试:

项目src目录下,创建spring的xml配置文件:spring-common.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2.  
  3. <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xmlns="http://www.springframework.org/schema/beans"
  5. xmlns:context="http://www.springframework.org/schema/context"
  6. xmlns:tx="http://www.springframework.org/schema/tx"
  7. xsi:schemaLocation="
  8. http://www.springframework.org/schema/beans
  9. http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
  10. http://www.springframework.org/schema/context
  11. http://www.springframework.org/schema/context/spring-context-3.2.xsd
  12. http://www.springframework.org/schema/tx
  13. http://www.springframework.org/schema/tx/spring-tx-3.2.xsd">
  14. <bean id = "myDataSource" class = "org.apache.commons.dbcp.BasicDataSource" destroy-method = "close">
  15. <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
  16. <property name="url" value="jdbc:mysql://localhost/sonne_game?useUnicode=true&characterEncoding=UTF-8"></property>
  17. <property name="username" value="root"></property>
  18. <property name="password" value=""></property>
  19. </bean>
  20. <bean id = "sqlSessionFactory" class = "org.mybatis.spring.SqlSessionFactoryBean">
  21. <property name = "dataSource" ref = "myDataSource" />
  22. <property name = "mapperLocations" value = "classpath:sonn/web/entity/*.xml" />
  23. </bean>
  24.  
  25. <!-- define mapper -->
  26. <bean id = "userMapper" class = "org.mybatis.spring.mapper.MapperFactoryBean">
  27. <property name = "mapperInterface" value = "sonn.web.mapper.UserMapper" />
  28. <property name = "sqlSessionFactory" ref = "sqlSessionFactory" />
  29. </bean>
  30. </beans>

myDataSource这个bean是配置的dbcp数据库连接。属于commons-dbcp.jar这个包。里面配置了数据库类型、url、用户名、密码。老生常谈了。由于目前用不到数据库连接池,先不管。

sqlSessionFactory则是mybatis很核心的东西

userMapper就是第三步所写的那些,对于User类的操作的bean。

这个xml文件是spring最基础的东西,实在没法再细说了。

上述这些东西做过之后,其实就等于完成了mybatis和spring的整合,我们可以写个测试类:

  1. package sonn.web.test;
  2.  
  3. import java.util.List;
  4.  
  5. import org.junit.Test;
  6. import org.springframework.context.ApplicationContext;
  7. import org.springframework.context.support.ClassPathXmlApplicationContext;
  8.  
  9. import sonn.web.entity.User;
  10. import sonn.web.mapper.UserMapper;
  11.  
  12. public class TestUserMapper {
  13. @Test
  14. public void testFindAll() {
  15. String conf = "spring-common.xml";
  16. ApplicationContext ac = new ClassPathXmlApplicationContext(conf);
  17. UserMapper mapper = ac.getBean("userMapper", UserMapper.class);
  18. List<User> lst = mapper.findAll();
  19. for (User usr : lst) {
  20. System.out.println(usr.getUsrname() + ":" + usr.getPasswd());
  21. }
  22. }
  23. }

输出结果:

如果只是本地的程序(以实现对数据库的操作),写成这样也就好了,但我们要做的是web项目,还需要一个view层。这时就需要spring-mvc出场了。

第五步,spring mvc配置:

关于mvc模型,真不想多说了。太基础了。

之前我博客园两篇文章探讨过spring-mvc的概念和配置:spring-mvc

标签简化spring mvc(不了解spring-mvc概念的请先看懂这两篇,否则下面的你是看不懂的)

前者是最基本的mvc概念,后者是前者基础上加入自动扫描机制。有了自动扫描机制,用spring搞web会简单好多。用标签简化了繁琐的bean的配置。

在src路径下,再新建一个spring的xml文件,名叫spring-mvc.xml:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xmlns:context="http://www.springframework.org/schema/context"
  5. xmlns:mvc="http://www.springframework.org/schema/mvc"
  6. xmlns:util="http://www.springframework.org/schema/util"
  7. xsi:schemaLocation=
  8. "http://www.springframework.org/schema/beans
  9. http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
  10. http://www.springframework.org/schema/context
  11. http://www.springframework.org/schema/context/spring-context-3.2.xsd
  12. http://www.springframework.org/schema/mvc
  13. http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
  14. http://www.springframework.org/schema/util
  15. http://www.springframework.org/schema/util/spring-util-3.2.xsd">
  16. <!-- 这个标签注册了Spring MVC分发请求到控制器所必须的DefaultAnnotationHandlerMapping和AnnotationMethodHandlerAdapter实例 -->
  17. <mvc:annotation-driven/>
  18. <context:component-scan base-package="sonn.web.controller"/>
  19.  
  20. <!-- 定义视图解析器viewResolver -->
  21. <bean id = "viewResolver"
  22. class = "org.springframework.web.servlet.view.InternalResourceViewResolver">
  23. <property name = "prefix" value = "/jsp/"/>
  24. <property name = "suffix" value = ".jsp"/>
  25. </bean>
  26. </beans>

该xml文件配置了自动扫描,路径是controller文件夹。

视图解析器配置了前端页面的路径WebRoot/jsp/xxxx.jsp

暂时使用jsp,freemarker的引入还要下一篇文章说。

有人会有疑问,目前建的两个spring的xml文件,spring-common.xml和spring-mvc.xml文件到底是怎样由spring读取到呢?

答案是:写在web.xml里:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <web-app version="3.0"
  3. xmlns="http://java.sun.com/xml/ns/javaee"
  4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  5. xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
  6. http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
  7. <display-name></display-name>
  8. <context-param>
  9. <param-name>contextConfigLocation</param-name>
  10. <param-value>classpath:/spring-*.xml</param-value>
  11. </context-param>
  12. <servlet>
  13. <servlet-name>springmvc</servlet-name>
  14. <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  15. <init-param>
  16. <param-name>contextConfigLocation</param-name>
  17. <param-value>classpath:/spring-mvc.xml</param-value>
  18. </init-param>
  19. <load-on-startup>1</load-on-startup>
  20. </servlet>
  21. <servlet-mapping>
  22. <servlet-name>springmvc</servlet-name>
  23. <url-pattern>*.form</url-pattern>
  24. </servlet-mapping>
  25. <listener>
  26. <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  27. </listener>
  28. <welcome-file-list>
  29. <welcome-file>index.jsp</welcome-file>
  30. </welcome-file-list>
  31. </web-app>

spring-mvc配置好之后,就可以建一个controller类了,下面有一些很基本的标签,如@RequestMapping,规定的是请求路径。方法里通过mapper接口调用的是spring配置文件里配置好的bean。用这个bean实现数据库查询后,使用Model发送到前端。最后返回的"gamne_lst"。会被spring-mvc解析为/jsp/game_lst.jsp这样的路径(见上文提到的配置)。依据这个路径浏览器加载对应的jsp文件,实现了view层的展示。

这样一番entity实体类-dao数据库操作-controller-view前端页面的过程,就是MVC结构,spring-mvc !

  1. package sonn.web.controller;
  2.  
  3. import java.util.List;
  4.  
  5. import javax.annotation.Resource;
  6. import javax.servlet.http.HttpServletRequest;
  7.  
  8. import org.springframework.stereotype.Controller;
  9. import org.springframework.ui.Model;
  10. import org.springframework.web.bind.annotation.RequestMapping;
  11. import org.springframework.web.bind.annotation.RequestMethod;
  12.  
  13. import sonn.web.entity.User;
  14. import sonn.web.mapper.UserMapper;
  15.  
  16. /**
  17. * @ClassName: GameController
  18. * @Description: the controller of game
  19. * @author sonne
  20. * @date 2017-1-7 16:20:16
  21. * @version 1.0
  22. */
  23. @Controller
  24. @RequestMapping("/game")
  25. public class GameController {
  26.  
  27. @Resource(name = "userMapper")
  28. private UserMapper userMapper;
  29.  
  30. @RequestMapping(value = "/lst", method = RequestMethod.GET)
  31. public String submit(HttpServletRequest request,Model model) throws Exception {
  32. List<User> usr_lst = userMapper.findAll();
  33. model.addAttribute("lst", usr_lst);
  34. return "game_lst";
  35. }
  36. }

下面是jsp的代码,用到了jstl标签来展示后台传过来的数据,不多说:

  1. <%@page pageEncoding="utf-8" contentType="text/html;charset=utf-8"%>
  2. <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
  3. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
  4. <html>
  5. <head>
  6. <meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
  7. <title>Sonn Game</title>
  8. </head>
  9. <body>
  10. <p>Hello.Here is Sonne's New website Sonn_Game</p>
  11. <c:forEach items="${lst}" var="usr" >
  12. <p>Usrname is ${usr.usrname} and usr's passwd is ${usr.passwd}</p>
  13. </c:forEach>
  14. </body>
  15. </html>

第六步,查看效果:

eclipse使用tomcat加载运行本项目,之后浏览器访问:http://localhost:8888/Sonne_game/game/lst.form(tomcat默认端口号是8080,我这里是8888,Sonne_game是我的项目名字,game/lst是controller里面requestmapping标签规定的路径,.form后缀是web.xml里设置的):

这样我们就实现了一个最基本的页面,逻辑虽然简单,却代表了非常本质的东西。在此基础上扩展,就是一个成熟的网站。

最后截图展示整个项目结构,上述所有内容都应该对应着这个结构来理解:

想要上述所有代码的话,当然是通过github来获取:github地址

sonne_game网站开发02spring+mybatis框架搭建的更多相关文章

  1. mybatis框架搭建学习初步

    mybatis框架搭建步骤:1. 拷贝jar到lib目录下,而且添加到工程中2. 创建mybatis-config.xml文件,配置数据库连接信息 <environments default=& ...

  2. SpringMVC+Mybatis框架搭建

    一.新建javaweb项目,并建好相应的包结构 二.添加项目jar到lib目录下 三.在config包中新建配置文件 sping-mvc.xml,内容如下: <?xml version=&quo ...

  3. Mybatis框架搭建

    Mybatis框架搭建 思路: 搭建环境 导入Mybatis 编写代码 测试 一.搭建环境 创建数据库 /* Navicat Premium Data Transfer​ Source Server ...

  4. Angular企业级开发(5)-项目框架搭建

    1.AngularJS Seed项目目录结构 AngularJS官方网站提供了一个angular-phonecat项目,另外一个就是Angular-Seed项目.所以大多数团队会基于Angular-S ...

  5. ASP.NET MVC5 网站开发实践(一) - 框架(续) 模型、数据存储、业务逻辑

    上次搭建好了项目框架,但还是觉得不太对劲,后来才想起来没有对开发目标进行定位,这个小demo虽然不用做需求分析,但是要实现什么效果还得明确.后来想了一下就做个最简单的网站,目标定为小公司进行展示用的网 ...

  6. SSM(Spring +SpringMVC + Mybatis)框架搭建

    SSM(Spring +SpringMVC + Mybatis)框架的搭建 最近通过学习别人博客发表的SSM搭建Demo,尝试去搭建一个简单的SSMDemo---实现的功能是对用户增删改查的操作 参考 ...

  7. spring+springmvc+mybatis框架搭建

    一.开发前准备 1)ecplise4.11.0 百度网盘:https://pan.baidu.com/s/1wO9_I52lp0mYNeNTdnj80w 提取码:booa 2)jdk1.6.0_45  ...

  8. 学习MVC之租房网站(二)-框架搭建及准备工作

    在上一篇<学习MVC之租房网站(一)-项目概况>中,确定了UI+Service的“双层”架构,并据此建立了项目 接下来要编写Common类库.配置AdminWeb和FrontWeb 一.编 ...

  9. Mybatis 框架搭建实例

    前言 MyBatis是一个优秀的持久层框架.原生的jdbc操作存在大量的重复性代码(如注册驱动,创建连接,创建statement,结果集检测等).框架的作用就是把这些繁琐的代码封装. MyBatis通 ...

随机推荐

  1. 引用64位dll时候出现 未能加载文件或程序集“System.Data.SQLite”或它的某一个依赖项。试图加载格式不正确的程序。

    引用64位dll时候出现 未能加载文件或程序集“System.Data.SQLite”或它的某一个依赖项.试图加载格式不正确的程序. 需要在web.config增加配置 <startup use ...

  2. 拼sql条件时判断 是不是当前时间是不是周五,如果今天不是周五,就选上周五

    if (Request.QueryString["start"] == null) { for (int i = 0; i < 6; i++) { if (DateTime. ...

  3. SAP项目管理模块培训教材

    SAP项目管理模块培训教材(PLM210.PLM220.PLM230)分享: http://sap.npbok.com/

  4. vc11(vs2012)下编译php

    需要原料: vs2012.php源码 1.本机的mingw没搞定,参考网上文章尝试vs2012编译,借助vs2012自带的命令行工具: 需要去bison官网下载bison.exe放在“c:/windo ...

  5. 使用django-admin.py 时出错

    我在安装好django后,运行django-admin.py 时出现两处错误: 一.当你在dos命令下输入django-admin.py 时不会运行,而是以记事本的方式打开了. 解决办法:找到你的dj ...

  6. java 单利模式

    首先何为单利模式: 单利模式即多次调用同一个对象的时候,只有一个实例(这里所谓的实例就是,假如创建了两个对象,它们的hashCode相同) 下面是相关代码: 1 创建一个对象Singleton类 pa ...

  7. Freemarker常用指令使用范例

    我的開發環境 框架:           springmvc+freemarker 開發工具:    springsource-tool-suite-2.9.0 JDK版本:    1.6.0_29 ...

  8. Python垃圾回收机制

    引用计数Python默认的垃圾收集机制是“引用计数”,每个对象维护了一个ob_ref字段.它的优点是机制简单,当新的引用指向该对象时,引用计数 引用计数 Python默认的垃圾收集机制是“引用计数”, ...

  9. jboss hello world

    http://developers.redhat.com/products/devstudio/get-started/ 1. 下载 Red Hat JBoss Developer studio 2. ...

  10. java-7311练习(下)

    java练习,仅供参考! 欢迎同学们交流讨论. JDK 1.8 API帮助文档 JDK 1.6 API中文文档 第一次小组作业:模拟双色球彩票 第一次小组作业(一) 控制台版 游戏规则: • 双色球为 ...