码迷,mamicode.com
首页 > 编程语言 > 详细

spring+springMvc+hibernate框架简单实例

时间:2018-03-02 10:20:57      阅读:178      评论:0      收藏:0      [点我收藏+]

标签:rman   hiberna   username   play   map   ber   creat   osc   strategy   

配置文件:

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>ssh</display-name>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  
  <!-- spring上下文监听器  -->
  
  <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
  
      
  <!-- 加载Spring和hibernate的配置文件  ioc容器-->  
      <context-param>
        <param-name>contextConfigLocation</param-name>  
        <param-value>classpath:config/applicationContext.xml</param-value>  
    </context-param> 
  
   <!-- 前端控制器  配置SpringMvc-->
  <servlet>
        <servlet-name>spring-mvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
         <!--加载spring-mvc配置文件  -->
         <init-param>  
            <param-name>contextConfigLocation</param-name>  
            <param-value>classpath:config/spring-mvc.xml</param-value>  
        </init-param>  
        <load-on-startup>1</load-on-startup>  
        <async-supported>true</async-supported>  
    </servlet>
    <servlet-mapping>
        <servlet-name>spring-mvc</servlet-name>
        <url-pattern>*.do</url-pattern>
    </servlet-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>
View Code

spring-mvc.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"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
                        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd                        
                        http://www.springframework.org/schema/context 
                        http://www.springframework.org/schema/context/spring-context-3.0.xsd">
    
    
    <!-- 注解配置 自动扫描controller  -->
    <context:component-scan base-package="com.controller" />

    <!-- 注解扫描包,只扫描@Controller的部分 -->
    <!-- <context:component-scan base-package="com.controller">
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan> -->

    <!--完成请求和注解POJO的映射 -->
    <bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor" />
    
    <!-- 定义视图解析器 -->
    <!-- <bean id="viewResolver"
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean> -->






</beans>
View Code

applicationContext.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:aop="http://www.springframework.org/schema/aop"
    xmlns:tx="http://www.springframework.org/schema/tx" 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.0.xsd
                        http://www.springframework.org/schema/tx 
                        http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
                        http://www.springframework.org/schema/aop 
                        http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
                        http://www.springframework.org/schema/context 
                        http://www.springframework.org/schema/context/spring-context-3.0.xsd">
            

        <!-- 自动扫描dao和service包(自动注入) -->
        <context:component-scan base-package="com.dao.*" />
        <context:component-scan base-package="com.service.*" />
                            
        <!-- 只解析除controller之外的注解(即解析service、dao), 避免重复加载导致事务失效  -->
        <!-- annotation为spting-mvc中解析的内容 -->
       <!--  <context:component-scan base-package="com">
            <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
        </context:component-scan>     -->        
        
    <!-- 1.数据源配置 -->    
        <bean id="dataSource" 
                class="org.springframework.jdbc.datasource.DriverManagerDataSource">
            <property name="driverClassName" value="com.mysql.jdbc.Driver" />
            <property name="url" value="jdbc:mysql://localhost:3306/com?Unicode=true&amp;characterEncoding=UTF-8" />
            <property name="username" value="root" />
            <property name="password" value="root" />
        </bean>
    
    <!-- 2.配置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>
                <!-- 其实这个hibernate.hbm2ddl.auto参数的作用主要用于:自动创建,更新,验证数据库表结构。如果不是此方面的需求建议set value="none"。 -->
                <prop key="hibernate.hbm2ddl.auto">none</prop>
                <!--是否在控制台打印sql语句  -->
                <prop key="hibernate.show_sql">true</prop>
                <!--输出格式化后的sql,更方便查看  -->
                <prop key="hibernate.format_sql">true</prop>
                <prop key="hibernate.current_session_context_class">org.springframework.orm.hibernate4.SpringSessionContext</prop>
            </props>
            <!-- 注解方式配置, -->
        </property>
        <property name="packagesToScan">
            <list>
                <!-- 此处可添加多个entity -->
                <value>com.entity</value>
            </list>
        </property>        
    </bean>
    <!-- 3.事务管理器配置 -->
        <bean id="txManager"
            class="org.springframework.orm.hibernate4.HibernateTransactionManager">
            <property name="sessionFactory" ref="sessionFactory" />
        </bean>
        <!-- 4.事务通知配置 -->
        <tx:advice id="txAdvice" transaction-manager="txManager">
            <tx:attributes>
                <tx:method name="*" />
            </tx:attributes>
        </tx:advice>
        <!-- 5.事务切面配置 -->
        <aop:config>
        <!-- 只对业务逻辑层(service层)实施事务 -->
            <aop:pointcut id="serviceCut"
                expression="execution(* com.service.*Service.*(..))" />
            <aop:advisor advice-ref="txAdvice" pointcut-ref="serviceCut" />
        </aop:config>    
</beans>  
View Code

controller(控制层)

技术分享图片
package com.controller;

import java.io.IOException;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

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.ResponseBody;

import com.entity.User;
import com.service.UserService;

@Controller
@RequestMapping("/userController")
public class UserController {

    private UserService userService;
    @Autowired
    public void setUserService(UserService userService) {
        this.userService = userService;
    }
    @RequestMapping(params = "toUserList")
    public String selectList(HttpServletRequest req){
        
        List<User> userList=userService.selectList();
    
        req.setAttribute("userList", userList);
        
        return "user/userList.jsp";
    }
    
    @RequestMapping(params = "doDel")
    @ResponseBody
    public void doDel(User user,HttpServletResponse response) throws IOException{
        
        Boolean ok=userService.delete(user);
        
        if(ok){
            String result= "{\"result\":\"成功\"}";
            response.getWriter().write(result);
        }else{
            String result= "{\"result\":\"失败\"}";
            response.getWriter().write(result);
        }
        
    }
    
    @RequestMapping(params = "toAdd")
    public String toAdd(User user,HttpServletRequest req){
        
        if(user.getId()!=null && !"".equals(user.getId())){
            
            user=userService.selectById(user);
            req.setAttribute("u", user);
        }
        
        return "user/addOrUpdUser.jsp";
    }
    
    @RequestMapping(params = "doAdd")
    public String doAdd(User user,HttpServletResponse response,HttpServletRequest req){
            
            if(user.getId()!=null && !"".equals(user.getId())){
                userService.doUpdate(user);
            }else{
                user.setId(UUID.randomUUID().toString().replace("-", ""));
                userService.doAdd(user);
            }
            
        
        return "redirect:userController.do?toUserList";
    }
    
}
View Code

service(服务层)

技术分享图片
package com.service;

import java.util.List;

import com.entity.User;

public interface UserService {

    List<User> selectList();

    Boolean delete(User user);

    void doAdd(User user);

    User selectById(User user);

    void doUpdate(User user);

    
}
View Code
技术分享图片
package com.service.impl;

import java.util.List;

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

import com.dao.UserDao;
import com.entity.User;
import com.service.UserService;
@Service
public class UserServiceImpl implements UserService{

    private UserDao userDao;
    @Autowired
    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }
    @Override
    public List<User> selectList() {
        // TODO Auto-generated method stub
        return userDao.selectList();
    }
    @Override
    public Boolean delete(User user) {
        
        return userDao.delete(user);
    }
    @Override
    public void doAdd(User user) {
        
        userDao.doAdd(user);
    }
    @Override
    public User selectById(User user) {
        
        return userDao.selectById(user);
    }
    @Override
    public void doUpdate(User user) {
        
        userDao.doUpdate(user);
    }
    
}
View Code

dao(持久层)

技术分享图片
package com.dao;

import java.util.List;

import com.entity.User;

public interface UserDao {

    List<User> selectList();

    Boolean delete(User user);

    void doAdd(User user);

    User selectById(User user);

    void doUpdate(User user);

}
View Code
技术分享图片
package com.dao.impl;

import java.util.List;

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

import com.dao.UserDao;
import com.entity.User;
@Repository
public class UserDaoImpl implements UserDao {
    
    
    private SessionFactory sessionFactory;
    @Autowired
    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }
    public Session getSession(){
        return sessionFactory.getCurrentSession();
    }
        
    @Override
    public List<User> selectList() {
        //hql 
        String hql = " from User";
        Query query = getSession().createSQLQuery(hql);
        //原生sql
        String sql="select * from user";
        List<User>    userList = getSession().createSQLQuery(sql).addEntity(User.class).list(); 
        return userList;//query.list();
    }
    @Override
    public Boolean delete(User user) {
        
//        String hql="delete User u where u.id = ?";
//        Query query = sessionFactory.getCurrentSession().createQuery(hql);
//        query.setString(0, user.getId()).executeUpdate();
    
        String sql="delete from user where id=‘"+user.getId()+"‘";
        
        return getSession().createSQLQuery(sql).executeUpdate()>0;
    }
    @Override
    public void doAdd(User user) {
        
        //getSession().save(user);
        
        String sql="insert into user values(‘"+user.getId()+"‘,‘"+user.getUserName()+"‘)";
        getSession().createSQLQuery(sql).executeUpdate();
    }
    @Override
    public User selectById(User user) {
        
        String hql = "from User u where u.id=?";
        Query query =getSession().createQuery(hql);
        query.setString(0, user.getId());
        //return (User) query.uniqueResult();
        
        String sql="select * from user where id=‘"+user.getId()+"‘";
        
        return (User) getSession().createSQLQuery(sql).addEntity(User.class).uniqueResult();
    }
    @Override
    public void doUpdate(User user) {
        
        getSession().update(user);;
        
//        String sql="update user set userName=‘"+user.getUserName()+"‘ where id=‘"+user.getId()+"‘";
//        getSession().createSQLQuery(sql).executeUpdate();
    }

}
View Code

entity(实体)

技术分享图片
package com.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 = "user")
public class User {
    
    private String id;
    private String userName;
    
    @Id
    @GeneratedValue(generator = "system-uuid")
    @GenericGenerator(name = "system-uuid", strategy = "uuid")
    @Column(length = 32)
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    @Column(name = "userName", length = 50)
    public String getUserName() {
        return userName;
    }
    public void setUserName(String userName) {
        this.userName = userName;
    }
    
}
View Code

jsp页面

技术分享图片
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>userList</title>
</head>
<script type="text/javascript" src="/ssh/js/jquery-1.10.2.js"></script>  
<style type="text/css">
    .tab{
     width:50%; 
     height:30%;
     text-align:center;
     border-collapse:collapse;
     }
</style>
<body>
        <button onclick="toAdd()">添加</button>
        <table  class="tab" border="1">
        <tr>
        <td>编号</td>
        <td>姓名</td>
        <td>操作</td>
        </tr>
    <c:forEach var="user" items="${userList}">
        <tr>
        <td>${user.id}</td>
        <td>${user.userName}</td>
        <td> 
            <a href="/ssh/userController.do?toAdd&id=${user.id }">编辑</a>  
            <a href="javascript:del(‘${user.id }‘)">删除</a> </td>
        </tr>
    </c:forEach>    
        </table>
    
</body>
<script type="text/javascript">
            function del(id){
                  $.ajax({
                         type: "POST",
                         url: "/ssh/userController.do?doDel",
                         data: {
                             id : id
                                },
                         dataType: "json",
                         success: function(data){
                             location.reload();
                                   alert(data.result);  
                                  }
                         });
            }
            
            function toAdd(){
                location.href="/ssh/userController.do?toAdd";
            }
</script>

</html>
View Code
技术分享图片
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
    <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>addOrUpdUser</title>
</head>
<body>

     <form action="/ssh/userController.do?doAdd"  method="post">  
        编号:<input type="text"  name="id" value="${u.id}" readonly="readonly">  
        姓名:<input type="text"  name="userName"  value="${u.userName}">  
        <button type="submit">确定</button> 
    </form> 


</body>
</html>
View Code

spring+springMvc+hibernate框架简单实例

标签:rman   hiberna   username   play   map   ber   creat   osc   strategy   

原文地址:https://www.cnblogs.com/libf/p/8491262.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!