一. SpringMVC
阅读我的上一篇文章《使用MyEclipse2015构建SpringMVC项目》,知道基本的构建方法,先构建一个纯springmvc项目,再对web.xml按照本文中做法简单改动。
二. Hibernate
之后用类似方法添加hibernate框架,并生成hibernate.cfg.xml和HibernateSessionFactory.java这个工厂文件。
进入MyEclipse Database Explorer,首先添加自己的服务器,之后,连接服务器,在所需的表(可多选)上右键Hibernate Reverse Engineering,根据所需功能生成实体类,不要忘记选择好主键策略。
三. Spring
这里给出只用springmvc-servlet.xml而不使用application.xml的方法
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" version="3.0"> <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:springmvc-servlet.xml</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <display-name>Spring4</display-name> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springmvc-servlet.xml</param-value> </context-param> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>
src目录下的springmvc-servlet
<?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 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd"> <!-- scan the package and the sub package --此处选择你需要注释的文件所在的公共包> <context:component-scan base-package="com.cielo.*"/> <!-- don‘t handle the static resource --> <mvc:default-servlet-handler /> <!-- if you use annotation you must configure following setting --> <mvc:annotation-driven /> <!-- configure the InternalResourceViewResolver --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver"> <!-- 前缀 --> <property name="prefix" value="/WEB-INF/jsp/" /> <!-- 后缀 --> <property name="suffix" value=".jsp" /> </bean> </beans>
这样,你就可以用近乎于无配置的方法去处理耦合
目录结构
四.Spring Annotation标签
spring目前支持用几乎无配置文件方法进行项目构建,这里简单列一个标签表
@Component
spring目前用来实现自动生成beans的标签,但是实际开发中,为了更方便阅读,一般使用三个与此等效的标签来表明层次,分别是
@Controller, @Service, @Repository
对应控制器层,业务层和DAO层。
@Autowired
根据类型名称实现自动装配,可以配合@Qualifier("Bean名称")来实现依据名字自动装配。
@Resource
根据变量名称实现自动装配。
需要注意一下,以上两个标签想实现自动装配,被装配的类要实现set和get方法
@RequestMapping("/url")
@RequestMapping(value="url",method=RequestMethod.方法名)
这个标签来定义Controller层的控制器/函数的对应连接,第二种方法可以选择post或者get方法,从而获取post和get数据。
贴一下上图目录结构中一些部分的代码
MainController.java
package com.cielo.controller; import javax.servlet.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import com.cielo.service.TbUserService; @Controller @RequestMapping("/Main") public class MainController { @Autowired TbUserService tbUserService; @RequestMapping("/add") public String add() { return "add"; } @RequestMapping(value = "/edit", method = RequestMethod.POST) public String edit(HttpServletRequest request) { boolean success = tbUserService.addAUserByNameAndPassword( request.getParameter("name"), request.getParameter("password")); if (success) return "edit"; return "error"; } public TbUserService getTbUserService() { return tbUserService; } public void setTbUserService(TbUserService tbUserService) { this.tbUserService = tbUserService; } }
TbUserService.java
package com.cielo.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.cielo.dao.TbUserDao; import com.cielo.entity.TbUser; @Service public class TbUserService { @Autowired private TbUserDao tbUserDao; public boolean addAUserByNameAndPassword(String name, String password) { TbUser tbUser = new TbUser(); tbUser.setName(name); tbUser.setPassword(password); return tbUserDao.add(tbUser); } public TbUserDao getTbUserDao() { return tbUserDao; } public void setTbUserDao(TbUserDao tbUserDao) { this.tbUserDao = tbUserDao; } public TbUserService(TbUserDao tbUserDao) { this.tbUserDao = tbUserDao; } public TbUserService() { // TODO Auto-generated constructor stub } }
TbUserDao.java(Dao负责直接和数据库对接操作,比较长,折叠给出)
package com.cielo.dao; import java.util.List; import org.hibernate.Query; import org.hibernate.Session; import org.springframework.stereotype.Repository; import com.cielo.entity.HibernateSessionFactory; import com.cielo.entity.TbUser; @Repository public class TbUserDao { public boolean add(TbUser tbUser) { Session session = null; try { session = HibernateSessionFactory.getSession(); session.beginTransaction(); session.save(tbUser); session.getTransaction().commit(); System.out.println("Success to add the user"); return true; } catch (Exception e) { session.getTransaction().rollback(); System.out.println("Fail to add the user"); e.printStackTrace(); } return false; } public TbUser selectById(int id){ Session session=null; try{ session=HibernateSessionFactory.getSession(); String hql="from TbUser as tb_user where tb_user.id=:id"; Query query=session.createQuery(hql); query.setInteger("id", id); List list=query.list(); return (TbUser) list.get(0); }catch(Exception e){ System.out.println("Fail to select the item by id"); e.printStackTrace(); } return null; } public TbUser selectByName(String name){ Session session=null; try{ session=HibernateSessionFactory.getSession(); String hql="from TbUser as tb_user where tb_user.name=:name"; Query query=session.createQuery(hql); query.setString("name", name); List list=query.list(); return (TbUser) list.get(0); }catch(Exception e){ System.out.println("Fail to select the item by name"); e.printStackTrace(); } return null; } public boolean deleteById(int id){ Session session=null; try{ session=HibernateSessionFactory.getSession(); session.beginTransaction(); String hqlString="delete from TbUser tb_user where tb_user.id=:id"; Query query=session.createQuery(hqlString); query.setInteger("id", id); session.getTransaction().commit(); return true; }catch(Exception e){ session.getTransaction().rollback(); System.out.println("Fail to delete the item by id"); e.printStackTrace(); } return false; } public boolean deleteByName(String name){ Session session=null; try{ session=HibernateSessionFactory.getSession(); session.beginTransaction(); String hqlString="delete from TbUser tb_user where tb_user.name=:name"; Query query=session.createQuery(hqlString); query.setString("name", name); session.getTransaction().commit(); return true; }catch(Exception e){ session.getTransaction().rollback(); System.out.println("Fail to delete the item by name"); e.printStackTrace(); } return false; } public boolean deleteByTbUser(TbUser tbUser){ Session session=null; try{ session=HibernateSessionFactory.getSession(); session.beginTransaction(); session.delete(tbUser); session.getTransaction().commit(); return true; }catch(Exception e){ session.getTransaction().rollback(); System.out.println("Fail to delete the item by tbUser"); e.printStackTrace(); } return false; } public boolean update(TbUser tbUser) { Session session = null; try { session = HibernateSessionFactory.getSession(); session.beginTransaction(); session.update(tbUser); session.getTransaction().commit(); System.out.println("Success to update the user"); return true; } catch (Exception e) { session.getTransaction().rollback(); System.out.println("Fail to update the user"); e.printStackTrace(); } return false; } public TbUserDao() { // TODO Auto-generated constructor stub } }
TbUser实体类,利用hibernate自动生成的标签,不再需要hbm文件去对应,只需要再hibernate.cfg.xml中设置一下Mapping即可
package com.cielo.entity; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; /** * TbUser entity. @author MyEclipse Persistence Tools */ @Entity @Table(name = "tb_user", schema = "dbo", catalog = "Web") public class TbUser implements java.io.Serializable { // Fields private Integer id; private String name; private String password; // Constructors /** default constructor */ public TbUser() { } /** full constructor */ public TbUser(Integer id, String name, String password) { this.id = id; this.name = name; this.password = password; } // Property accessors @Id @Column(name = "id", unique = true, nullable = false) @GeneratedValue public Integer getId() { return this.id; } public void setId(Integer id) { this.id = id; } @Column(name = "name", nullable = false) public String getName() { return this.name; } public void setName(String name) { this.name = name; } @Column(name = "password", nullable = false) public String getPassword() { return this.password; } public void setPassword(String password) { this.password = password; } }
完整代码见github上此项目