SpringMVC又一個漂亮的web框架,他與Struts2並駕齊驅,Struts出世早而占據了一定優勢,下麵同樣做一個簡單的應用實例,介紹SpringMVC的基本用法,接下來的博客也將梳理一下Struts2和SpringMVC的一些異同,通過梳理和舊知識的聯繫,讓學習的成本變低,花很短的時間就可以 ...
SpringMVC又一個漂亮的web框架,他與Struts2並駕齊驅,Struts出世早而占據了一定優勢,下麵同樣做一個簡單的應用實例,介紹SpringMVC的基本用法,接下來的博客也將梳理一下Struts2和SpringMVC的一些異同,通過梳理和舊知識的聯繫,讓學習的成本變低,花很短的時間就可以瞭解一門貌似新的技術,其實本質沒變。
原文http://langgufu.iteye.com/blog/2088355
下麵開始實例,這個實例的需求是對用戶信息進行增刪改查。首先創建一個web項目test_ssh,目錄結構及需要的Jar包如下圖:
創建一個User實體類,放在Entity包下,採用註解的方式:
[java] view plaincopy- package com.tgb.entity;
- import javax.persistence.Column;
- import javax.persistence.Entity;
- import javax.persistence.GeneratedValue;
- import javax.persistence.Id;
- import javax.persistence.Table;
- import org.hibernate.annotations.GenericGenerator;
- @Entity
- @Table(name="T_USER")
- public class User {
- @Id
- @GeneratedValue(generator="system-uuid")
- @GenericGenerator(name = "system-uuid",strategy="uuid")
- @Column(length=32)
- private String id;
- @Column(length=32)
- private String userName;
- @Column(length=32)
- private String age;
- public String getId() {
- return id;
- }
- public void setId(String id) {
- this.id = id;
- }
- public String getUserName() {
- return userName;
- }
- public void setUserName(String userName) {
- this.userName = userName;
- }
- public String getAge() {
- return age;
- }
- public void setAge(String age) {
- this.age = age;
- }
- }
本篇關於SpringMVC基本都會採用註解的方式,首先配置好數據源以及事務spring-common.xml,放在config.spring包下:
[html] view plaincopy- <?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"
- xsi:schemaLocation="http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans.xsd">
- <!-- 配置數據源 -->
- <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource" >
- <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
- <property name="url" value="jdbc:mysql://localhost/test_ssh"></property>
- <property name="username" value="root"></property>
- <property name="password" value="1"></property>
- </bean>
- <!-- 配置SessionFactory -->
- <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.hbm2ddl.auto">update</prop>
- <prop key="hibernate.show_sql">true</prop>
- <prop key="hibernate.format_sql">true</prop>
- </props>
- </property>
- <property name="annotatedClasses">
- <list>
- <value>com.tgb.entity.User</value>
- </list>