IntelliJ IDEA 创建Spring+SpringMVC+hibernate+…

2018-06-18 02:15:51来源:未知 阅读 ()

新老客户大回馈,云服务器低至5折

第一步: 新建maven管理的web项目, 具体步骤参考:http://www.cnblogs.com/gczmn/p/8693734.html

第二步: 创建项目结构, 完整项目结构如下:

 

第三步: 填充文件,有些地方如果不是上面目录的样子需要自己改变,已经使用颜色做出标记

  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/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.SshProject</groupId>
  <artifactId>SshProject</artifactId>
  <packaging>war</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>SshProject Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <!-- 本人将配置包的版本信息都统一放入此处,方便以后管理-->
  <properties>
    <springVersion>4.3.1.RELEASE</springVersion>
    <hibernateVersion>4.3.5.Final</hibernateVersion>
    <jstlVersion>1.2</jstlVersion>
    <taglibVersion>1.1.2</taglibVersion>
    <servletVersion>3.0-alpha-1</servletVersion>
    <jsonVersion>1.9.13</jsonVersion>
    <jacksonVersion>2.5.0</jacksonVersion>
    <mysqlVersion>5.1.38</mysqlVersion>
    <c3p0Version>0.9.1.2</c3p0Version>
    <log4jVersion>1.2.17</log4jVersion>
    <fileuploadVersion>1.3.1</fileuploadVersion>
    <lombokVersion>1.16.10</lombokVersion>
  </properties>

  <dependencies>
    <!-- 单元测试 -->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>

    <!-- spring-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-beans</artifactId>
      <version>${springVersion}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-core</artifactId>
      <version>${springVersion}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>${springVersion}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-orm</artifactId>
      <version>${springVersion}</version>
    </dependency>

    <!-- spring web + spring MVC-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>${springVersion}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>${springVersion}</version>
    </dependency>

    <!-- hibernate配置-->
    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-core</artifactId>
      <version>${hibernateVersion}</version>
    </dependency>

    <!-- hibernate 缓存, 视情况添加-->
    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-ehcache</artifactId>
      <version>${hibernateVersion}</version>
    </dependency>

    <!-- jsp页面使用的jstl支持-->
    <dependency>
      <groupId>jstl</groupId>
      <artifactId>jstl</artifactId>
      <version>${jstlVersion}</version>
    </dependency>
    <dependency>
      <groupId>taglibs</groupId>
      <artifactId>standard</artifactId>
      <version>${taglibVersion}</version>
    </dependency>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>servlet-api</artifactId>
      <version>${servletVersion}</version>
      <scope>provided</scope>
    </dependency>

    <!-- DataBase数据库连接 mysql包-->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>${mysqlVersion}</version>
    </dependency>

    <!-- 数据库连接池-->
    <dependency>
      <groupId>c3p0</groupId>
      <artifactId>c3p0</artifactId>
      <version>${c3p0Version}</version>
    </dependency>

    <!-- json数据 使springMVC可以返回json值 ,视情况添加-->
    <dependency>
      <groupId>org.codehaus.jackson</groupId>
      <artifactId>jackson-mapper-asl</artifactId>
      <version>${jsonVersion}</version>
    </dependency>

    <!-- Jackson可以轻松的将Java对象转换成json对象和xml文档,同样也可以将json、xml转换成Java对象-->
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-core</artifactId>
      <version>${jacksonVersion}</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-annotations</artifactId>
      <version>${jacksonVersion}</version>
    </dependency>

    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>${jacksonVersion}</version>
    </dependency>

    <!-- log4j配置, 视情况添加-->
    <dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
      <version>${log4jVersion}</version>
    </dependency>

    <!--文件 上传-->
    <dependency>
      <groupId>commons-fileupload</groupId>
      <artifactId>commons-fileupload</artifactId>
      <version>${fileuploadVersion}</version>
    </dependency>

    <!-- lombok插件导包-->
    <dependency>
      <groupId>org.projectlombok</groupId>
      <artifactId>lombok</artifactId>
      <version>${lombokVersion}</version>
      <scope>provided</scope>
    </dependency>

  </dependencies>
  <build>
    <finalName>SshProject</finalName>
  </build>
</project>

spring-hibernate.xml

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:tx="http://www.springframework.org/schema/tx"
       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-4.1.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-4.1.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx-4.1.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd">

    <!--********************************************配置Spring***************************************-->
    <!-- 自动扫描 决定扫描哪个包下的文件-->
    <context:component-scan base-package="com.sshProject">
        <!-- 扫描时跳过 @Controller 注解的JAVA类(控制器) -->
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>

    <!--********************************************配置hibernate********************************************-->

    <!--扫描配置文件(这里指向的是之前配置的那个jdbc.properties) 如果有改动需要修改-->
    <context:property-placeholder location="classpath:jdbc.properties" />

    <!--配置数据源-->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
        <property name="driverClass" value="${jdbc.driver}" />  <!--数据库连接驱动-->
        <property name="jdbcUrl" value="${jdbc.url}" />     <!--数据库地址-->
        <property name="user" value="${jdbc.username}" />   <!--用户名-->
        <property name="password" value="${jdbc.password}" />   <!--密码-->
        <property name="maxPoolSize" value="40" />      <!--最大连接数-->
        <property name="minPoolSize" value="1" />       <!--最小连接数-->
        <property name="initialPoolSize" value="10" />      <!--初始化连接池内的数据库连接-->
        <property name="maxIdleTime" value="20" />  <!--最大空闲时间-->
    </bean>

    <!--配置session工厂-->
    <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
<!--如果有修改需要改成对应的配置文件-->
<property name="packagesToScan" value="com.sshProject.entity" /> <property name="hibernateProperties"> <props> <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop> <!--hibernate根据实体自动生成数据库表--> <prop key="hibernate.dialect">${hibernate.dialect}</prop> <!--指定数据库方言--> <prop key="hibernate.show_sql">${hibernate.show_sql}</prop> <!--在控制台显示执行的数据库操作语句--> <prop key="hibernate.format_sql">${hibernate.format_sql}</prop> <!--在控制台显示执行的数据哭操作语句(格式)--> </props> </property> </bean> <!-- 事物管理器配置 --> <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory" /> </bean> <tx:annotation-driven transaction-manager="transactionManager" /> </beans>

spring-mvc.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.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.0.xsd
    http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
    <!-- 启动注解驱动的spring MVC功能,注册请求url和注解POJO类方法的映射-->
    <mvc:annotation-driven />

    <context:component-scan base-package="com.sshProject" />
     <!--静态文件-->
    <mvc:default-servlet-handler/>
    <!-- 对模型视图名称的解析,在请求时模型视图名称添加前后缀 -->
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
        <property name="prefix" value="views/" />      <!-- 前缀 -->
        <property name="suffix" value=".jsp" />   <!-- 后缀 -->
    </bean>

</beans>

jdbc.properties

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

#hibernate config
hibernate.dialect = org.hibernate.dialect.MySQLDialect
hibernate.show_sql = true
hibernate.format_sql = true
hibernate.hbm2ddl.auto = update

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">
  <display-name>Archetype Created Web Application</display-name>
  <servlet>
    <servlet-name>spring</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <!-- 此处指向的的是SpringMVC的配置文件 -->
      <param-value>classpath:config/spring-mvc.xml,classpath:config/spring-hibernate.xml</param-value>
    </init-param>
    <!--配置容器在启动的时候就加载这个servlet并实例化-->
    <load-on-startup>1</load-on-startup>
  </servlet>

  <servlet-mapping>
    <servlet-name>spring</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
  <welcome-file-list>
    <welcome-file>/index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

PersonController.java

package com.sshProject.controller;

import com.sshProject.entity.Person;
import com.sshProject.service.PersonService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;


@Controller
public class PersonController {

    @Autowired
    private PersonService personService;
        @RequestMapping("/getAllPerson")
        public String getAllPerson(HttpServletRequest request){

            request.setAttribute("personList", personService.getAllPerson());

            return "/index";
        }

        @RequestMapping("/getPerson")
        public String getPerson(String id,HttpServletRequest request){

            request.setAttribute("person", personService.getPerson(id));

            return "/editPerson";
        }

        @RequestMapping("/toAddPerson")
        public String toAddPerson(){
            return "/addPerson";
        }

        @RequestMapping("/addPerson")
        public String addPerson(Person person, HttpServletRequest request){

            personService.addPerson(person);

            return "redirect:/getAllPerson";
        }

        @RequestMapping("/delPerson")
        public void delPerson(String id,HttpServletResponse response){

            String result = "{\"result\":\"error\"}";

            if(personService.delPerson(id)){
                result = "{\"result\":\"success\"}";
            }

            response.setContentType("application/json");

            try {
                PrintWriter out = response.getWriter();
                out.write(result);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        @RequestMapping("/updatePerson")
        public String updatePerson(Person person,HttpServletRequest request){

            if(personService.updatePerson(person)){
                person = personService.getPerson(String.valueOf(person.getId()));
                request.setAttribute("person", person);
                return "redirect:/getAllPerson";
            }else{
                return "/error";
            }
        }
    }

PersonDao.java

package com.sshProject.dao;

import com.sshProject.entity.Person;

import java.util.List;

public interface PersonDao {
    Person getPerson(String id);

    List<Person> getAllPerson();

    void addPerson(Person person);

    boolean delPerson(String id);
boolean updatePerson(Person person); }

PersonDaoImpl.java 

 注意: 这个类里sql语句的Person 是实体类Person的名字, 数据库中也有一个person表, hibernate是根据实体类来映射的好像

package com.sshProject.dao.impl;

import com.sshProject.dao.PersonDao;
import com.sshProject.entity.Person;
import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;


@Repository
@Transactional
public class PersonDaoImpl implements PersonDao{
    @Autowired
    private SessionFactory sessionFactory;
    public void setSessionFactory(SessionFactory sessionFactory){
        this.sessionFactory = sessionFactory;
    }
    public Person getPerson(String id) {
        String hql = "from Person p where p.id=?";
        Query query = sessionFactory.getCurrentSession().createQuery(hql);
        query.setString(0, id);
        return (Person)query.uniqueResult();
    }

    public List<Person> getAllPerson() {
        String hql = "from Person";
        Query query = sessionFactory.getCurrentSession().createQuery(hql);
        return query.list();
    }

    public void addPerson(Person person) {
        sessionFactory.getCurrentSession().save(person);
    }

    public boolean delPerson(String id) {
        String hql = "delete Person p where p.id = ?";
        Query query = sessionFactory.getCurrentSession().createQuery(hql);
        query.setString(0, id);
        return (query.executeUpdate() > 0);
    }

    public boolean updatePerson(Person person) {
        String hql = "update Person p set p.name = ? where p.id = ?";
        Query query = sessionFactory.getCurrentSession().createQuery(hql);
        query.setString(0, person.getName());
        query.setString(1, String.valueOf(person.getId()));
        return (query.executeUpdate() > 0);
    }
}

Person.java

package com.sshProject.entity;

import javax.persistence.*;

@Entity
@Table(name="person")
public class Person {
    @Id
    @GeneratedValue
    @Column(name="id")
    private int id;

    @Column(name="name")
    private String name;

    @Column(name="email")
    private String email;

    @Column(name="status")
    private int status;

  //setter getter
}

PersonService.java

package com.sshProject.service;

import com.sshProject.entity.Person;

import java.util.List;


public interface PersonService { Person getPerson(String id); List<Person> getAllPerson(); void addPerson(Person person); boolean delPerson(String id); boolean updatePerson(Person person); }

PersonServiceImpl.java

package com.sshProject.service.impl;

import com.sshProject.dao.PersonDao;
import com.sshProject.entity.Person;
import com.sshProject.service.PersonService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
@Service public class PersonServiceImpl implements PersonService{ @Autowired private PersonDao personDao; public Person getPerson(String id) { return personDao.getPerson(id); } public List<Person> getAllPerson() { List<Person> list = personDao.getAllPerson(); return list; } public void addPerson(Person person) { personDao.addPerson(person); } public boolean delPerson(String id) { return personDao.delPerson(id); } public boolean updatePerson(Person person) { return personDao.updatePerson(person); } }

addPerson.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Insert title here</title>
    <script type="text/javascript">
        function addUser(){
            var form = document.forms[0];
            form.action = "/addPerson";
            form.method="post";
            form.submit();
        }
    </script>
</head>
<body>
<h1>添加用户</h1>
<form action="" name="userForm">
    姓名:<input type="text" name="name">
    邮箱:<input type="text" name="email">
    状态:<input type="text" name="status">
    <input type="button" value="添加" onclick="addUser()">
</form>
</body>
</html>

editPerson.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <script type="text/javascript" src="../js/jquery-1.4.4.min.js"></script>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Insert title here</title>
</head>
<body>
<h1>编辑用户</h1>
<form action="/updatePerson" name="userForm" method="post">
    <input type="hidden" name="id" value="${person.id}">
    姓名:<input type="text" name="name" value="${person.name}">
    <input type="submit" value="编辑" >
</form>
</body>
</html>

index.xml

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

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <script type="text/javascript" src="../js/jquery-1.4.4.min.js"></script>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Insert title here</title>
    <script type="text/javascript">
        function del(id){
            $.get("/delPerson?id=" + id,function(data){
                if("success" == data.result){
                    alert("删除成功");
                    window.location.reload();
                }else{
                    alert("删除失败");
                }
            });
        }
    </script>
</head>
<body>
<h3><a href="/toAddPerson">添加用户</a></h3>
<table border="1">
    <tbody>
    <tr>
        <th>姓名</th>
        <th>邮箱</th>
        <th>状态</th>
        <th>操作</th>
    </tr>
    <c:if test="${!empty personList}">
        <c:forEach items="${personList}" var="person">
            <tr>
                <td>${person.name }</td>
                <td>${person.email }</td>
                <td>${person.status }</td>
                <td>
                    <a href="/getPerson?id=${person.id }">编辑</a>
                    <a href="javascript:del('${person.id}')">删除</a>
                </td>
            </tr>
        </c:forEach>
    </c:if>
    </tbody>
</table>
</body>
</html>

welcome.jsp

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

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Insert title here</title>
</head>
<body>
<h3>
    <a href="/toAddPerson">添加用户</a>
</h3>
</body>
</html>

第三步:maven打包, 点击最右侧maven project, 先clean然后package, 这时候可以在项目目录里看到target目录

package后  

第四步: 配置tomcat, 点击又上角

tomcat的名字自定义,其他的默认就好

 点击deployment

选择maven打包后的target中的war文件

然后一路ok, 启动tomcat, 结果如下:

点击添加

添加成功

编辑和删除也是正确的, 不在演示,参考文章找不到了, 有见过类似的可以附上链接, 谢谢

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:spring cloud demo解释

下一篇:用枚举来进行菜单和角色的绑定