使用maven搭建SSH项目(spring+springmvc+Hibernate)

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/tiandixuanwuliang/article/details/79403783

本文介绍使用eclipse+maven搭建Spring+SpringMvc+Hibernate项目,以登陆为例:
1、创建maven项目
2、把maven项目变为动态网站
3、搭建spring+springmvc+Hibernate项目


1 创建maven项目

2 把maven项目变为动态网站

3 开始搭建spring+springmvc+Hibernate项目

3.1 配置maven依赖,在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/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.welljoint</groupId>
    <artifactId>testSSH2</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <spring.version>4.2.6.RELEASE</spring.version>
    </properties>

    <dependencies>
        <!-- springframework 4 dependencies begin -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <!-- springframework 4 dependencies end -->

        <!-- hibernate 配置 begin -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>3.6.9.Final</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>3.6.9.Final</version>
        </dependency>
        <!-- hibernate 配置 end -->

        <!-- mysql数据库的驱动包 start -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.6</version>
        </dependency>

        <!-- 引入jstl包 -->
        <dependency>
            <groupId>javax.servlet.jsp.jstl</groupId>
            <artifactId>jstl-api</artifactId>
            <version>1.2</version>
        </dependency>

        <!-- 引入servlet -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
        </dependency>

        <!-- 引入数据库连接池 -->
        <dependency>
            <groupId>commons-dbcp</groupId>
            <artifactId>commons-dbcp</artifactId>
            <version>1.4</version>
        </dependency>
        <dependency>
            <groupId>commons-pool</groupId>
            <artifactId>commons-pool</artifactId>
            <version>1.6</version>
        </dependency>
    </dependencies>
</project>

3.2 请检查maven依赖是否导入到项目中了

3.3 在src/main/java中新建一个com.welljoint.entity的包;在这个包里新建一个User.java的bean

package com.welljoint.entity;
/** 
 * @version  
 * @time 2018-2-28 下午6:02:03 
 * @describe:用户的bean
 */
public class User {
    private Integer id;
    private String userName;
    private String password;

    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;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }

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

3.4 在WEB-INF目录下创建一个view文件夹;在该文件夹里创建一个login.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>登陆</title>
</head>
<body>
    <form method="post">
        用户名:<input type="text" name="userName"><br>
        密码:<input type="text" name="password"><br>
        <input type="submit" value="登陆">
    </form>
</body>
</html>
  • 再在view文件夹下创建一个login_success.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>登陆成功</title>
</head>
<body>
    登陆成功
</body>
</html>

3.5 在src/main/java中新建一个com.welljoint.rest的包;在这个包里新建一个LoginController.java作为控制器

package com.welljoint.rest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.welljoint.entity.User;

/** 
 * @version  
 * @time 2018-2-28 下午5:57:07 
 * @describe:控制器
 */
@Controller  //注解为控制器
@RequestMapping(value="/login")    //截获带有/login的请求
public class LoginController {

    @RequestMapping(method=RequestMethod.GET)
    public String get(){  //用来返回一个页面
        return "login";  //返回指向login.jsp页面
    }

    @RequestMapping(method=RequestMethod.POST)
    public String post(User user){  //用来处理用户的登陆请求
        return "login_success";
    }
}

3.6 在src/main/resources中新建一个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:p="http://www.springframework.org/schema/p"
    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-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">  

    <!-- 对web包中的所有类进行扫描,以完成Bean创建和自动依赖注入的功能 -->
    <context:component-scan base-package="com.welljoint" />

    <!-- 激活基于注解的配置 @RequestMapping, @ExceptionHandler,数据绑定 ,@NumberFormat ,  
    @DateTimeFormat ,@Controller ,@Valid ,@RequestBody ,@ResponseBody等  -->  
    <mvc:annotation-driven />  

    <!-- 视图层配置 -->  
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">  
        <!--配置JSTL表达式-->  
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>  
        <!-- 前缀 -->
        <property name="prefix" value="/WEB-INF/view/"/>  
        <!-- 后缀 -->
        <property name="suffix" value=".jsp"/>  
    </bean>  

    <!-- 配置静态资源 -->
    <mvc:resources location="/res/" mapping="/res/**"/>  
</beans>  

3.7 配置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>testSSH2</display-name>

    <!-- 请求都交给DispatcherServlet处理 -->
    <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:spring-mvc.xml</param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <!-- 增加中文乱码过滤器 -->
    <filter>
        <filter-name>CharacterEncodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>CharacterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <!-- 清除jsp空格 -->
    <jsp-config>
        <jsp-property-group>
            <url-pattern>*.jsp</url-pattern>
            <trim-directive-whitespaces>true</trim-directive-whitespaces>
        </jsp-property-group>
    </jsp-config>
</web-app>
  • 如果你是按照上述一步步做的话,已经可以运行看效果了,效果图如下:
    这里写图片描述
  • 任意输入点击登陆后,如下图:
    这里写图片描述

3.8 写service层:在src/main/java中新建一个com.welljoint.service的包;在这个包里新建一个LoginService.java作为服务层的接口

package com.welljoint.service;

public interface LoginService {
    public int login(String userName,String password);
}
  • 再在com.welljoint.service包中新建一个LoginServiceImpl.java作为服务层接口的实现
package com.welljoint.service;

import org.springframework.stereotype.Service;

@Service
public class LoginServiceImpl implements LoginService{
    public int login(String userName,String password){
        return 1;
    }
}
  • 此时就可以把service层注入到controller层来发挥作用了,把LoginController.java修改为如下:
package com.welljoint.rest;

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.welljoint.entity.User;
import com.welljoint.service.LoginService;

/** 
 * @version  
 * @time 2018-2-28 下午5:57:07 
 * @describe:控制器
 */
@Controller  //注解为控制器
@RequestMapping(value="/login")    //截获带有/login的请求
public class LoginController {

    @Autowired
    LoginService loginService;  //注入service层

    @RequestMapping(method=RequestMethod.GET)
    public String get(){  //用来返回一个页面
        return "login";  //返回指向login.jsp页面
    }

    @RequestMapping(method=RequestMethod.POST)
    public String post(User user){  //用来处理用户的登陆请求
        if (loginService.login(user.getUserName(), user.getPassword())==1) {
            return "login_success";  //登陆成功,跳转到login_success.jsp页面
        }
        return "login";
    }
}
  • 把项目运行起来,如果效果和之前的一样,输入任意值,点击登陆可以跳转,则证明service层写正确了,如下:
    这里写图片描述

3.9写dao层:在src/main/java中新建一个com.welljoint.dao的包;在这个包里新建一个UserDao.java作为数据层的接口

package com.welljoint.dao;

import com.welljoint.entity.User;

public interface UserDao {
    public User find(String userName,String password);
}
  • 再在com.welljoint.dao包中新建一个UserDaoImpl.java作为数据层接口的实现
package com.welljoint.dao;

import org.springframework.stereotype.Repository;

import com.welljoint.entity.User;

@Repository
public class UserDaompl implements UserDao{
    public User find(String userName,String password){
        return new User();//假数据,后期要通过Hibernate去数据库取
    }
}
  • 此时就可以把dao层注入到service层来发挥作用了,把LoginServiceImpl.java修改为如下:
package com.welljoint.service;

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

import com.welljoint.dao.UserDao;

@Service
public class LoginServiceImpl implements LoginService{

    @Autowired
    private UserDao userDao;

    public int login(String userName,String password){
        return userDao.find(userName, password)==null?0:1;
    }
}
  • 把项目运行起来,如果效果和之前的一样,输入任意值,点击登陆可以跳转,则证明dao层写正确了,如下:
    这里写图片描述

3.10 把Hibernate加入到项目中,并且去数据库查询数据

  • 对于这一节,是难点,<敲黑板>,3.9节前做的是前奏,都没有涉及到数据库操作,关于3.10节,大家可以用Hibernate也可以用Mybatis,这一章我们讲Hibernate,我的另一篇文章讲Mybatis,也欢迎大家看。

  • (1)使用mysql,在本地创建一个名为ssh的数据库(不用建表,表会自动创建的)
    这里写图片描述

  • (2)在com.welljoint.entity包中创建User这个bean的映射文件User.hbm.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
<hibernate-mapping package="com.welljoint.entity">
    <class name="User" table="user">
        <id name="id">
            <generator class="native"/>
        </id>
        <property name="userName" length="32" not-null="true" unique="true"/>
        <property name="password" length="64" not-null="true"/>
    </class>
</hibernate-mapping>
  • (3)在src/main/resources中创建spring.xml文件,代码如下:
<?xml version="1.0" encoding="UTF-8"?>
<beans default-autowire="byName"
    xmlns="http://www.springframework.org/schema/beans" 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"
    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.0.xsd
                        http://www.springframework.org/schema/context 
                        http://www.springframework.org/schema/context/spring-context-3.0.xsd
                        http://www.springframework.org/schema/tx 
                        http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">

    <!-- 对web包中的所有类进行扫描,以完成Bean创建和自动依赖注入的功能 -->
    <context:component-scan base-package="com.welljoint" />

    <!-- 数据源,BasicDataSource,commons-dbcp -->
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://localhost:3306/ssh?useUnicode=true&amp;characterEncoding=UTF-8" />
        <property name="username" value="root" />
    </bean>

    <!-- Hibernate SesssionFactory -->
    <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
                <prop key="hibernate.format_sql">true</prop>
                <prop key="hibernate.hbm2ddl.auto">update</prop>
            </props>
        </property>
        <property name="mappingLocations" value="classpath:/com/welljoint/entity/*.hbm.xml" />
    </bean>

    <!-- PlatTranscationManager -->
    <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>

    <tx:annotation-driven transaction-manager="transactionManager" />
</beans>
  • (4)把spring.xml配置文件,加入到web.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" 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>testSSH2</display-name>

    <!-- 配置spring容器 -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring.xml</param-value>
    </context-param>

    <!-- 配置监听器 -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <!-- 请求都交给DispatcherServlet处理 -->
    <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:spring-mvc.xml</param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <!-- 增加中文乱码过滤器 -->
    <filter>
        <filter-name>CharacterEncodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>CharacterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <!-- 清除jsp空格 -->
    <jsp-config>
        <jsp-property-group>
            <url-pattern>*.jsp</url-pattern>
            <trim-directive-whitespaces>true</trim-directive-whitespaces>
        </jsp-property-group>
    </jsp-config>
</web-app>
  • (5)把Hibernate功能添加到dao层中,从而进行数据库操作,UserDaoImpl.java代码修改为如下:
package com.welljoint.dao;

import java.util.List;

import javax.annotation.Resource;

import org.hibernate.SessionFactory;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;

import com.welljoint.entity.User;

@Repository
public class UserDaompl extends HibernateDaoSupport implements UserDao{
    //HibernateDaoSupport来操作数据库更加方便

    //用来注入sessionFactory(不注入会报错)
    @Resource(name = "sessionFactory")
    public void setSessionFactoryOverride(SessionFactory sessionFactory) {
        super.setSessionFactory(sessionFactory);
    }

    @Override
    public User find(String userName,String password){
        //注意:以下是HQL语句
        List<?> users = getHibernateTemplate().find("from User where userName=? and password=?",userName,password);
        return users.size()>0?(User)users.get(0):null;//假数据,后期要通过Hibernate去数据库取
    }
}
  • (6)最终项目截图如下:
    这里写图片描述
  • (7)恭喜您,整个SSH项目已经搭建完毕了,快来运行一下吧。启动项目后,首先检查eclipse的控制台有没有错误信息,有的话请百度。再看到浏览器会显示登陆框,如下:
    这里写图片描述
  • (8)此时ssh数据库已经自动创建了一个user表了,请看:
    这里写图片描述
  • (9)我们在上述的user表中,手动填入“11”,“22”,(后期大家自己写注册的代码,就不用手动填写了)如下图:
    这里写图片描述
  • (10)回到浏览器,我们可以使用刚刚填入到数据库的值进行登陆了
    这里写图片描述
    这里写图片描述
    • 我们填入错误的值(填入错误的值,仍会跳转到login.jsp页面)
      这里写图片描述
      这里写图片描述

4项目下载地址:

http://download.csdn.net/download/tiandixuanwuliang/10264025

本文原地址:http://mp.blog.csdn.net/mdeditor/79403783

展开阅读全文

没有更多推荐了,返回首页