Eclipse搭建SSH入门项目(spring+springmvc+Hibernate)

本人框架初学者,为了让自己加深下印象,根据这个大神的博客搭建一个ssh框架的HelloWorld工程,参考的博客链接如下https://blog.csdn.net/tiandixuanwuliang/article/details/79403783


首先版本很重要,前期因为版本不对应消耗了很长时间,大家要注意选择配对的版本。我使用的版本是:

Eclipse:4.7.3a           JDK:8.0.144          Tomcat:9.0          JDBC:8.0.11

mysql:8.0                     maven:3.3.9           Hibernate:4.3.9final      spring:4.3.9

一、创建Maven工程并使其变为动态

1.给Eclipse配置好Maven环境后,新建一个Maven Project。

2.点击下一步后填写相应信息,然后点击完成

3.使之变为动态项目

(1)在项目上单击右键 
这里写图片描述 
(2) 
这里写图片描述 
(3) 
这里写图片描述
(4)勾选创建web.xml后,点击完成 
这里写图片描述 
(5)点击ok 
这里写图片描述

4.此时项目结构如图

二、配置依赖

1.在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.lzl</groupId>
  <artifactId>testSSH2</artifactId>
  <version>0.0.1-SNAPSHOT</version>
   <packaging>jar</packaging>
   
       <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <spring.version>4.3.9.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>4.3.9.Final</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>4.3.9.Final</version>
        </dependency>
        <!-- hibernate 配置 end -->

        <!-- mysql数据库的驱动包 start -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.11</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>

2.添加依赖。

(1)项目右键—->properties—–>Deployment Assembly,点击“Add” 
这里写图片描述 
(2)选择java build path entries—>next 
这里写图片描述 
(3) 
这里写图片描述

(4)然后会自动下载,下载需要稍等一段时间,自动下载的依赖插件将放置到指定的Maven仓库当中。

三、编写相关XML文件Java文件和jsp文件。

1.XML文件

(1)在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-4.3.xsd
                        http://www.springframework.org/schema/context 
    http://www.springframework.org/schema/context/spring-context-4.3.xsd
                        http://www.springframework.org/schema/mvc 
    http://www.springframework.org/schema/mvc/spring-mvc-4.3.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>  

(2)在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-4.3.xsd
                        http://www.springframework.org/schema/context 
                        http://www.springframework.org/schema/context/spring-context-4.3.xsd
                        http://www.springframework.org/schema/tx 
                        http://www.springframework.org/schema/tx/spring-tx-4.3.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.cj.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://localhost:3306/ssh?useSSL=false&amp;allowPublicKeyRetrieval=true&amp;serverTimezone=UTC" />
        <property name="username" value="root" />
        <property name="password" value="123456" />
    </bean>

    <!-- Hibernate SesssionFactory -->
    <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>
                <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.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>

    <tx:annotation-driven transaction-manager="transactionManager" />
</beans>

(3)修改WEB-INF文件夹下的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>testSSH2</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  
    <!-- 配置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>

(4)在在src/main/resources中新建一个名称为com.welljoint.entity的包,并在中创建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>

2.jsp文件

WEB-INF文件夹下新建view文件夹

(1)在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=ISO-8859-1">
<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>

(2)在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=ISO-8859-1">
<title>登陆成功</title>
</head>
<body>
   登陆成功了
</body>
</html>

3.java文件及接口

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

package com.welljoint.entity;

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 + "]";
    }
}

(2)在src/main/java中新建一个com.welljoint.rest的包;在这个包里新建一个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";
    }
}

(3)在src/main/java中新建一个com.welljoint.service的包;在这个包里新建一个LoginService.java和LoginServiceImpl.java

package com.welljoint.service;

public interface LoginService {
	public int login(String userName,String password);
}
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;
    }
}

(4)在src/main/java中新建一个com.welljoint.dao的包;在这个包里新建一个UserDao.java和UserDaompl.java

package com.welljoint.dao;
import com.welljoint.entity.User;
public interface UserDao {
	public User find(String userName,String password);
}
package com.welljoint.dao;

import java.util.List;

import javax.annotation.Resource;

import org.hibernate.SessionFactory;
import org.springframework.orm.hibernate4.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去数据库取
    }
}

四、运行

1.在数据库中自行新建一个ssh的数据库。

2.然后在eclipse右键项目,以服务器方式运行,运行成功后在ssh中可以看到新建了一个user表(此处容易出bug,可能要自行百度解决下)

3.在浏览器栏中输入http://localhost:8080/testSSH2/login

4.在数据库中给user表自行添加一下密码和账号即可,然后根据账号密码从浏览器中登陆会跳转到登陆成功页面。


这个是本人写的第一条博客,如有侵权联系立删。有什么不足之处,恳请请大家批评指正。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值