1、首先让我们看一下搭建好的框架结构: 我们可以看到有controller层 和 service层 和 entity层
1、我们先来看一下springMVC的配置文件applicationContext-mvc.xml:
<!-- 启动注解驱动的Spring MVC功能,注册请求url和注解POJO类方法的映射-->
<mvc:annotation-driven/>
<!-- 启动包扫描功能,以便注册带有@Controller、@Service、@repository、@Component等注解的类成为spring的bean -->
<context:component-scan base-package="com.xiaoyu.ssh.*" >
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Service"/>
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Repository"/>
</context:component-scan>
<!-- http请求映射关系配置 -->
<!-- 对模型视图名称的解析,在请求时模型视图名称添加前后缀 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/view/"/>
<property name="suffix" value=".jsp"/>
<!-- 注解驱动用来控制编译静态模型 -->
</bean>
<!-- 对于静态资源的的处理 -->
<context:annotation-config/>
<mvc:default-servlet-handler/>
<mvc:resources location="/" mapping="/**/*.js"/>
<mvc:resources location="/" mapping="/**/*.css"/>
<mvc:resources location="/" mapping="/**/*.png"/>
<mvc:resources location="/" mapping="/**/*.gif"/>
<mvc:resources location="/" mapping="/**/*.jpg"/>
2、接下来我们再来看一下spring的配置文件applicationContext.xml:
<!-- 加载数据源 -->
<context:property-placeholder location="classpath:/resources/jdbc.properties"/>
<aop:aspectj-autoproxy/>
<!-- 配置spring的作用域 -->
<context:component-scan base-package="com">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<!-- jdbc数据源 -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${driverClassName}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</bean>
<!-- 配置Hibernate Seesion 把hibernate 的sessionFactory 交给spring处理 -->
<tx:annotation-driven transaction-manager="transactionManager"/>
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
<prop key="hibernate.cache.use_second_level_cache">false</prop>
<prop key="hibernate.cache.use_query_cache">false</prop>
<prop key="current_session_context_class">thread</prop>
<prop key="hibernate.current_session_context_class">org.springframework.orm.hibernate4.SpringSessionContext</prop>
</props>
</property>
<property name="packagesToScan">
<list>
<value>com.xiaoyu.ssh.entity</value>
</list>
</property>
</bean>
<!-- 配置spring 事物声明-->
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<!-- 配置事物属性 ,需要事物管理器-->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="get*" read-only="true"/>
<tx:method name="purchase" propagation="REQUIRES_NEW"/>
<tx:method name="*" propagation="REQUIRED" rollback-for="Exception"/>
</tx:attributes>
</tx:advice>
3、接下来我们看一下jdbc数据源jdbc.properties:
#数据库的路径
url = jdbc:mysql://localhost/people
#连接mysql的驱动#
driverClassName = com.mysql.jdbc.Driver
#用户名#
username = root
#密码#
password = 123456
4、写好spring和springMVC的些配置文件后我们再来看一下web.xml文件:
<context-param>
<param-name>contextConfigLocation</param-name>
<!-- 应用上下文配置文件 -->
<param-value>classpath*:resources/ApplicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<!-- springMVC 核心控制器 -->
<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*:resources/ApplicationContext-MVC.xml</param-value>
</init-param>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- springMVC 核心控制器 -->
<!--定义拦截器自动拦截中文字符编码并设置为UTF-8编码-->
<filter>
<filter-name>charsetEncoding</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>charsetEncoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter>
<filter-name>HiddenHttpMethodFilter</filter-name>
<filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>HiddenHttpMethodFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
5、我们来实现entity层的代码:
@Entity
@Table(name = "person")
public class Person {
private int id;
private String name;
private int age;
private int sex;
public Person(){};
@Id
@Column(name="id",nullable=false,length=32,unique=true)
@GenericGenerator(name="generator",strategy="uuid.hex")
@GeneratedValue
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Column(name="name",nullable=false,length=32)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Column(name="age",nullable=false,length=32)
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Column(name="sex",nullable=false,length=32)
public int getSex() {
return sex;
}
public void setSex(int sex) {
this.sex = sex;
}
public Person(int id, String name, int age, int sex) {
super();
this.id = id;
this.name = name;
this.age = age;
this.sex = sex;
}
@Override
public String toString() {
return "person [id=" + id + ", name=" + name + ", age=" + age + ", sex=" + sex + "]";
}
**
6、我们来实现service层代码:
**
@Repository
public class ServiceDaoImplement {
@Resource private SessionFactory sessionFactory;
public Session getSessionFactory(){
return sessionFactory.getCurrentSession();
}
public void addPerson(Person p){
this.getSessionFactory().save(p);
}
public void deletePersonById(String id){
this.getSessionFactory().createQuery("delete Person id = ?").setParameter(0, id).executeUpdate();
}
public Person findPersonById(String id){
return (Person) this.getSessionFactory().createQuery("from person where id = ?").setParameter(0, id).uniqueResult();
}
public void updatePerson(Person p){
this.getSessionFactory().update(p);
}
}
7、在Controller层调用这个方法:
@Autowired private ServiceDao personDao;
@RequestMapping(value="/text")
public String test(){
Person p = new Person ();
p.setId(1);
p.setName("张三");
p.setAge(18);
p.setSex(0);
personDao.addPerson(p);
System.out.println("添加用户张三完毕!");
return "/main";
}