從最開始搭框架談起,並且,我不只僅會講how,還會努力講why。由於對於web開發,因爲有太多好的框架、組件、工具,使得how每每不是那麼深入,背後的why更值得專研。若是有初學者關注我這個系列,也必定會對你有很大幫助。由於我要作的就是從起步階段,獨立一人開發一個網站。並且這是一個很是簡潔清晰的網站。html
本篇相關代碼已上傳github:sonne game前端
第一步,jar包:java
以上這些jar包並不算多,spring的jar包、mybatis的兩個jar包、一個mysql數據庫鏈接的jar包,剩下一些commons jar包。mysql
這篇文章介紹了spring相關的jar包,我以爲很不錯:spring各jar包做用linux
此外,commons-collections.jar的做用:爲Java標準的Collections API提供了至關好的補充。在此基礎上對其經常使用的數據結構操做進行了很好的封裝、抽象和補充。保證性能的同時大大簡化代碼。spring是要依賴這個包的。git
commons-codec.jar是Apache開源組織提供的用於摘要運算、編碼的包。DES、SHA一、MD五、Base64,URL,Soundx等等。github
commons-dbcp.jar是主流數據庫鏈接池之一,以前日向博客用的是c3p0。web
commons-pool.jar是用於實現對象池,用這個包能夠減小建立對象次數。spring
commons-logging.jar 日誌相關,是spring的必備包。sql
第二步,數據庫的準備:
我使用的是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項目必須的過程。該實體類對應着剛纔建的那個數據庫表。
package sonn.web.entity; /** * @ClassName: User * @Description: entity class of Usr. * @author sonne * @date 2017-1-6 21:24:00 create the class * @version 1.0 */ public class User { private int id; private String usrname; private String passwd; //private String nick_name; //private String register_date; //private String profile_pic_path; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUsrname() { return usrname; } public void setUsrname(String usrname) { this.usrname = usrname; } public String getPasswd() { return passwd; } public void setPasswd(String passwd) { this.passwd = passwd; } }
在該實體類同一個目錄下,建mapper的xml。這是mybatis的寫法。下面xml中有一條sql語句,會由mybatis爲咱們執行。衆所周知,mybatis和hibernate不一樣一點,是要本身寫sql語句的,在某些方面更加靈活。那麼問題是,既然是要本身寫sql語句,與不使用mybatis又有何區別呢。我認爲這樣至少實現了sql和代碼的分離,是種更好的設計。代碼統一寫在xml裏,也方便統一管理。
我以前的日向博客是使用的open jpa。寫法有很大不一樣。那種是真正的orm。有興趣的能夠去我github上看看:日向博客代碼
<?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 = "sonn.web.mapper.UserMapper"> <select id = "findAll" resultType = "sonn.web.entity.User"> select ID,USRNAME,PASSWD from USER </select> </mapper>
上述只是一個實體類,和一個xml文件,xml裏面配置了查詢的sql語句。
User是entity層,那麼那個xml應該是實現dao的功能,但設想咱們在controller裏要進行查詢的動做的話,該如何寫?用java代碼怎麼調用xml文件裏的sql ?
瓜熟蒂落的,咱們會發現這時須要一個java的接口:
package sonn.web.mapper; import java.util.List; import sonn.web.entity.User; /** * @ClassName: UserMapper * @Description: User Mapper Interface * @author sonne * @date 2017-1-7 15:51:11 * @version 1.0 */ public interface UserMapper { public List<User> findAll(); }
至於該接口與實體類和xml的對應關係,是由mybatis來替咱們作。
第四步,spring基本配置,並測試:
項目src目錄下,建立spring的xml配置文件:spring-common.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd"> <bean id = "myDataSource" class = "org.apache.commons.dbcp.BasicDataSource" destroy-method = "close"> <property name="driverClassName" value="com.mysql.jdbc.Driver"></property> <property name="url" value="jdbc:mysql://localhost/sonne_game?useUnicode=true&characterEncoding=UTF-8"></property> <property name="username" value="root"></property> <property name="password" value=""></property> </bean> <bean id = "sqlSessionFactory" class = "org.mybatis.spring.SqlSessionFactoryBean"> <property name = "dataSource" ref = "myDataSource" /> <property name = "mapperLocations" value = "classpath:sonn/web/entity/*.xml" /> </bean> <!-- define mapper --> <bean id = "userMapper" class = "org.mybatis.spring.mapper.MapperFactoryBean"> <property name = "mapperInterface" value = "sonn.web.mapper.UserMapper" /> <property name = "sqlSessionFactory" ref = "sqlSessionFactory" /> </bean> </beans>
myDataSource這個bean是配置的dbcp數據庫鏈接。屬於commons-dbcp.jar這個包。裏面配置了數據庫類型、url、用戶名、密碼。老生常談了。因爲目前用不到數據庫鏈接池,先無論。
sqlSessionFactory則是mybatis很核心的東西
userMapper就是第三步所寫的那些,對於User類的操做的bean。
這個xml文件是spring最基礎的東西,實在無法再細說了。
上述這些東西作過以後,其實就等於完成了mybatis和spring的整合,咱們能夠寫個測試類:
package sonn.web.test; import java.util.List; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import sonn.web.entity.User; import sonn.web.mapper.UserMapper; public class TestUserMapper { @Test public void testFindAll() { String conf = "spring-common.xml"; ApplicationContext ac = new ClassPathXmlApplicationContext(conf); UserMapper mapper = ac.getBean("userMapper", UserMapper.class); List<User> lst = mapper.findAll(); for (User usr : lst) { System.out.println(usr.getUsrname() + ":" + usr.getPasswd()); } } }
輸出結果:
若是隻是本地的程序(以實現對數據庫的操做),寫成這樣也就行了,但咱們要作的是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:
<?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:mvc="http://www.springframework.org/schema/mvc" xmlns:util="http://www.springframework.org/schema/util" xsi:schemaLocation= "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd"> <!-- 這個標籤註冊了Spring MVC分發請求到控制器所必須的DefaultAnnotationHandlerMapping和AnnotationMethodHandlerAdapter實例 --> <mvc:annotation-driven/> <context:component-scan base-package="sonn.web.controller"/> <!-- 定義視圖解析器viewResolver --> <bean id = "viewResolver" class = "org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name = "prefix" value = "/jsp/"/> <property name = "suffix" value = ".jsp"/> </bean> </beans>
該xml文件配置了自動掃描,路徑是controller文件夾。
視圖解析器配置了前端頁面的路徑WebRoot/jsp/xxxx.jsp
暫時使用jsp,freemarker的引入還要下一篇文章說。
有人會有疑問,目前建的兩個spring的xml文件,spring-common.xml和spring-mvc.xml文件究竟是怎樣由spring讀取到呢?
答案是:寫在web.xml裏:
<?xml version="1.0" encoding="UTF-8"?> <web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"> <display-name></display-name> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:/spring-*.xml</param-value> </context-param> <servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:/spring-mvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>*.form</url-pattern> </servlet-mapping> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </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 !
package sonn.web.controller; import java.util.List; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import sonn.web.entity.User; import sonn.web.mapper.UserMapper; /** * @ClassName: GameController * @Description: the controller of game * @author sonne * @date 2017-1-7 16:20:16 * @version 1.0 */ @Controller @RequestMapping("/game") public class GameController { @Resource(name = "userMapper") private UserMapper userMapper; @RequestMapping(value = "/lst", method = RequestMethod.GET) public String submit(HttpServletRequest request,Model model) throws Exception { List<User> usr_lst = userMapper.findAll(); model.addAttribute("lst", usr_lst); return "game_lst"; } }
下面是jsp的代碼,用到了jstl標籤來展現後臺傳過來的數據,很少說:
<%@page pageEncoding="utf-8" contentType="text/html;charset=utf-8"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=gb2312" /> <title>Sonn Game</title> </head> <body> <p>Hello.Here is Sonne's New website Sonn_Game</p> <c:forEach items="${lst}" var="usr" > <p>Usrname is ${usr.usrname} and usr's passwd is ${usr.passwd}</p> </c:forEach> </body> </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地址