1. 程式人生 > >基於註解的Spirng MVC框架的搭建(基礎篇)

基於註解的Spirng MVC框架的搭建(基礎篇)

看這篇搭建過程前,最好是先了解一下原理。

最近正好在帶兩個實習生,教他們怎麼搭建一個Spring MVC的框架,網上也看了很多demo,發現各有各的版本,於是自己用Spring3,Hibernate3搭了一個,伺服器是Tomcat6,資料庫是MySql(note:這好像是我工作以來第一次搭建框架)

原始碼下載地址,免費1,免費2

有個額外的phil.jar包,他的工程目錄如下,有興趣的可以解包檢視一下,主要是在HibernateTemplate和JdbcTemplate的基礎之上自己封裝了一個CommonDao,所以我所有的Dao實現類都是繼承了CommonDaoImpl的,另外順便封裝了一下User,Role等一些簡單的類.


下面直接進入正題,我的工程目錄如下:



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>	
  <servlet>
        <servlet-name>dispatcherServlet</servlet-name>
        <servlet-class>
            org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath*:/main/config/applicationContext.xml,classpath*:/main/config/springmvc-servlet.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    
    <servlet-mapping>
        <servlet-name>dispatcherServlet</servlet-name>
        <url-pattern>*.html</url-pattern>
    </servlet-mapping>  
	<welcome-file-list>
	    <welcome-file>reg.jsp</welcome-file>
	</welcome-file-list>
</web-app>

springmvc-servlet.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:p="http://www.springframework.org/schema/p"
	xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context"
	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.0.xsd    
            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd    
            http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd    
            http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd">
     
    <!-- 對web包中的Controller進行掃描,以完成Bean建立和自動依賴注入的功能 -->
    <context:component-scan base-package="main.java.com.sy.controller"/>

    <!-- 啟動Spring MVC的註解功能,完成請求和註解POJO的對映 -->
    <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"/>

    <!--對模型檢視名稱的解析,即在模型檢視名稱新增前後綴 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" 
         p:suffix=".jsp"/>
</beans>
application.properties
#jdbc
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/sy
jdbc.user=root
jdbc.password=root

#hibernate
hibernate.dialect=org.hibernate.dialect.MySQLDialect
hibernate.show_sql=true
hibernate.hbm2ddl.auto=update
applicationContext.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:aop="http://www.springframework.org/schema/aop"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="
http://www.springframework.org/schema/beans 
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/aop 
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
  http://www.springframework.org/schema/context   
   http://www.springframework.org/schema/context/spring-context-3.0.xsd
">

  <context:component-scan base-package="main.java.com.sy.service"></context:component-scan>
  <context:component-scan base-package="main.java.com.sy.dao"></context:component-scan>
  <context:component-scan base-package="main.java.com.sy.bean"></context:component-scan>
  
  <context:property-placeholder location="classpath*:/main/config/application.properties" />
	<!-- 支援aop註解 -->
	<aop:aspectj-autoproxy />

	<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">  
            <property name="driverClassName" value="${jdbc.driverClass}"></property>  
            <property name="url" value="${jdbc.url}"></property>  
            <property name="username" value="${jdbc.user}"></property>  
            <property name="password" value="${jdbc.password}"></property>
    </bean>  

   <bean id="sessionFactory"  
       class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">  
           <property name="dataSource">  
               <ref bean="dataSource" />  
           </property>
           <property name="hibernateProperties">  
               <props>
                   <prop key="hibernate.dialect">${hibernate.dialect}</prop>  
                   <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
                   <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
               </props>
           </property>
		<property name="packagesToScan">
			<value>main.java.com.sy.entity</value>
		</property>
   </bean>  

<bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate" >
	<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
 
<bean id="jdbcTemplate"  class="org.springframework.jdbc.core.JdbcTemplate">   
     <property name="dataSource" ref="dataSource"/>   
</bean>


<!-- 配置事務管理 -->
	<bean id="hibernateTransactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager" >
		<property name="sessionFactory" ref="sessionFactory"></property>
	</bean>
	<tx:annotation-driven transaction-manager="hibernateTransactionManager" />
	<aop:config> 
		<aop:pointcut expression="execution(* main.java.com.sy.service.impl.*.*(..))" id="businessService"/> 
		<aop:advisor advice-ref="txAdvice" pointcut-ref="businessService" /> 
	</aop:config> 

	<tx:advice id="txAdvice" transaction-manager="hibernateTransactionManager">
		<tx:attributes>
			<tx:method name="delete*" propagation="REQUIRED" rollback-for="Exception"/>
			<tx:method name="delet*" propagation="REQUIRED" rollback-for="Exception"/>
			<tx:method name="save*" propagation="REQUIRED" rollback-for="Exception"/>
			<tx:method name="update*" propagation="REQUIRED" rollback-for="Exception"/>
			<tx:method name="add*" propagation="REQUIRED" rollback-for="Exception"/>
			<tx:method name="create*" propagation="REQUIRED" rollback-for="Exception"/>
			<tx:method name="merge*" propagation="REQUIRED" rollback-for="Exception"/>
			<tx:method name="revoke*" propagation="REQUIRED" rollback-for="Exception"/>
			<tx:method name="*" propagation="SUPPORTS"/>
		</tx:attributes>
	</tx:advice>

</beans>

基本的xml配置已經好了,下面我們開始寫程式碼來跳轉吧,我個人比較喜歡先寫dao,然後再寫service,最後再寫Controller。

先定義一個BaseEntity.java,主要就是Id,建立/更新時間,建立/更新人

@MappedSuperclass
public class BaseEntity implements Serializable{
	
	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	protected Long id;
	
	@Column(updatable=false)
	protected Date creatTime=new Date();
	
	@Column(updatable=false)
	protected String creatUser;
	
	@Column(insertable=false)
	protected Date updateTime=new Date();
	
	@Column(insertable=false)
	protected String updateUser;

	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public Date getCreatTime() {
		return creatTime;
	}

	public void setCreatTime(Date creatTime) {
		this.creatTime = creatTime;
	}

	public String getCreatUser() {
		return creatUser;
	}

	public void setCreatUser(String creatUser) {
		this.creatUser = creatUser;
	}

	public Date getUpdateTime() {
		return updateTime;
	}

	public void setUpdateTime(Date updateTime) {
		this.updateTime = updateTime;
	}

	public String getUpdateUser() {
		return updateUser;
	}

	public void setUpdateUser(String updateUser) {
		this.updateUser = updateUser;
	}

}
UserDao.java
public interface UserDao {
	
	public void add(User u);

}

UserDaoImpl.java

@Repository
public class UserDaoImpl extends CommonDaoImpl implements UserDao {
	
	public void add(User u){
		super.save(u);
	}
}
UserService.java
public interface UserService {
	
	public void add(User u);

}
UserServiceImpl.java
@Service
public class UserServiceImpl implements UserService {
	
	@Resource
	private UserDao userDao;

	public void add(User u){
		userDao.add(u);
	}	
}
UserController.java
@Controller
public class UserController {
	
	@Resource
	private UserService userService;
	
	@RequestMapping(value = "/reg.html")
	public String reg(HttpServletRequest request,HttpServletResponse reponse,User u){
		System.out.println("UserController.reg()");
		userService.add(u);
		String msg ="add successfully";
		request.setAttribute("msg", msg);
		return "index";
	}	
}
reg.jsp
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <body>
		<form action="reg.html" method="post">
			使用者名稱:
			<input type="text" name="userName" /><br/>
			<input type="submit" value="註冊"  />
		</form>
  </body>
</html>
index.jsp
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <body>
    <h2>${msg}</h2>
  </body>
</html>

OK,一切大功告成,啟動Tomcat,位址列輸入http://localhost:8080/TestJar/

出現如下圖所示



輸入“test001”,點選“註冊”,跳轉到

提示成功了誒,雖然這是我事先寫好的msg,我們檢視一下資料庫來驗證



這次是真的新增成功了。

有問題的童鞋可以加我QQ401276,驗證資訊CSDN.