基于注解的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.


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值