重拾springmvc+hibernate

多年不用java了,最近被迫重拾java,叫喊,还是那么厚重,但是也有些变化和新的感觉,就当是体会记忆的味道吧!

版本介绍:

  • jdk 7
  • springmvc 4.1.5
  • hibernate  4.3.5
  • maven model 4.0.0
  • db2 type4
  • tomcat 7
  • eclipse Luna Release (4.4.0)

使用maven做包管理:pom.xml

Steps:

  1. create a dynamic java web project
  2. convert to a maven project
  3. add springmvc dependency
  4. edit some xml config files: web.xml, applicationContext.xml and so on.

功能介绍:

  1. 首先springmvc,hibernate相关的配置, 使用spring的dispatcherservlet做拦截,根据不同的资源和请求做控制,比如静态资源的拦截,控制器的拦截和请求分派
  2. 连接的数据库使用db2, 驱动的配置,default_schema的配置,事务管理,会话管理等实现数据访问
  3. ajax请求的数据处理,json的数据格式的处理,使用jackson的jar文件

感想:(纯属个人观点,欢迎讨论)

  1. 对于很久不用java的程序员,java的一些思想还是对我有很多影响的,比如封装,继承的方式,分层处理
  2. 关于web开发的方式,java比以前灵活多了,特别是springmvc的dispatcher方式, 现在很多主流的web开发语言在web开发方面的框架路子都差不多,想Ruby on Rails, Django, Thinkphp. 差别在于语言本身的性能和使用场景方面
  3. 相对应其他语言的框架,springmvc的配置还是有点繁琐,还有jar的版本众多,有点不知所措了,有时候一个版本不可以用,但是不知道陷阱在哪里

主要代码文件内容如下:

 

web.xml内容如下:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>SpringDemo</display-name>
  <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>
  
  <listener>
      <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
  </listener>
  <listener>
      <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  
 <context-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>/WEB-INF/applicationContext.xml</param-value>
  </context-param>
  <servlet>
      <servlet-name>MVC</servlet-name>
      <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
      <init-param>
          <param-name>contextConfigLocation</param-name>
          <param-value>
              /WEB-INF/config/mvc*.*
          </param-value>
      </init-param>
      <load-on-startup>1</load-on-startup>
  </servlet>
  
  <servlet-mapping>
      <servlet-name>MVC</servlet-name>
      <url-pattern>/</url-pattern>
  </servlet-mapping>
</web-app>

 

applicationContext.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"   
       xmlns:aop="http://www.springframework.org/schema/aop"   
       xmlns:context="http://www.springframework.org/schema/context"  
       xmlns:mvc="http://www.springframework.org/schema/mvc"   
       xmlns:tx="http://www.springframework.org/schema/tx"   
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
       xsi:schemaLocation="http://www.springframework.org/schema/aop   
        http://www.springframework.org/schema/aop/spring-aop-4.0.xsd   
        http://www.springframework.org/schema/beans   
        http://www.springframework.org/schema/beans/spring-beans-4.0.xsd   
        http://www.springframework.org/schema/context   
        http://www.springframework.org/schema/context/spring-context-4.0.xsd   
        http://www.springframework.org/schema/mvc   
        http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd   
        http://www.springframework.org/schema/tx   
        http://www.springframework.org/schema/tx/spring-tx-4.0.xsd"> 

<!-- 使用注解 -->
    <mvc:annotation-driven />
<!-- 自动扫描 -->
    <context:component-scan base-package="com.alecchyi.*" />  
<!-- 页面拦截相关 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">  
        <property name="prefix" value="/page/" />  
        <property name="suffix" value=".jsp" />  
    </bean>  
<!-- 静态资源相关 -->
    <mvc:resources mapping="/js/**" location="/js/" cache-period="31536000" />
    <mvc:resources mapping="/css/**" location="/css/" cache-period="31536000" />
<!-- 数据库连接相关 -->
    <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="packagesToScan">
            <list>
            <value>com.alecchyi.demo.entry</value>
            <value>com.alecchyi.demo.dao</value>
            <value>com.alecchyi.demo.service</value>
            </list>
        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.hbm2ddl.auto">update</prop>
                <prop key="hibernate.dialect">org.hibernate.dialect.DB2Dialect</prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.default_schema">ruby</prop>
            </props>
        </property>
    </bean>
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.ibm.db2.jcc.DB2Driver" />
        <property name="url" value="jdbc:db2://localhost:50000/demo" />
        <property name="username" value="db2admin" />
        <property name="password" value="password" />
    </bean>
<!-- 事务相关 --> 
    <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>
    
    <bean id="persistenceExceptionTranslationPostProcessor" class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />
	<tx:advice id="txAdvice" transaction-manager="transactionManager">
		<tx:attributes>
			<tx:method name="add*" propagation="REQUIRED" />
			<tx:method name="get*" propagation="REQUIRED" />
			<tx:method name="*" read-only="true" />
		</tx:attributes>
	</tx:advice>
	<aop:config expose-proxy="true">
		<aop:pointcut id="txPointcut" expression="execution(* com.alecchyi.demo.service..*.*(..))" />
		<aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut" />
	</aop:config>
<!-- 数据操作相关 -->
    <bean id="usersDao" class="com.alecchyi.demo.dao.UsersDao">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>
    <bean id="userService" class="com.alecchyi.demo.service.UserService">
        <property name="usersDao" ref="usersDao" />
    </bean>
</beans>

 

dao.java内容:

package com.alecchyi.demo.dao;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

import com.alecchyi.demo.entry.Users;

public class UsersDao {
	private SessionFactory sessionFactory;

	public List<Users> getAllUsers(){
		Session session = sessionFactory.getCurrentSession();
		Query query = session.createQuery("from users");
		return query.list();
	}

	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}	
}

 

service.java内容:

package com.alecchyi.demo.service;

import javax.annotation.Resource;
import javax.transaction.Transactional;

import org.springframework.stereotype.Service;

import com.alecchyi.demo.dao.UsersDao;

public class UserService {

	private UsersDao usersDao;
	
	public UsersDao getUsersDao() {
		return usersDao;
	}

	public void setUsersDao(UsersDao usersDao) {
		this.usersDao = usersDao;
	}

	public int userCount(){
		return usersDao.getAllUsers().size();
	}
}

 

entity.java内容:

package com.alecchyi.demo.entry;
import java.sql.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity(name="users")
public class Users {

	public Users(){
		super();
	}
	@Id
	@GeneratedValue(strategy=GenerationType.AUTO)
	@Column(name="id")
	private Integer id;
	
	public Integer getId() {
		return id;
	}

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

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getNickname() {
		return nickname;
	}

	public void setNickname(String nickname) {
		this.nickname = nickname;
	}

	public Integer getAge() {
		return age;
	}

	public void setAge(Integer age) {
		this.age = age;
	}

	public Date getBirth() {
		return birth;
	}

	public void setBirth(Date birth) {
		this.birth = birth;
	}

	@Column(name="username")
	private String username;
	
	@Column(name="password")
	private String password;
	
	@Column(name="nickname")
	private String nickname;
	
	@Column(name="age")
	private Integer age;
	
	@Column(name="birth")
	private Date birth;
	
}

 

controller.java内容:

package com.alecchyi.controller;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alecchyi.demo.service.UserService;

@Controller
public class PortalController {

	@Resource(name="userService")
	private UserService userService;

	@RequestMapping("demo")
	public ModelAndView portal(){
		ModelAndView view = new ModelAndView("portal");
		return view;
	}
	
	@RequestMapping(value="update",method=RequestMethod.POST)
	@ResponseBody
	public Map<String,Object> update(HttpServletRequest request){
		String username = request.getParameter("name");
		System.out.println(userService.userCount());
		Map<String,Object> map = new HashMap<String,Object>(1);
		map.put("username", username);
		return map;
	}
}

 

view.jsp内容:

<script type="text/javascript">
jQuery(document).ready(function($){
	$("#link").click(function(){
		$.ajax({
			url:"update",
			dataType:"json",
			data:"name=ruby",
			type:"post",
			success:function(data){
				alert(data.username);
			},
			error:function(){
				alert("error");
			}
		});
	});
});
</script>

 

pom.xml 内容如下:(有些并不是必须的)

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>SpringDemo</groupId>
  <artifactId>SpringDemo</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>
  <name>Spring</name>
  <description>Spring</description>
  <build>
    <sourceDirectory>src</sourceDirectory>
    <plugins>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.1</version>
        <configuration>
          <source>1.7</source>
          <target>1.7</target>
        </configuration>
      </plugin>
      <plugin>
        <artifactId>maven-war-plugin</artifactId>
        <version>2.4</version>
        <configuration>
          <warSourceDirectory>WebContent</warSourceDirectory>
          <failOnMissingWebXml>false</failOnMissingWebXml>
        </configuration>
      </plugin>
    </plugins>
  </build>
  <dependencies>
  	<dependency>
  		<groupId>org.springframework</groupId>
  		<artifactId>spring-context</artifactId>
  		<scope>runtime</scope>
  	</dependency>
  	<dependency>
  		<groupId>org.springframework</groupId>
  		<artifactId>spring-webmvc</artifactId>
  	</dependency>
  	<dependency>
  		<groupId>com.fasterxml.jackson.core</groupId>
  		<artifactId>jackson-databind</artifactId>
  	</dependency>
  	<dependency>
  		<groupId>com.fasterxml.jackson.core</groupId>
  		<artifactId>jackson-core</artifactId>
  	</dependency>
  	<dependency>
  		<groupId>com.fasterxml.jackson.core</groupId>
  		<artifactId>jackson-annotations</artifactId>
  	</dependency>
  	<dependency>
  		<groupId>org.hibernate</groupId>
  		<artifactId>hibernate-core</artifactId>
  	</dependency>
  	<dependency>
  		<groupId>mysql</groupId>
  		<artifactId>mysql-connector-java</artifactId>
  	</dependency>
  	<dependency>
  		<groupId>org.springframework.security</groupId>
  		<artifactId>spring-security-config</artifactId>
  	</dependency>
  	<dependency>
  		<groupId>org.springframework.security</groupId>
  		<artifactId>spring-security-core</artifactId>
  	</dependency>
  	<dependency>
  		<groupId>org.springframework.security</groupId>
  		<artifactId>spring-security-web</artifactId>
  	</dependency>
  	<dependency>
  		<groupId>org.springframework</groupId>
  		<artifactId>spring-orm</artifactId>
  	</dependency>
  	<dependency>
  		<groupId>org.aspectj</groupId>
  		<artifactId>aspectjrt</artifactId>
  	</dependency>
  	<dependency>
  		<groupId>org.aspectj</groupId>
  		<artifactId>aspectjweaver</artifactId>
  	</dependency>
  </dependencies>
  <dependencyManagement>
  	<dependencies>
  		<dependency>
  			<groupId>org.springframework</groupId>
  			<artifactId>spring-context</artifactId>
  			<version>4.1.4.RELEASE</version>
  		</dependency>
  		<dependency>
  			<groupId>org.springframework</groupId>
  			<artifactId>spring-webmvc</artifactId>
  			<version>4.1.4.RELEASE</version>
  		</dependency>
  		<dependency>
  			<groupId>com.fasterxml.jackson.core</groupId>
  			<artifactId>jackson-databind</artifactId>
  			<version>2.5.1</version>
  		</dependency>
  		<dependency>
  			<groupId>com.fasterxml.jackson.core</groupId>
  			<artifactId>jackson-core</artifactId>
  			<version>2.5.1</version>
  		</dependency>
  		<dependency>
  			<groupId>com.fasterxml.jackson.core</groupId>
  			<artifactId>jackson-annotations</artifactId>
  			<version>2.5.1</version>
  		</dependency>
  		<dependency>
  			<groupId>org.hibernate</groupId>
  			<artifactId>hibernate-core</artifactId>
  			<version>4.3.5.Final</version>
  		</dependency>
  		<dependency>
  			<groupId>mysql</groupId>
  			<artifactId>mysql-connector-java</artifactId>
  			<version>5.1.29</version>
  		</dependency>
  		<dependency>
  			<groupId>org.springframework.security</groupId>
  			<artifactId>spring-security-config</artifactId>
  			<version>3.2.5.RELEASE</version>
  		</dependency>
  		<dependency>
  			<groupId>org.springframework.security</groupId>
  			<artifactId>spring-security-core</artifactId>
  			<version>3.2.5.RELEASE</version>
  		</dependency>
  		<dependency>
  			<groupId>org.springframework.security</groupId>
  			<artifactId>spring-security-web</artifactId>
  			<version>3.2.5.RELEASE</version>
  		</dependency>
  		<dependency>
  			<groupId>org.springframework</groupId>
  			<artifactId>spring-jdbc</artifactId>
  			<version>4.1.4.RELEASE</version>
  		</dependency>
  		<dependency>
  			<groupId>org.springframework</groupId>
  			<artifactId>spring-orm</artifactId>
  			<version>4.1.4.RELEASE</version>
  		</dependency>
  		<dependency>
  			<groupId>org.aspectj</groupId>
  			<artifactId>aspectjweaver</artifactId>
  			<version>1.7.4</version>
  		</dependency>
  		<dependency>
  			<groupId>org.aspectj</groupId>
  			<artifactId>aspectjrt</artifactId>
  			<version>1.7.4</version>
  		</dependency>
  	</dependencies>
  </dependencyManagement>
</project>

 

 

 

你可能感兴趣的:(Hibernate,json,springMVC,db2)