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

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


1 创建maven项目

  • 请点击查看:http://blog.csdn.net/tiandixuanwuliang/article/details/79250504#t0

2 把maven项目变为动态网站

  • 请点击查看:http://blog.csdn.net/tiandixuanwuliang/article/details/79250504#t1

  • 项目图如下:
    使用maven搭建SSH项目(spring+springmvc+Hibernate)_第1张图片

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.0modelVersion>
    <groupId>com.welljointgroupId>
    <artifactId>testSSH2artifactId>
    <version>0.0.1-SNAPSHOTversion>
    <packaging>warpackaging>

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

    <dependencies>
        
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-coreartifactId>
            <version>${spring.version}version>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-contextartifactId>
            <version>${spring.version}version>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-webartifactId>
            <version>${spring.version}version>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-webmvcartifactId>
            <version>${spring.version}version>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-ormartifactId>
            <version>${spring.version}version>
        dependency>
        

        
        <dependency>
            <groupId>org.hibernategroupId>
            <artifactId>hibernate-coreartifactId>
            <version>3.6.9.Finalversion>
        dependency>
        <dependency>
            <groupId>org.hibernategroupId>
            <artifactId>hibernate-entitymanagerartifactId>
            <version>3.6.9.Finalversion>
        dependency>
        

        
        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
            <version>5.1.6version>
        dependency>

        
        <dependency>
            <groupId>javax.servlet.jsp.jstlgroupId>
            <artifactId>jstl-apiartifactId>
            <version>1.2version>
        dependency>

        
        <dependency>
            <groupId>javax.servletgroupId>
            <artifactId>javax.servlet-apiartifactId>
            <version>3.1.0version>
        dependency>

        
        <dependency>
            <groupId>commons-dbcpgroupId>
            <artifactId>commons-dbcpartifactId>
            <version>1.4version>
        dependency>
        <dependency>
            <groupId>commons-poolgroupId>
            <artifactId>commons-poolartifactId>
            <version>1.6version>
        dependency>
    dependencies>
project>

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

  • 请点击查看:http://blog.csdn.net/tiandixuanwuliang/article/details/79250504#t4

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"%>

<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"%>

<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的文件,代码如下:

  
<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">  

    
    <context:component-scan base-package="com.welljoint" />

      
    <mvc:annotation-driven />  

      
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">  
          
        <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,代码如下:


<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>testSSH2display-name>

    
    <servlet>
        <servlet-name>springmvcservlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
        <init-param>
            <param-name>contextConfigLocationparam-name>
            <param-value>classpath:spring-mvc.xmlparam-value>
        init-param>
    servlet>
    <servlet-mapping>
        <servlet-name>springmvcservlet-name>
        <url-pattern>/url-pattern>
    servlet-mapping>

    
    <filter>
        <filter-name>CharacterEncodingFilterfilter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
    filter>
    <filter-mapping>
        <filter-name>CharacterEncodingFilterfilter-name>
        <url-pattern>/*url-pattern>
    filter-mapping>

    
    <jsp-config>
        <jsp-property-group>
            <url-pattern>*.jspurl-pattern>
            <trim-directive-whitespaces>truetrim-directive-whitespaces>
        jsp-property-group>
    jsp-config>
web-app>
  • 如果你是按照上述一步步做的话,已经可以运行看效果了,效果图如下:
    使用maven搭建SSH项目(spring+springmvc+Hibernate)_第2张图片
  • 任意输入点击登陆后,如下图:
    这里写图片描述

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层写正确了,如下:
    使用maven搭建SSH项目(spring+springmvc+Hibernate)_第3张图片

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层写正确了,如下:
    使用maven搭建SSH项目(spring+springmvc+Hibernate)_第4张图片

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

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

  • (1)使用mysql,在本地创建一个名为ssh的数据库(不用建表,表会自动创建的)
    使用maven搭建SSH项目(spring+springmvc+Hibernate)_第5张图片

  • (2)在com.welljoint.entity包中创建User这个bean的映射文件User.hbm.xml


<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文件,代码如下:

<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">

    
    <context:component-scan base-package="com.welljoint" />

    
    <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&characterEncoding=UTF-8" />
        <property name="username" value="root" />
    bean>

    
    <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.MySQLDialectprop>
                <prop key="hibernate.format_sql">trueprop>
                <prop key="hibernate.hbm2ddl.auto">updateprop>
            props>
        property>
        <property name="mappingLocations" value="classpath:/com/welljoint/entity/*.hbm.xml" />
    bean>

    
    <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代码修改为如下(请关注本文件中新添加的两部分代码):

<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>testSSH2display-name>

    
    <context-param>
        <param-name>contextConfigLocationparam-name>
        <param-value>classpath:spring.xmlparam-value>
    context-param>

    
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
    listener>

    
    <servlet>
        <servlet-name>springmvcservlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
        <init-param>
            <param-name>contextConfigLocationparam-name>
            <param-value>classpath:spring-mvc.xmlparam-value>
        init-param>
    servlet>
    <servlet-mapping>
        <servlet-name>springmvcservlet-name>
        <url-pattern>/url-pattern>
    servlet-mapping>

    
    <filter>
        <filter-name>CharacterEncodingFilterfilter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
    filter>
    <filter-mapping>
        <filter-name>CharacterEncodingFilterfilter-name>
        <url-pattern>/*url-pattern>
    filter-mapping>

    
    <jsp-config>
        <jsp-property-group>
            <url-pattern>*.jspurl-pattern>
            <trim-directive-whitespaces>truetrim-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)最终项目截图如下:
    使用maven搭建SSH项目(spring+springmvc+Hibernate)_第6张图片
  • (7)恭喜您,整个SSH项目已经搭建完毕了,快来运行一下吧。启动项目后,首先检查eclipse的控制台有没有错误信息,有的话请百度。再看到浏览器会显示登陆框,如下:
    使用maven搭建SSH项目(spring+springmvc+Hibernate)_第7张图片
  • (8)此时ssh数据库已经自动创建了一个user表了,请看:
    使用maven搭建SSH项目(spring+springmvc+Hibernate)_第8张图片
  • (9)我们在上述的user表中,手动填入“11”,“22”,(后期大家自己写注册的代码,就不用手动填写了)如下图:
    使用maven搭建SSH项目(spring+springmvc+Hibernate)_第9张图片
  • (10)回到浏览器,我们可以使用刚刚填入到数据库的值进行登陆了
    使用maven搭建SSH项目(spring+springmvc+Hibernate)_第10张图片
    使用maven搭建SSH项目(spring+springmvc+Hibernate)_第11张图片
    • 我们填入错误的值(填入错误的值,仍会跳转到login.jsp页面)
      使用maven搭建SSH项目(spring+springmvc+Hibernate)_第12张图片
      使用maven搭建SSH项目(spring+springmvc+Hibernate)_第13张图片

4项目下载地址:

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

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

你可能感兴趣的:(WEB,最笨的办法学SSM框架)