struts2.0+hibernate3.0+spring3實現註冊登錄(hbm)


上面是項目結構,自己導入ssh的jar包加入如下代碼即可!

一、配置web.xml。

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
	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">
  <!-- 配置Spring核心監聽器 -->	
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>
    <!-- 爲struts2配置核心過濾器 -->
    <filter>
        <filter-name>struts2</filter-name>
        <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <!-- 歡迎頁 -->
    <welcome-file-list>
        <welcome-file>login.jsp</welcome-file>
    </welcome-file-list>
</web-app>
二、配置log4j.properties。

### direct log messages to stdout ###
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n

### direct messages to file mylog.log ###
log4j.appender.file=org.apache.log4j.FileAppender
log4j.appender.file.File=d:/mylog.log
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n

### set log levels - for more verbose logging change 'info' to 'debug' ###

log4j.rootLogger=info, stdout
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
	"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
	"http://struts.apache.org/dtds/struts-2.3.dtd">

<struts>
    <!-- 自動加載配置文件,報錯信息非常詳細 -->
    <constant name="struts.devMode" value="true" />
    
    <!-- 將對象工廠 設置爲Spring -->
    <constant name="struts.objectFactory" value="spring"></constant>
	
    <constant name="struts.custom.i18n.resources" value="cn.itcast.ssh.message"></constant>
	
    <package name="basic" namespace="/" extends="struts-default">
        <action name="user_*" class="xk.action.UserAction" method="{1}">
            <result>/jsps/main.jsp</result>
            <result name="input">/login.jsp</result>
        </action>
    </package>
</struts>

jdbc.driverClass= com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql:///sshexec
jdbc.user= root
jdbc.password=1234

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

	<context:property-placeholder location="classpath:jdbc.properties"/>
	<!-- c3p0數據源  -->
	<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
		<property name="driverClass" value="${jdbc.driverClass}"></property>
		<property name="jdbcUrl" value="${jdbc.url}"></property>
		<property name="user" value="${jdbc.user}"></property>
		<property name="password" value="${jdbc.password}"></property>
	</bean>
	
	<!-- sessionFactory 就是 HibernateAPI SessionFactory 對象 -->
	<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
		<!-- JDBC數據源 -->
		<property name="dataSource" ref="dataSource"></property>
		<!-- Hibernate常規屬性 -->
		<property name="hibernateProperties">
			<props>
				<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
				<prop key="hibernate.hbm2ddl.auto">update</prop>
				<prop key="hibernate.show_sql">true</prop>
				<prop key="hibernate.format_sql">true</prop>
				<prop key="hibernate.current_session_context_class">thread</prop>
			</props>
		</property>			
		<!-- 會自動掃描路徑下所有hbm文件  -->
		<property name="mappingDirectoryLocations">
			<list>
				<value>classpath:xk/domain</value>
			</list>
		</property>
	</bean>
	
	<!-- 配置事務管理器 -->
	<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
		<property name="sessionFactory" ref="sessionFactory"></property>
	</bean>
	
	<!-- 註解驅動事務管理 -->
	<tx:annotation-driven transaction-manager="transactionManager"/>
	
	<!-- 登陸流程 -->
	<bean id="userdao" class="xk.dao.UserDao">
		<property name="sessionFactory" ref="sessionFactory"></property>
	</bean>
	
	<!-- id 必須爲userService 按名次注入給Struts的Action -->
	<bean id="userService" class="xk.service.UserService">
		<property name="userdao" ref="userdao"></property>
	</bean>
	
</beans>

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package xk.domain;

/**
 *
 * @author john
 */
public class UserInfo {

    private Integer id;
    private String name;
    private String password;

    public Integer getId() {
        return id;
    }

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

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getName() {
        return name;
    }

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

    @Override
    public String toString() {
        return "UserInfo{" + "id=" + id + ", name=" + name + ", password=" + password + '}';
    }

}

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC 
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <class name="xk.domain.UserInfo" table="userinfo" catalog="sshexec">
        <id name="id">
            <generator class="native"></generator>
        </id>
        <property name="name" length="50"></property>
        <property name="password" length="50"></property>
    </class>
</hibernate-mapping>

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package xk.dao;

import java.util.List;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import xk.domain.UserInfo;
import xk.utils.MD5Utils;

/**
 *
 * @author john
 */
public class UserDao extends HibernateDaoSupport {

    //登錄方法
    public UserInfo login(UserInfo userinfo) {
        String hql = "from UserInfo where name = ? and  password = ?";
        //密碼進行MD5加密
        List<UserInfo> userinfos = this.getHibernateTemplate().find(hql, userinfo.getName(), MD5Utils.md5(userinfo.getPassword()));
        if (userinfos.size() > 0) {
            return userinfos.get(0);
        } else { 
            return null;
        }
    }

    public void add(UserInfo userinfo) {
        this.getHibernateTemplate().save(userinfo);
    }
    
}

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package xk.service;

import org.springframework.transaction.annotation.Transactional;
import xk.dao.UserDao;
import xk.domain.UserInfo;

/**
 *
 * @author john
 */
@Transactional
public class UserService {

    private UserDao userdao;

    public void setUserdao(UserDao userdao) {
        this.userdao = userdao;
    }

    public UserInfo login(UserInfo userinfo) {
        return userdao.login(userinfo);
    }

    public void add(UserInfo userinfo) {
        userdao.add(userinfo);
    }

}

package xk.utils;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class MD5Utils {

    /**
     * 使用md5的算法進行加密
     */
    public static String md5(String plainText) {
        byte[] secretBytes = null;
        try {
            secretBytes = MessageDigest.getInstance("md5").digest(plainText.getBytes());
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("沒有md5這個算法!");
        }
        String md5code = new BigInteger(1, secretBytes).toString(16);// 16進制數字
        // 如果生成數字未滿32位,需要前面補0
        for (int i = 0; i < 32 - md5code.length(); i++) {
            md5code = "0" + md5code;
        }
        return md5code;
    }

    public static void main(String[] args) {
        System.out.println(md5("123"));
    }

}

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package xk.action;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import javax.servlet.http.HttpSession;
import org.apache.struts2.ServletActionContext;
import xk.domain.UserInfo;
import xk.service.UserService;
import xk.utils.MD5Utils;

/**
 *
 * @author john
 */
public class UserAction extends ActionSupport implements ModelDriven<UserInfo> {

    private UserInfo userinfo = new UserInfo();
    private UserService userService = new UserService();

    @Override
    public UserInfo getModel() {
        return userinfo;
    }

    public String login() {
        System.err.println("----"+userinfo.toString());
        UserInfo existUser = userService.login(userinfo);
        if (existUser == null) {
            this.addActionError(this.getText("loginerror"));
            return INPUT;
        } else {
            //登錄成功,將用戶保存至session
            HttpSession session = ServletActionContext.getRequest().getSession();
            session.setAttribute("existUser", existUser);
            return SUCCESS;
        }
    }

    public String add() {
        userinfo.setPassword(MD5Utils.md5(userinfo.getPassword()));
        userService.add(userinfo);
        return SUCCESS;
    }

    public void setUserService(UserService userService) {
        this.userService = userService;
    }

}

<%-- 
    Document   : login
    Created on : 2014-4-14, 14:38:41
    Author     : john
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@taglib  uri="/struts-tags" prefix="s" %>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <s:form action="user_login" theme="simple">
            <s:textfield name="name" />
            <s:password name="password" />
            <s:submit value="登錄" />
        </s:form>
    </body>
</html>

<%-- 
    Document   : add
    Created on : 2014-4-14, 15:09:43
    Author     : john
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@taglib  uri="/struts-tags" prefix="s" %>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <s:form action="user_add" theme="simple">
            <s:textfield name="name" />
            <s:password name="password" />
            <s:submit value="註冊"/>
        </s:form>
    </body>
</html>

<%-- 
    Document   : main
    Created on : 2014-4-14, 15:08:33
    Author     : john
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <h1>操作成功!</h1>
    </body>
</html>
就可以了,相關類名,一看便知!


發佈了28 篇原創文章 · 獲贊 5 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章