到你了

该我上场表演啦!

导航

Maven搭建SSH框架

 

工具:Eclipse(Maven管理工具)+Tomcat+Mysql。

1.新建一个Maven工程(maven-archetype-webapp)。

 打开File ——>new——>Maven Project,直接next,选择(maven-archetype-webapp).接着输入Grouid和ArtifactId,点击finish等待生成项目即可。

 

 

 

2.修改pom.xml文件,我这里的依赖是网上找的。保存后会自动下载jar包在你的repository文件夹中(这里要保证连网)。

<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.gh</groupId>
  <artifactId>SSH1</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>SSH1 Maven Webapp</name>
  <url>http://maven.apache.org</url>
  
    <properties>
        <!-- 统一源码的编码方式 -->
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <!-- 统一各个框架版本 -->
        <struts.version>2.5.10</struts.version>
        <spring.version>4.3.8.RELEASE</spring.version>
        <hibernate.version>4.2.4.Final</hibernate.version>
    </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-core</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <!-- Spring web依赖 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <!-- Spring整合ORM框架依赖 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <!-- Struts2 核心依赖 -->
        <dependency>
            <groupId>org.apache.struts</groupId>
            <artifactId>struts2-core</artifactId>
            <version>${struts.version}</version>
        </dependency>
        <!-- Struts2和Spring整合依赖 -->
        <dependency>
            <groupId>org.apache.struts</groupId>
            <artifactId>struts2-spring-plugin</artifactId>
            <version>${struts.version}</version>
        </dependency>
        <!-- Hibernate 核心依赖 -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>${hibernate.version}</version>
        </dependency>
        <!-- MySQL 依赖 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.42</version>
        </dependency>
        <!-- C3P0 依赖 -->
        <dependency>
            <groupId>com.mchange</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.5</version>
        </dependency>
        <!-- AspectJ依赖 -->
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.8.10</version>
        </dependency>
        <!-- SLF4J依赖 -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.7.25</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>
    <dependency>
  <groupId>org.apache.taglibs</groupId>
  <artifactId>taglibs-standard-spec</artifactId>
  <version>1.2.5</version>
</dependency>
<dependency>
  <groupId>org.apache.taglibs</groupId>
  <artifactId>taglibs-standard-impl</artifactId>
  <version>1.2.5</version>
</dependency>
    
  </dependencies>
  <build>
    <finalName>SSH1</finalName>
      <!-- 统一源代码编译输出的JDK版本 -->
      <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.5.1</version>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                </configuration>
            </plugin>
            <!-- 打包时跳过单元测试 -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>2.19.1</version>
                <configuration>
                    <skipTests>true</skipTests>
                </configuration>
            </plugin>
            <!-- 集成Tomcat插件 -->
            <plugin>
                <groupId>org.apache.tomcat.maven</groupId>
                <artifactId>tomcat7-maven-plugin</artifactId>
                <version>2.2</version>
                <configuration>
                    <path>/${project.artifactId}</path>
                </configuration>
            </plugin>
        </plugins>
    
  </build>
</project>
View Code

3.修改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>
  <!-- 配置Struts2过滤器 -->
    <filter>
        <filter-name>struts2</filter-name>
        <filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
     
    <!-- 配置Spring的监听器 -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
     
    <!-- 指定Spring配置文件所在路径 -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param> 
  
</web-app>
View Code

4.添加struts.xml文件和applicationcontext.xml文件在src目录下。

  struts.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN"
    "http://struts.apache.org/dtds/struts-2.1.dtd"><!-- 注意版本 -->
    <struts>
    <constant name="struts.enable.DynamicMethodInvocation" value="true"/> 
    <package name="user"  namespace="/user" extends="struts-default">
            <action name="UserAction" class="action.UserAction" method="toLogin">
              <result name="success">/index2.jsp</result>
              <result name="error">/error.jsp</result>
               </action>
    </package>  
    </struts>
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:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:tx="http://www.springframework.org/schema/tx"  
    xsi:schemaLocation="
    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
    http://www.springframework.org/schema/aop   
    http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
    http://www.springframework.org/schema/context  
    http://www.springframework.org/schema/context/spring-context-3.1.xsd  
    http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans-3.1.xsd" default-autowire="byName">
    
    <context:annotation-config />
    <!-- spring 扫描路径,注意当前工程只需要扫描dao和service,srpingmvc或者struts2注解才有变化 -->
    <context:component-scan base-package="dao,service" />

    <bean id="dataSource"
        class="org.apache.commons.dbcp.BasicDataSource">
        <property name="driverClassName"
            value="com.mysql.jdbc.Driver">
        </property>
        <property name="url"
            value="jdbc:mysql://127.0.0.1:3306/young">
        </property>
        <property name="username" value="root"></property>
        <property name="password" value="root"></property>
    </bean>
    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource">
            <ref bean="dataSource" />
        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">
                    org.hibernate.dialect.MySQLDialect
                </prop>
                <prop key="hibernate.show_sql">
                    true
                </prop>
            </props>
        </property>
        <property name="mappingDirectoryLocations">
            <list>
                <value>classpath:entity/</value>
            </list>
        </property>
        </bean>
            <!-- 配置声明式事务管理(采用注解的方式) -->
    <bean id="txManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory"></property>
    </bean>
    <!-- 开启注解事务 -->
    <tx:annotation-driven transaction-manager="txManager"/>
</beans>
View Code

5.新建实体,动作类和接口等。结构如下图。

   UserAction.java

package action;
import java.util.List;

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

import com.opensymphony.xwork2.ActionSupport;


import entity.User;
import service.UserService;
@Controller
public class UserAction extends ActionSupport{
    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    @Autowired
    private UserService userService;//�Զ�ע��

    public String toLogin(){
        List<User>list=userService.findAll();
        for (User user : list) {
            System.out.println(user.getUserName());
        }
        return "success";
    }
    
}
View Code

  BaseDao.java

package common;

import java.util.List;

public interface BaseDao<T> {
    public List<T> findAll();
    public int insert(T t);
    public int update (T t,int id);
    public int delete(int id);
    public T findById(int id);
}
View Code

   BaseService.java

package common;

import java.util.List;

public interface BaseService <T>{
    public List<T> findAll();
    public boolean insert(T t);
    public boolean update (T t,int id);
    public boolean delete(int id);
    public T findById(int id);
}
View Code

  UserDao.java

package dao;

import common.BaseDao;
import entity.User;

public interface UserDao extends BaseDao<User>{

}
View Code

 UserDaoimpl.java

package dao.impl;

import java.util.List;

import org.hibernate.Query;
import org.springframework.orm.hibernate5.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;

import dao.UserDao;
import entity.User;
@Repository
public class UserDaoimpl extends HibernateDaoSupport   implements UserDao   {

    public List<User> findAll() {
        // TODO Auto-generated method stub
        String sql="select * from user";
        Query query=getSessionFactory().openSession().createSQLQuery(sql).addEntity(User.class);
        List<User> list=query.list();
        return list ;
    }

    public int insert(User t) {
        // TODO Auto-generated method stub
        return 0;
    }

    public int update(User t, int id) {
        // TODO Auto-generated method stub
        return 0;
    }

    public int delete(int id) {
        // TODO Auto-generated method stub
        return 0;
    }

    public User findById(int id) {
        // TODO Auto-generated method stub
        return null;
    }


    

}
View Code

UserService.java

package service;

import common.BaseDao;
import entity.User;

public interface UserService extends BaseDao<User>{

}
View Code

UserServiceimpl.java

package service.impl;

import java.util.List;

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

import dao.UserDao;
import entity.User;
import service.UserService;
@Transactional
@Service
public class UserServiceimpl implements UserService{
    @Autowired
    private UserDao userdao;

    public List<User> findAll() {
        // TODO Auto-generated method stub
        return userdao.findAll();
    }

    public int insert(User t) {
        // TODO Auto-generated method stub
        return 0;
    }

    public int update(User t, int id) {
        // TODO Auto-generated method stub
        return 0;
    }

    public int delete(int id) {
        // TODO Auto-generated method stub
        return 0;
    }

    public User findById(int id) {
        // TODO Auto-generated method stub
        return null;
    }


}
View Code

User.java

package entity;
// Generated 2018-3-29 10:41:32 by Hibernate Tools 3.4.0.CR1

/**
 * User generated by hbm2java
 */
public class User implements java.io.Serializable {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    private Integer userid;
    private String userName;
    private String pwd;

    public User() {
    }

    public User(String userName, String pwd) {
        this.userName = userName;
        this.pwd = pwd;
    }

    public Integer getUserid() {
        return this.userid;
    }

    public void setUserid(Integer userid) {
        this.userid = userid;
    }

    public String getUserName() {
        return this.userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getPwd() {
        return this.pwd;
    }

    public void setPwd(String pwd) {
        this.pwd = pwd;
    }

}
View Code

 

 

User.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated 2018-3-29 10:41:32 by Hibernate Tools 3.4.0.CR1 -->
<hibernate-mapping>
    <class name="entity.User" table="user" catalog="young">
        <id name="userid" type="java.lang.Integer">
            <column name="userid" />
            <generator class="identity" />
        </id>
        <property name="userName" type="string">
            <column name="userName" length="10" />
        </property>
        <property name="pwd" type="string">
            <column name="pwd" length="10" />
        </property>
    </class>
</hibernate-mapping>
View Code

 jsp代码

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<%@ taglib uri="http://java.sun.com/jstl/core_rt" prefix="c"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<c:set var="ctx" value="${pageContext.request.contextPath}"></c:set>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
</head>
<body>

     <form action="${ctx}/user/UserAction!toLogin.action"   method="post">
          用户名:<input type="text" name="username" id="username" value=""/>
          密码:<input type="password" name="user.password" id="password" value=""/>
          <input type="submit" value="登录">
      </form>


</body>
</html>
View Code

最后部署项目下tomcat中,运行console输出如下:

总结:在这过程中遇到了不少问题。一般都是包的问题和版本问题。

1.在搭建框架运行不报错后,准备去请求数据时,却一直找不到动作类。在跳转时jsp页面一直报如下错。

解决办法:参考博客:https://blog.csdn.net/axwolfer/article/details/40164151

在struts.xml中添加如下代码:

    <constant name="struts.enable.DynamicMethodInvocation" value="true"/>

 

 2.Hibernate版本问题,Hibernate升级后有了不少变化,具体网上看。之前一直用Hibernate3,在搭建开始时我用的是Hibernate5,后来改成了Hibernate4。

使用5时请求数据库时报如下错:

Could not open Hibernate Session for transaction; nested exception is java.lang.NoClassDefFoundError: org/hibernate/engine/transaction/spi/TransactionContext。

解决办法:将Hibernate中的依赖改成Hibernate4版本的即可。

 

posted on 2018-04-03 11:55  到你了  阅读(6645)  评论(0编辑  收藏  举报