基於IDEA 最新Spirng3.2+hibernate4+struts2.3 全註解配置 登...

若是你以爲本教程或者項目源碼對你有用,請支持下,或者點擊網頁下方打賞按鈕,謝謝html

    首先說說 IDEA 12,因爲myeclipse愈來愈卡,我改用idea12 了,發現其功能強悍到eclipse沒法比擬,此款ide理解上下文是一等一的,不用什麼jquery插件,extjs插件,均可以實現全智能的代碼提示。速度什麼的都比myeclipse快。並且IDEA提供了android支持struts spring hibernate 支持。下面,我講教你們完成一個基於全註解的Spirng3.2+hibernate4+struts2.3 登陸項目,本人對Java極其熱愛,愛好Java編程的朋友能夠加QQ羣:185441009java

第一步 建立工程:mysql

圖中的project name 就是eclipse裏的workspace,下面有個額module name,這個module 纔是真正的項目,若是你不更名字,它會自動建立一個跟project name同樣的工程。jquery

點 nextandroid

選擇相應的框架,包括application server tomcat,這裏要說明的是,選擇的時候它會提示是否下載所依賴的jarweb

 

記住要選中上圖中Level爲爲global 意思就是這個lib是Userlibary,同理,spring hibernate 亦是如此。spring

完了以後 finish,項目就建立完畢了。sql

第二步,配置lib數據庫

ide下載的jar並非完美的,有些衝突,有些少包多包。項目上右鍵,選擇打開project Structure 選擇global library,這裏能夠配置lib。apache

通過修整,最終導入的包以下。

 

第三步 搭建ssh框架

web.xml 

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
    http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
         version="2.5">

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <filter>
        <filter-name>struts2</filter-name>
        <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
        <init-param>
            <param-name>struts.ui.theme</param-name>
            <param-value>simple</param-value>
        </init-param>
        <init-param>
            <param-name>struts.objectFactory</param-name>
            <param-value>spring</param-value>
        </init-param>
        <init-param>
            <param-name>struts.convention.action.packages</param-name> //這是註解加載action類的時候用的
            <param-value>com.blog.actions</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

</web-app>

 

第二步 配置數據源

點擊ide右邊的database

而後右擊 add 按照步驟一步一步添加數據源 完成以後如圖所示

 

以後選中IDE側面的 persistence 選中hibernate.cfg.xml 右擊

 

 

 

選擇 genernate mapping,按照步驟生成帶註解的pojo類。

建立相應的配置文件 和 java 類 工程結構如圖所示 struts無需配置。

 

 

 

hibernate 配置文件:

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD//EN"
        " http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <property name="connection.url">jdbc:mysql://localhost:3306/blog</property>
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="connection.username">root</property>
        <property name="connection.password">123456</property>
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="hibernate.c3p0.min_size">5</property>
        <property name="hibernate.c3p0.max_size">20</property>
        <property name="hibernate.c3p0.timeout">1800</property>
        <property name="hibernate.c3p0.max_statements">50</property>
        <mapping class="com.blog.entity.AppInitEntity"/>
        <mapping class="com.blog.entity.ArticleEntity"/>
        <mapping class="com.blog.entity.CommentEntity"/>
        <mapping class="com.blog.entity.UserEntity"/>
        <!-- DB schema will be updated if needed -->
        <!-- <property name="hbm2ddl.auto">update</property> -->
    </session-factory>
</hibernate-configuration>

 

spring 配置文件

<?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:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">


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

    <bean id="sessionFactory"
          class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="configLocation" value="classpath:hibernate.cfg.xml"></property>
    </bean>

</beans>

 

loginAction

package com.blog.actions;

import com.blog.dao.UserDao;
import com.blog.entity.UserEntity;
import com.blog.service.UserService;
import com.opensymphony.xwork2.ActionSupport;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;

import javax.annotation.Resource;

/**
 * Created with IntelliJ IDEA.
 * User: Juyan
 * Date: 12-12-15
 * Time: 下午12:31
 * To change this template use File | Settings | File Templates.
 */
@Controller
@Namespace("/")
@Action("login")
@Results({@Result(name = "success", location = "/welcome.jsp"), @Result(name = "error", location = "/index.jsp")})


public class LoginAction extends ActionSupport {

    public String getUserName() {
        return userName;
    }

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

    public String getPwd() {
        return pwd;
    }

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

    private String userName;
    private String pwd;

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    private String message;

    @Resource
    UserService userService;

    public void check() {

        Integer id = 1;
        UserEntity userEntity = userService.findById(id);
        System.out.println(userEntity.getUserName());

    }
}

 

UserDao

package com.blog.dao;

import com.blog.entity.UserEntity;

/**
 * Created with IntelliJ IDEA.
 * User: Juyan
 * Date: 12-12-15
 * Time: 下午8:46
 * To change this template use File | Settings | File Templates.
 */
public interface UserDao {

    public UserEntity findById(Object id);
}

 

UserDaoImpl

package com.blog.daoimpl;

import com.blog.dao.UserDao;
import com.blog.entity.UserEntity;
import org.hibernate.Session;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Repository;

import java.io.Serializable;
import java.util.logging.Logger;

/**
 * Created with IntelliJ IDEA.
 * User: Juyan
 * Date: 12-12-15
 * Time: 下午8:52
 * To change this template use File | Settings | File Templates.
 */
@Repository
public class UserDaoImpl extends SuperDao implements UserDao {

    static Logger logger = Logger.getLogger(UserDaoImpl.class.toString());


    @Override
    public UserEntity findById(Object id) {
        UserEntity userEntity = null;
        try {
            Session session=sessionFactory.openSession();
            userEntity = (UserEntity) session.load(UserEntity.class, (Serializable) id);
            logger.info("id:" + id);
        } catch (DataAccessException e) {
            logger.info(e.toString());
        }
        return userEntity;
    }

超類 SuperDao

package com.blog.daoimpl;

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

import javax.annotation.Resource;


/**
 * Created with IntelliJ IDEA.
 * User: Juyan
 * Date: 12-12-15
 * Time: 下午8:49
 * To change this template use File | Settings | File Templates.
 */
@Component
public class SuperDao {
    @Resource
    SessionFactory sessionFactory;

}

 

 UserEntity 實體類

package com.blog.entity;

import javax.persistence.Basic;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import java.sql.Timestamp;
import java.util.Collection;

/**
 * Created with IntelliJ IDEA.
 * User: Juyan
 * Date: 12-12-15
 * Time: 下午2:05
 * To change this template use File | Settings | File Templates.
 */
@javax.persistence.Table(name = "user", schema = "", catalog = "blog")
@Entity
public class UserEntity {
    private int userId;

    @javax.persistence.Column(name = "user_id", nullable = false, insertable = true, updatable = true, length = 10, precision = 0)
    @Id
    public int getUserId() {
        return userId;
    }

    public void setUserId(int userId) {
        this.userId = userId;
    }

    private String userName;

    @javax.persistence.Column(name = "user_name", nullable = false, insertable = true, updatable = true, length = 50, precision = 0)
    @Basic
    public String getUserName() {
        return userName;
    }

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

    private String pwd;

    @javax.persistence.Column(name = "pwd", nullable = false, insertable = true, updatable = true, length = 50, precision = 0)
    @Basic
    public String getPwd() {
        return pwd;
    }

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

    private String email;

    @javax.persistence.Column(name = "email", nullable = false, insertable = true, updatable = true, length = 50, precision = 0)
    @Basic
    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    private Timestamp regTime;

    @javax.persistence.Column(name = "reg_time", nullable = false, insertable = true, updatable = true, length = 19, precision = 0)
    @Basic
    public Timestamp getRegTime() {
        return regTime;
    }

    public void setRegTime(Timestamp regTime) {
        this.regTime = regTime;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        UserEntity that = (UserEntity) o;

        if (userId != that.userId) return false;
        if (email != null ? !email.equals(that.email) : that.email != null) return false;
        if (pwd != null ? !pwd.equals(that.pwd) : that.pwd != null) return false;
        if (regTime != null ? !regTime.equals(that.regTime) : that.regTime != null) return false;
        if (userName != null ? !userName.equals(that.userName) : that.userName != null) return false;

        return true;
    }

    @Override
    public int hashCode() {
        int result = userId;
        result = 31 * result + (userName != null ? userName.hashCode() : 0);
        result = 31 * result + (pwd != null ? pwd.hashCode() : 0);
        result = 31 * result + (email != null ? email.hashCode() : 0);
        result = 31 * result + (regTime != null ? regTime.hashCode() : 0);
        return result;
    }

    private Collection<ArticleEntity> articlesByUserId;

    @OneToMany(mappedBy = "userByUserId")
    public Collection<ArticleEntity> getArticlesByUserId() {
        return articlesByUserId;
    }

    public void setArticlesByUserId(Collection<ArticleEntity> articlesByUserId) {
        this.articlesByUserId = articlesByUserId;
    }
}

 UserService

package com.blog.service;

import com.blog.entity.UserEntity;

import java.security.PrivateKey;

/**
 * Created with IntelliJ IDEA.
 * User: Juyan
 * Date: 12-12-15
 * Time: 下午8:43
 * To change this template use File | Settings | File Templates.
 */
public interface UserService {


    public UserEntity findById(Object id);


}

 

UserServiceImpl

package com.blog.serviceimpl;

import com.blog.dao.UserDao;
import com.blog.daoimpl.UserDaoImpl;
import com.blog.entity.UserEntity;
import com.blog.service.UserService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * Created with IntelliJ IDEA.
 * User: Juyan
 * Date: 12-12-15
 * Time: 下午8:47
 * To change this template use File | Settings | File Templates.
 */
@Service
public class UserServiceImpl implements UserService {

    @Resource
    UserDao userDao;

    @Override
    public UserEntity findById(Object id) {
        return userDao.findById(id);
    }
}

index.jsp

<%@ taglib prefix="s" uri="/struts-tags" %>
<%--
  Created by IntelliJ IDEA.
  User: Juyan
  Date: 12-12-15
  Time: 下午12:14
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>Login</title>
  </head>
  <body>
              <s:form action="login" namespace="/"  method="POST">
                  用戶名:<s:textfield name="userName"  />
                  密碼:<s:password name="pwd"/>
                                  <s:submit name="登陸" method="check"/>
              </s:form>
              <s:property value="message"/>
  </body>
</html>

 

配置完畢後,點擊上面的tomcat毛旁邊的運行按鈕。說是登錄,其實我只查詢了對象。數據庫是mysql,本身建立吧。user表裏面有個id字段。道理是同樣的。

還有什麼問題加我QQ.

相關文章
相關標籤/搜索