JavaWeb-Maven构建ssh框架

1 环境

 

搭建SpringMVC+Spring+Hibernate4 ,Maven环境、 需要MySQL 数据库支持,使用的编程工具Eclipse  

搭建完毕后的项目架构如下:

JavaWeb-Maven构建ssh框架_第1张图片


2 新建Maven项目

2.1 新建Maven项目

JavaWeb-Maven构建ssh框架_第2张图片

2.2 选择web项目

JavaWeb-Maven构建ssh框架_第3张图片
JavaWeb-Maven构建ssh框架_第4张图片

点击【finish】

3 新建的项目架构

JavaWeb-Maven构建ssh框架_第5张图片

新建完毕,项目报错,并且缺少目录。修改如下:

3.1 显示所有的目录

目录结构为:

src/main/resources

src/main/java

src/test/resources

src/test/java

 

【右键项目】-->【Build Path】--> 【Configure Build Path】
JavaWeb-Maven构建ssh框架_第6张图片

JavaWeb-Maven构建ssh框架_第7张图片

会看见所有的目录,没有看见的目录拉其滚动条就可看见

JavaWeb-Maven构建ssh框架_第8张图片

 然后点击【Apply】-->【OK】即可。

如果没有出现,则重复以上步骤,然后双击【Allow ouput folders for source folders】,再进行【Apply】。

JavaWeb-Maven构建ssh框架_第9张图片

最后项目结构如下:

JavaWeb-Maven构建ssh框架_第10张图片

以上结构还需要添加一些东西,选中【项目右键】-->  【Build Path】--> 【new Source Folder】--> 【输入文件夹名称】--> 【Finish】.

这里新建src/test/resources 

JavaWeb-Maven构建ssh框架_第11张图片

JavaWeb-Maven构建ssh框架_第12张图片

目录如下:

JavaWeb-Maven构建ssh框架_第13张图片

3.2 修改项目的编辑版本

默认项目的编译级别是1.5 ,有一些JDK的新特性可能会报错,所以需要更换项目的编译级别。修改如下:

【右键项目】-->【Properties】

JavaWeb-Maven构建ssh框架_第14张图片

JavaWeb-Maven构建ssh框架_第15张图片

去掉选择,更换编译版本1.8

JavaWeb-Maven构建ssh框架_第16张图片


选择【Project Facets】然后修改Java版本,因为安装的是JDK1.8 所以选择1.8

JavaWeb-Maven构建ssh框架_第17张图片

JavaWeb-Maven构建ssh框架_第18张图片

然后点击【Apply】-->【OK】


3.3 加入依赖

结果工程还是报错,因为缺少类javax.servlet.http.HttpServlet,此类在javax包中。

在pom.xml中加入以下依赖:

JavaWeb-Maven构建ssh框架_第19张图片

  
          
            jstl  
            jstl  
            1.2  
          
          
            javax.servlet  
            servlet-api  
            2.5  
            provided  
          
        
          
            javax.servlet  
            jsp-api  
            2.0  
            provided  
          
  

查看项目:

JavaWeb-Maven构建ssh框架_第20张图片

3.4 设置部署程序集(Web Deployment Assembly)

右键项目,选择[properties] -->[Deployment Assembly] 如下图:



4 Spring与Hibernate的整合

4.1 基本配置

4.1.1 添加依赖(pom.xml)

 
		
			org.springframework
			spring-core
			${spring.version}
		

		
			org.springframework
			spring-beans
			${spring.version}
		

		
			org.springframework
			spring-context
			${spring.version}
		

		
			org.springframework
			spring-tx
			${spring.version}
		

		
			org.springframework
			spring-web
			${spring.version}
		

		
			org.springframework
			spring-test
			${spring.version}
			test
		

		
		
			org.springframework
			spring-webmvc
			${spring.version}
		

		
		
			org.springframework
			spring-orm
			${spring.version}
		

		
		
			org.hibernate
			hibernate-core
			${hibernate.version}
		

		
			org.hibernate
			hibernate-ehcache
			${hibernate.version}
		

		
		
			net.sf.ehcache
			ehcache
			2.9.0
		

		
		
			log4j
			log4j
			1.2.17
		

		
		
			mysql
			mysql-connector-java
			5.1.34
		

		
		
			com.mchange
			c3p0
			0.9.5-pre10
		

		
		
			com.alibaba
			fastjson
			1.2.3
		

		
			com.fasterxml.jackson.core
			jackson-annotations
			${jackson.version}
		

		
			com.fasterxml.jackson.core
			jackson-core
			${jackson.version}
		

		
			com.fasterxml.jackson.core
			jackson-databind
			${jackson.version}
		

		
		
			org.aspectj
			aspectjweaver
			1.8.4
		

		
		
			jstl
			jstl
			1.2
		
		
			javax.servlet
			servlet-api
			2.5
			provided
		

		
			javax.servlet
			jsp-api
			2.0
			provided
		

4.1.2 configure.properties

#application configs

#jdbc c3p0 config
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/db_test?useUnicode=true&characterEncoding=utf-8
jdbc.username=root
jdbc.password=123456

#hibernate config
hibernate.dialect=org.hibernate.dialect.MySQLDialect
hibernate.show_sql=true
hibernate.format_sql=true
hibernate.hbm2ddl.auto=create
hibernate.cache.use_second_level_cache=true
hibernate.cache.use_query_cache=true
hibernate.cache.region.factory_class=org.hibernate.cache.ehcache.EhCacheRegionFactory
hibernate.cache.provider_configuration_file_resource_path=ehcache.xml

4.1.3 spring.xml



			
	
	
	
	



4.1.4 spring-hibernate.xml

  
  
  
      
      
          
          
          
          
  
          
          
          
          
          
          
          
          
          
          
          
          
      
  
      
      
          
          
          
          
              
                ${hibernate.dialect}  
                ${hibernate.show_sql}  
                ${hibernate.format_sql}  
                ${hibernate.hbm2ddl.auto}  
  
                  
                ${hibernate.cache.use_second_level_cache}  
                ${hibernate.cache.use_query_cache}  
                ${hibernate.cache.region.factory_class}  
                ${hibernate.cache.provider_configuration_file_resource_path}  
                  
              
          
          
          
      
  
      
      
          
      
  
  
  
  

4.1.5 Log4j的配置

### set log levels ###  
log4j.rootLogger = INFO , C , D , E   
  
### console ###  
log4j.appender.C = org.apache.log4j.ConsoleAppender  
log4j.appender.C.Target = System.out  
log4j.appender.C.layout = org.apache.log4j.PatternLayout  
log4j.appender.C.layout.ConversionPattern = [student][%p] [%-d{yyyy-MM-dd HH:mm:ss}] %C.%M(%L) | %m%n  
  
### log file ###  
log4j.appender.D = org.apache.log4j.DailyRollingFileAppender  
log4j.appender.D.File = ./logs/student.log  
log4j.appender.D.Append = true  
log4j.appender.D.Threshold = INFO   
log4j.appender.D.layout = org.apache.log4j.PatternLayout  
log4j.appender.D.layout.ConversionPattern = [student][%p] [%-d{yyyy-MM-dd HH:mm:ss}] %C.%M(%L) | %m%n  
  
### exception ###  
log4j.appender.E = org.apache.log4j.DailyRollingFileAppender  
log4j.appender.E.File = ./logs/student_error.log   
log4j.appender.E.Append = true  
log4j.appender.E.Threshold = ERROR   
log4j.appender.E.layout = org.apache.log4j.PatternLayout  
log4j.appender.E.layout.ConversionPattern = [student][%p] [%-d{yyyy-MM-dd HH:mm:ss}] %C.%M(%L) | %m%n  

配置结构截图:





4.2 编写Entity

User代码:

package cn.ssh.student.entity;

import java.io.Serializable;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "t_user")
public class User implements Serializable {
	@Id
     // 配置自动增长
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	private Integer id;

	private String userName;

	private String password;

	private Integer age;

	private static final long serialVersionUID = 1L;

	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 == null ? null : userName.trim();
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password == null ? null : password.trim();
	}

	public Integer getAge() {
		return age;
	}

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

	@Override
	public String toString() {
		return "User [id=" + id + ", userName=" + userName + ", password=" + password + ", age=" + age + "]";
	}

}

4.3 Dao层

4.3.1 GenericDao接口

package cn.ssh.student.dao;

import java.io.Serializable;
import java.util.List;

public interface GenericDao {  
    
    T load(PK id);  
      
    T get(PK id);  
      
    List findAll();  
      
    void persist(T entity);  
      
    PK save(T entity);  
      
    void saveOrUpdate(T entity);  
      
    void delete(PK id);  
      
    void flush();  
}  


4.3.2 UserDao接口

 package cn.ssh.student.dao;

import cn.ssh.student.entity.User;
 
 
public interface UserDao extends GenericDao {  
  
}  

4.3.3 UserDao接口实现类

package cn.ssh.student.dao.impl;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import cn.ssh.student.dao.UserDao;
import cn.ssh.student.entity.User;

@Repository
public class UserDaoImpl implements UserDao {

	@Autowired
	private SessionFactory sessionFactory;

	private Session getCurrentSession() {
		return this.sessionFactory.getCurrentSession();
	}

	@Override
	public User load(String id) {
		return (User) this.getCurrentSession().load(User.class, id);
	}

	@Override
	public User get(String id) {
		return (User) this.getCurrentSession().get(User.class, id);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List findAll() {
		List Users = this.getCurrentSession().createQuery("from User").setCacheable(true).list();
		return Users;
	}

	@Override
	public void persist(User entity) {
		this.getCurrentSession().persist(entity);

	}

	@Override
	public String save(User entity) {
		return (String) this.getCurrentSession().save(entity);
	}

	@Override
	public void saveOrUpdate(User entity) {
		this.getCurrentSession().saveOrUpdate(entity);
	}

	@Override
	public void delete(String id) {
		User entity = this.load(id);
		this.getCurrentSession().delete(entity);
	}

	@Override
	public void flush() {
		this.getCurrentSession().flush();

	}
}

项目架构:

4.4 Service层

4.4.1 UserService接口

 package cn.ssh.student.service;

import java.util.List;

import cn.ssh.student.entity.User;

public interface UserService {
	User load(Integer id);

	User get(Integer id);

	List findAll();

	void persist(User entity);

	Integer save(User entity);

	void saveOrUpdate(User entity);

	void delete(Integer id);

	void flush();
}

4.4.2 UserService接口实现类

package cn.ssh.student.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.ssh.student.dao.UserDao;
import cn.ssh.student.entity.User;
import cn.ssh.student.service.UserService;

@Service
public class UserServiceImpl implements UserService {
	@Autowired
	private UserDao userDao;

	@Override
	@Transactional(readOnly = true)
	public User load(Integer id) {
		return userDao.load(id);
	}

	@Override
	@Transactional(readOnly = true)
	public User get(Integer id) {
		return userDao.get(id);
	}

	@Override
	@Transactional(readOnly = true)
	public List findAll() {
		return userDao.findAll();
	}

	@Override
	@Transactional
	public void persist(User entity) {
		userDao.persist(entity);
	}

	@Override
	@Transactional
	public Integer save(User entity) {
		return userDao.save(entity);
	}

	@Override
	@Transactional
	public void saveOrUpdate(User entity) {
		userDao.saveOrUpdate(entity);
	}

	@Override
	@Transactional
	public void delete(Integer id) {
		userDao.delete(id);
	}

	@Override
	@Transactional
	public void flush() {
		userDao.flush();
	}

}

4.5 测试



测试代码:

package cn.ssh.student.service;

import java.util.List;

import org.apache.log4j.Logger;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import cn.ssh.student.entity.User;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:spring.xml", "classpath:spring-hibernate.xml" })
public class UserServiceTest {

	private static final Logger LOGGER = Logger.getLogger(UserServiceTest.class);

	@Autowired
	private UserService userService;

	@Test
	public void testLoad() {
		System.out.println(userService);
	}

	@Test
	public void testGet() {
		User user = userService.get(5);
		System.out.println(user);
	}

	@Test
	public void testFindAll() {
		List users = userService.findAll();
		System.out.println(users);
	}

	@Test
	public void testPersist() {
	
	}

	@Test
	public void testSave() {
		User user = new User();
		user.setAge(1);
		user.setPassword("123");
		user.setUserName("李四");
		userService.save(user);
	}

	
	@Test
	public void testSaveOrUpdate() {
	
	}

	@Test
	public void testDelete() {
	
	}

	@Test
	public void testFlush() {
	
	}

}

执行testLoad()测试方法,测试成功,数据库自动生成表:






5 整合SpringMVC

5.1 spring-mvc.xml




	
	

	
	
		
		
			
				
					
						text/html;charset=UTF-8
						application/json;charset=UTF-8
					
				

			
		
	

	
	
		
		
		
	
  

spring-mvc的配置信息可以直接整合在spring-hibernate.xml这个配置文件中。

5.2 web.xml



	Archetype Created Web Application


	
		contextConfigLocation
		classpath:spring.xml,classpath:spring-hibernate.xml
	

	
		encodingFilter
		org.springframework.web.filter.CharacterEncodingFilter
		
			encoding
			UTF-8
		
		
			forceEncoding
			true
		
	
	
		encodingFilter
		/*
	

	
	
		openSessionInViewFilter
		org.springframework.orm.hibernate4.support.OpenSessionInViewFilter
		
			singleSession
			true
		
	

	
		openSessionInViewFilter
		*.jsp
	

	
	
		org.springframework.web.context.ContextLoaderListener
	

	
	
		org.springframework.web.util.IntrospectorCleanupListener
	


	
	
		spring mvc servlet
		SpringMVC
		org.springframework.web.servlet.DispatcherServlet
		
			contextConfigLocation
			
			classpath:spring-mvc.xml
		
		1
	

	
		SpringMVC
		*.do
	

	
	
		30
	

	
		/index.jsp
	



6 项目运行

内置tomcat运行

启动时为:tomcat7:run 因为在配置pom.xml中配置了tomcat插件的名字。


启动项目:

点击【Run】

启动成功:

7 用户管理

7.1 增加用户

页面预览

添加界面效果如图:

输入内容,并提交



7.1.1 后台代码

Controller层:
	// 添加
	@RequestMapping("/add")
	public String add(User user) {
		userService.save(user);
		// 重定向到查询所有用户
		return "redirect:getAll.do";
	}

	// 查询所有的用户
	@RequestMapping("/getAll")
	public String getAll(Model model) {
		List list = userService.findAll();
		model.addAttribute("userList", list);
		return "show";
	}


Service层:
 	@Override
	@Transactional
	public Integer save(User entity) {
		return userDao.save(entity);
	}
	@Override
	@Transactional(readOnly = true)
	public List findAll() {
		return userDao.findAll();
	}

7.1.2 页面代码

add.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"  %>




Insert title here


姓名: 年龄: 密码:


查看所有页面代码(show.jsp):

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>





测试



	
    ${user.id}  ${user.userName}   删除  更新  
新增

7.2 查找用户

在浏览器中输入地址:http://localhost:8080/student/getById.do?id=2


7.2.1 后台代码

Controller层:
	// 查询某一个用户
	@RequestMapping("/getById")
	public String getById(Integer id, Model model) {
		User user = userService.get(id);
		model.addAttribute("user", user);
        // 转发到showUser.jsp页面
		return "showUser";
	}

Service层
 	@Override
	@Transactional(readOnly = true)
	public User get(Integer id) {
		return userDao.get(id);
	}


7.2.2 页面代码

showUser.jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"  %>




  
	查询单个用户
  
  
  
    ${user.id}  ${user.userName}
  


7.3 修改用户

查询所有用户,地址:http://localhost:8080/student/getAll.do

点击王武后面的【更新】

结果:


7.3.1 后台代码

Controller层:
	
	@RequestMapping("/update")
	public String update(User user){
		userService.saveOrUpdate(user);
        // 更新成功,重定向查询所有
		return "redirect:getAll.do";
	}
	
	//更新之前
	@RequestMapping("/proupdate")
	public String proUpdate(Integer id,Model model){
		User user = userService.get(id);
		model.addAttribute("user",user);
		return "update";
	}

Service层:
	@Override
	@Transactional(readOnly = true)
	public User get(Integer id) {
		return userDao.get(id);
	}
	
	@Override
	@Transactional
	public void saveOrUpdate(User entity) {
		userDao.saveOrUpdate(entity);
	}

7.3.2 页面代码

update.jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>




Insert title here


姓名: 年龄: 密码:

7.4 删除用户


点击【删除】


7.4.1 后台代码

Controller层:
// 删除某一个用户
	@RequestMapping("/delete")
	public String delete(Integer id,Model model) {
		userService.delete(id);
		// 重定向到查询所有的用户
		return "redirect:getAll.do";
	}
Service层:
	@Override
	@Transactional
	public void delete(Integer id) {
		userDao.delete(id);
	}

8 项目下载

http://download.csdn.net/download/anoiadream/9935156
 

9 参考博客

http://blog.csdn.net/Ethan_Fu/article/details/49449369




你可能感兴趣的:(Java)