前段时间学习了下springmvc+hibernate.用这个框架实现了增删改查,想把学习的东西贴出来,和大家一起交流。由于之前没有学过什么框架之类的东西,在学习时遇到了很多困难,学的也很慢。
我学先看的是hibernate,hibernate主要是用在数据持久层,用来把数据持久化,建立java实体bean与数据库中表的对应。利用hibernate操作数据库时就有很多封装好了的方法,很方便调用。再学的是spring,知道它是作为一个容器在使用,以及ioc和aop,不过我这里基本没有用到aop,没有涉及到切面的编程。在学springmvc时,以为它就是spring,根本没有想这是一个基于MVC的框架,框架这东西之前我是一直都不理解。后来靠给我讲了下,这个框架里面最重要的就是分层,它的模型层就是与数据库打交道的,控制层是不与数据打交道的,是在业务层的基础上进行控制,而业务层是实现模型层的一些方法,最后是用视图层进行显示,搞清楚逻辑关系是很重要的。
直接贴代码:
实体类:student.java
package com.xl.entity; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.SequenceGenerator; import javax.persistence.Table; @Entity @Table(name="student") public class Student { @Id @SequenceGenerator(name="seq_student",sequenceName="seq_student") @GeneratedValue(strategy=GenerationType.SEQUENCE,generator="seq_student") @Column(length=20) private Integer id; @Column(length=50) private String name; @Column(length=20) private Integer age; @Column(length=50) private String course; public Student(){} public Student(Integer id,String name,String course,Integer age){ this.id=id; this.age=age; this.name=name; this.course=course; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public String getCourse() { return course; } public void setCourse(String course) { this.course = course; } }
IStudentDao.java
package com.xl.dao; import java.util.List; import com.xl.entity.Student; public interface IStudentDao { public void addStudent(Student stu); public List<Student> getAllStudents(); public Student getStudentById(Integer id); public void delStudent(Integer id); public void update(Student stu); }
StudentService.java
package com.xl.service; import java.util.List; import javax.annotation.Resource; import org.hibernate.SessionFactory; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.xl.dao.IStudentDao; import com.xl.entity.Student; @Service @Transactional public class StudentService implements IStudentDao { @Resource private SessionFactory sessionFactory; public void addStudent(Student stu) { sessionFactory.getCurrentSession().persist(stu); } @SuppressWarnings("unchecked") public List<Student> getAllStudents() { return sessionFactory.getCurrentSession().createQuery("from Student order by id").list(); } public Student getStudentById(Integer id) { return (Student) sessionFactory.getCurrentSession().get(Student.class, id); } public void delStudent(Integer id) { sessionFactory.getCurrentSession().delete(sessionFactory.getCurrentSession().load(Student.class, id)); } public void update(Student stu) { sessionFactory.getCurrentSession().update(stu); } }
StudentController.java
package com.xl.controller; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.util.List; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import com.xl.dao.IStudentDao; import com.xl.entity.Student; @Controller @RequestMapping("/student") public class StudentController { @Resource private IStudentDao studentService; /** * 获取学生列表 在首页显示 * @param req * @param rep * @return */ @RequestMapping("/stu") public String tostu(HttpServletRequest req,HttpServletResponse rep){ List<Student> students=studentService.getAllStudents(); req.setAttribute("studentlist", students); return "stu"; } /** * 根据获取的id删除对应的学生信息 * @param req * @param rep * @param id * @return */ @RequestMapping("/del") public String del(HttpServletRequest req,HttpServletResponse rep,Integer id){ studentService.delStudent(id); List<Student> students=studentService.getAllStudents(); req.setAttribute("studentlist", students); return "stu"; } /** * 在增加学生信息时候 这里要注意编码 * 要先判断名字,年龄是否为空。也可以用ajax,对于更新就不是用这方法 * @param name * @param age * @param course * @param req * @param rep * @return */ @RequestMapping("/add") public String add(String name,Integer age,String course, HttpServletRequest req,HttpServletResponse rep){ try { rep.setContentType("text/html;charset=utf-8"); Student student=null; student = new Student(null,URLDecoder.decode(name,"utf-8"),URLDecoder.decode(course,"utf-8"),age); studentService.addStudent(student); List<Student> students=studentService.getAllStudents(); req.setAttribute("studentlist", students); return "stu"; //printWriter.write("qq".getBytes()); } catch (Exception e) { e.printStackTrace(); return null; } } /** * 根据传来的id取出student在页面中显示出来,与update分开 * @param req * @param id * @return */ @RequestMapping("/toUpdate") public String toUpdate(HttpServletRequest req,Integer id){ //查找要更新的数据 Student student=studentService.getStudentById(id); //放入作用域 req.setAttribute("student", student); return "update"; } /** * 类似于删除,根据传来的student。直接用StudentService里的update方法更新 * @param student * @param req * @param rep */ @RequestMapping("/update") public String update(Student student,HttpServletRequest req,HttpServletResponse rep){ try{ System.out.println("12121212"); rep.setContentType("text/html;charset=utf-8"); Student newstudent=null; newstudent=new Student(student.getId(),URLDecoder.decode(student.getName(),"utf-8"), URLDecoder.decode(student.getCourse(),"utf-8"),student.getAge()); studentService.update(newstudent); List<Student> students=studentService.getAllStudents(); req.setAttribute("studentlist", students); return "stu"; }catch(Exception e){ e.printStackTrace(); return null; } } }
配置文件
beans.xml
<?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:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd" > <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driverClass" value="oracle.jdbc.driver.OracleDriver"></property> <property name="jdbcUrl" value="jdbc:oracle:thin:@localhost:1521:orcl"/> <property name="user" value="scott"/> <property name="password" value="xuli"/> <property name="initialPoolSize" value="5"></property> <property name="minPoolSize" value="5"></property> <property name="maxPoolSize" value="15"/> <property name="checkoutTimeout" value="1000"/> </bean> <!-- 配置sessionfactory --> <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> <property name="hibernateProperties"> <value> hibernate.dialect=org.hibernate.dialect.OracleDialect hibernate.hbm2ddl.auto=update hibernate.show_sql=true hibernate.format_sql=false </value> </property> <property name="configLocations"> <list> <value> classpath*:config/hibernate.cfg.xml </value> </list> </property> </bean> <!-- 配置事务管理器 --> <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory" /> </bean> <tx:annotation-driven transaction-manager="transactionManager"/> <!-- 自动扫描(自动注入) --> <context:component-scan base-package="com.xl" /> </beans>
hibernate.hbm.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <mapping class="com.xl.entity.Student"/> </session-factory> </hibernate-configuration>
Springmvc-servlet.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd"> <!-- 自动扫描controller包下的所有类,使其认为spring mvc的控制器 --> <context:component-scan base-package="com.xl.controller" /> <!-- 对模型视图名称的解析,即在模型视图名称添加前后缀 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" p:prefix="/" p:suffix=".jsp" /> </beans>
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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" 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>zx</display-name> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath*:config/beans.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <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*:config/Springmvc-servlet.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <filter> <filter-name>openSessionInViewFilter</filter-name> <filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class> <init-param> <param-name>singleSession</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>openSessionInViewFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <filter> <filter-name>characterEncodingFilter</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> <init-param> <param-name>forceEncoding</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>characterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app>
最后的效果是:
在学习过程中也遇到很多低级的问题,如果是像我这样的新手的话,刚开始可能都会遇到,第一个就是jar包问题,我在前面几天调试的时候经常报的错就是jar包冲突或是缺少jar包,第二个就是配置文件的问题,总是搞不清楚怎么配,只是去复制粘贴别人的配置文件,自己又不是很懂,刚开始时程序都跑不起来。再有的一些问题基本就是一些细节性的问题,比如编码问题等。
只是很简单的一个实现,像分页,插入日志等都没有做,我也不是很会,还在继续学习中,水平有限,还望轻喷。