ssh客戶管理系統項目--(一)

項目搭建:

這裏寫圖片描述
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/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.yan</groupId>
    <artifactId>ssh</artifactId>
    <packaging>war</packaging>
    <version>0.0.1-SNAPSHOT</version>
    <name>ssh Maven Webapp</name>
    <url>http://maven.apache.org</url>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <maven.compiler.encoding>UTF-8</maven.compiler.encoding>
        <spring.version>5.0.4.RELEASE</spring.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</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-orm</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.struts</groupId>
            <artifactId>struts2-spring-plugin</artifactId>
            <version>2.5.14.1</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>5.2.13.Final</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.8</version>
        </dependency>
        <!-- 在maven中使用本地包,具體開發中比較建議由管理員上傳到私服上供公司中的所有開發人員使用 1、將需要使用的jar包拷貝到/WEB-INF/lib/文件夾下 
            2、引入依賴,需要scope爲system,需要配置額外的systemPath設置 -->
        <dependency>
            <groupId>com.oracle</groupId>
            <artifactId>ojdbc6</artifactId>
            <version>6.0.0</version>
            <scope>system</scope>
            <systemPath>${project.basedir}/src/main/webapp/WEB-INF/lib/ojdbc6.jar</systemPath>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${spring.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>

    </dependencies>
    <build>
        <finalName>ssh</finalName>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

配置文件:
這裏寫圖片描述
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:context="http://www.springframework.org/schema/context"
    xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx"
    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-4.3.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">
    <!-- 配置連接池 -->
    <context:property-placeholder location="classpath:database.properties" />
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
        p:driverClassName="${jdbc.driver}" p:url="${jdbc.url}" p:username="${jdbc.username}"
        p:password="${jdbc.password}" />
    <!-- 配置sessionFactory -->
    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate5.LocalSessionFactoryBean"
        p:dataSource-ref="dataSource" p:packagesToScan="com.yan.entity">
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.format_sql">true</prop>
                <prop key="hibernate.hbm2ddl.auto">update</prop>
                <prop key="hibernate.current_session_context_class">org.springframework.orm.hibernate5.SpringSessionContext</prop>
            </props>
        </property>
    </bean>
    <tx:annotation-driven transaction-manager="transactionManager" />
    <bean id="transactionManager"
        class="org.springframework.orm.hibernate5.HibernateTransactionManager"
        p:sessionFactory-ref="sessionFactory" />
    <context:component-scan base-package="com.lq">
        <context:include-filter type="annotation"
            expression="org.springframework.stereotype.Controller" />
        <context:include-filter type="annotation"
            expression="org.springframework.stereotype.Repository" />
        <context:include-filter type="annotation"
            expression="org.springframework.stereotype.Service" />
    </context:component-scan>
</beans>

database.properties:

jdbc.driver=oracle.jdbc.OracleDriver
jdbc.url=jdbc:oracle:thin:@localhost:1521:oracl
jdbc.username=scott
jdbc.password=123456

struts.xml:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"
    "http://struts.apache.org/dtds/struts-2.5.dtd">
<struts>
    <package name="default" extends="struts-default"
        strict-method-invocation="false">
        <action name="user_*" class="userAction" method="{1}">
            <result name="input">/WEB-INF/content/user/{1}.jsp</result>
            <result name="login">/WEB-INF/content/user/login.jsp</result>
            <result name="list" type="redirectAction">
                <param name="actionName">list</param>
                <param name="namespace">/user</param>
            </result>
        </action>
    </package>
    <package name="user" extends="struts-default"
        strict-method-invocation="false" namespace="/user">
        <action name="*" class="adminUserAction" method="{1}">
            <result>/WEB-INF/content/user/{1}.jsp</result>
        </action>
    </package>
</struts>   

連接測試:

package com.lq.test;

import java.sql.SQLException;

import javax.annotation.Resource;
import javax.sql.DataSource;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext.xml")
public class Test1 {
    @Resource(name = "dataSource")
    private DataSource ds;

    @Test
    public void connTest() throws SQLException {
        System.out.println(ds.getConnection());
    }

}

這裏寫圖片描述

package com.lq.action;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.lq.entity.UserBean;
@Controller("adminUserAction")
@Scope("prototype")
public class AdminUserAction extends ActionSupport implements ModelDriven<UserBean> {
    private static final long serialVersionUID = 2599362356720145475L;
    private UserBean user = new UserBean();

    public String list() throws Exception {
        return SUCCESS;
    }

    public UserBean getModel() {
        return user;
    }
}
package com.lq.action;

import java.util.Map;

import javax.annotation.Resource;

import org.apache.struts2.interceptor.SessionAware;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.lq.biz.IUserServ;
import com.lq.entity.UserBean;

@Controller("userAction")
@Scope("prototype")
public class UserAction extends ActionSupport implements ModelDriven<UserBean>, SessionAware {
    private static final long serialVersionUID = 2599362356720145475L;
    private UserBean user = new UserBean();

    @Resource(name = "userService")
    private IUserServ userv;

    private Map<String, Object> sessionAttribute;

    public String tologin() {
        return LOGIN;
    }

    public String login() throws Exception {
        boolean bb = userv.login(user);
        if (bb) {
            sessionAttribute.put("user", user);
            return "list";
        } else {
            this.addActionError("鐧誨綍澶辮觸錛佽閲嶆柊鐧誨綍");
            return LOGIN;
        }
    }

    public UserBean getModel() {
        return user;
    }

    @Override
    public void setSession(Map<String, Object> arg0) {
        this.sessionAttribute = arg0;
    }
}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE validators PUBLIC
        "-//Apache Struts//XWork Validator 1.0.3//EN"
        "http://struts.apache.org/dtds/xwork-validator-1.0.3.dtd">
<validators>
    <field name="username">
        <field-validator type="requiredstring" short-circuit="true">
            <message>用戶名稱不能爲空!</message>
        </field-validator>
        <field-validator type="regex">
            <param name="regex">
                <![CDATA[^[a-zA-Z0-9_]{6,20}$]]>
            </param>
            <message>用戶名稱不合法!</message>
        </field-validator>
    </field>
    <field name="password">
        <field-validator type="requiredstring" short-circuit="true">
            <message>用戶口令不能爲空!</message>
        </field-validator>
        <field-validator type="stringlength">
            <param name="minLength">6</param>
            <param name="maxLength">20</param>
            <message>用戶口令只能是6到20個字符!</message>
        </field-validator>
    </field>
</validators>

這裏寫圖片描述

package com.lq.biz;

import com.lq.entity.UserBean;

public interface IUserServ {

    boolean login(UserBean user) throws Exception;

}
package com.lq.biz;

import java.util.List;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import com.lq.dao.IUserDao;
import com.lq.entity.UserBean;

@Service("userService")
@Transactional(readOnly = true, propagation = Propagation.SUPPORTS)
public class UserServImpl implements IUserServ {
    @Autowired
    private IUserDao userDao;

    @Override
    public boolean login(UserBean user) throws Exception {
        Assert.notNull(user, "參數錯誤!");
        Assert.hasText(user.getUsername(), "參數錯誤!");
        Assert.hasText(user.getPassword(), "參數錯誤!");
        List<UserBean> ulist = userDao.selectByExample(user);
        if (ulist != null && ulist.size() > 0) {
            UserBean temp = ulist.get(0);
            BeanUtils.copyProperties(temp, user);
            return true;
        }
        return false;
    }

}

這裏寫圖片描述

package com.lq.dao;

import java.util.List;

import com.lq.entity.UserBean;

public interface IUserDao {

    List<UserBean> selectByExample(UserBean user, int... pages);

}
package com.lq.dao;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Example;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.lq.entity.UserBean;

@Repository("userDao")
public class UserDaoImpl implements IUserDao {
    @Autowired
    private SessionFactory sessionFactory;

    @SuppressWarnings("unchecked")
    @Override
    public List<UserBean> selectByExample(UserBean user, int... pages) {
        @SuppressWarnings("deprecation")
        Criteria criteria = getSession().createCriteria(UserBean.class);
        if (user != null)
            criteria.add(Example.create(user).enableLike());
        if (pages != null && pages.length > 0)
            criteria.setFirstResult(pages[0]);
        if (pages != null && pages.length > 1)
            criteria.setMaxResults(pages[1]);
        return criteria.list();
    }

    protected Session getSession() {
        return sessionFactory.getCurrentSession();
    }
}

這裏寫圖片描述

package com.lq.entity;

import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.SequenceGenerator;

@Entity(name = "t_roles")
@SequenceGenerator(name = "seq1", sequenceName = "seq_roles", initialValue = 1, allocationSize = 1)
public class RoleBean implements Serializable {
    private static final long serialVersionUID = -7278613856522370880L;
    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "seq1")
    private Long id;
    @Column(length = 32, nullable = false)
    private String name;
    @OneToMany(mappedBy = "role", cascade = CascadeType.ALL)
    private Set<UserBean> users = new HashSet<>(0);

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Set<UserBean> getUsers() {
        return users;
    }

    public void setUsers(Set<UserBean> users) {
        this.users = users;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((id == null) ? 0 : id.hashCode());
        result = prime * result + ((name == null) ? 0 : name.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        RoleBean other = (RoleBean) obj;
        if (id == null) {
            if (other.id != null)
                return false;
        } else if (!id.equals(other.id))
            return false;
        if (name == null) {
            if (other.name != null)
                return false;
        } else if (!name.equals(other.name))
            return false;
        return true;
    }

}
package com.lq.entity;

import java.io.Serializable;
import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.SequenceGenerator;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

import org.hibernate.annotations.DynamicInsert;

@Entity(name = "t_users")
@DynamicInsert
@SequenceGenerator(name = "seq2", sequenceName = "seq_users", initialValue = 1, allocationSize = 1)
public class UserBean implements Serializable {
    private static final long serialVersionUID = -1356428520215870556L;
    @Id
    @GeneratedValue(strategy=GenerationType.SEQUENCE,generator="seq2")
    private Long id;
    @Column(length=20,nullable=false,unique=true)
    private String username;
    @Column(length=20,nullable=false)
    private String password;
    @Temporal(TemporalType.DATE)
    @Column(columnDefinition="date default sysdate")
    private Date birth;
    @Column(columnDefinition="number(1) default 1")
    private Boolean sex;
    @ManyToOne(optional=false)
    @JoinColumn(name="role_id")
    private RoleBean role = new RoleBean();
    public Long getId() {
        return id;
    }
    public void setId(Long 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;
    }
    public Date getBirth() {
        return birth;
    }
    public void setBirth(Date birth) {
        this.birth = birth;
    }
    public Boolean getSex() {
        return sex;
    }
    public void setSex(Boolean sex) {
        this.sex = sex;
    }
    public RoleBean getRole() {
        return role;
    }
    public void setRole(RoleBean role) {
        this.role = role;
    }
    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((id == null) ? 0 : id.hashCode());
        result = prime * result + ((username == null) ? 0 : username.hashCode());
        return result;
    }
    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        UserBean other = (UserBean) obj;
        if (id == null) {
            if (other.id != null)
                return false;
        } else if (!id.equals(other.id))
            return false;
        if (username == null) {
            if (other.username != null)
                return false;
        } else if (!username.equals(other.username))
            return false;
        return true;
    }

}

前臺頁面:
index.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="/struts-tags" prefix="s"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>My JSP 'my10.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<s:head/>
</head>

<body>
<a href="user_tologin.action">登錄系統</a>
</body>
</html>

show.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="/struts-tags" prefix="s"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>My JSP 'my10.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<s:head/>
</head>

<body>
this is show.jsp
</body>
</html>

list.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="/struts-tags" prefix="s"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>My JSP 'my10.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<s:head />
</head>

<body>this is List.jsp
</body>
</html>

login.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="/struts-tags" prefix="s"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>My JSP 'my10.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<script
    src="http://static.runoob.com/assets/jquery-validation-1.14.0/lib/jquery.js"></script>
<script
    src="http://static.runoob.com/assets/jquery-validation-1.14.0/dist/jquery.validate.min.js"></script>
<style type="text/css">
    .error{color:red;}
</style>    
<s:head />
<script type="text/javascript">
    $(function(){
        $('#user_login').validate({
            rules:{
                username:{required:true,rangelength:[6,20]},
                password:{required:true}
            },messages:{
                username:{required:'必須填寫!',rangelength:'用戶名稱應該在6到20個字符之間!'},
                password:{required:'必須填寫!'}
            }
        });
    });
</script>
</head>

<body>
    <s:actionerror />
    <s:form action="user_login.action">
        <s:textfield name="username" label="用戶名稱" />
        <s:password name="password" label="用戶口令" />
        <tr>
            <td colspan="2"><s:submit value="登錄系統" theme="simple" /> <s:reset
                    value="重置數據" theme="simple" /></td>
        </tr>
    </s:form>
</body>
</html>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章