花了兩天時間,結合了網上大神們提供的信息,自己動手利用註解方式搭建了ssh框架,並實現了註冊登錄的簡單功能,下面給大家展示一下自己的學習成果,如有疑問的地方,還望各位留言指出,謝謝~
項目結構:
效果展示:
好啦,上面就是運行後項目的展示效果,界面醜就不要吐槽啦。。
下面來貼代碼。
1.web.xml配置
其實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>sshPro</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<!-- 項目名稱 -->
<display-name>sshPro</display-name>
<!--spring框架配置文件 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/config/applicationContext*.xml</param-value>
</context-param>
<!-- spring監聽 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- struts2配置 -->
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
<init-param>
<!-- 固定格式-->
<param-name>actionPackages</param-name>
<param-value>com.ssh</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- struts2配置結束 -->
<!-- openSessionFilter加載配置 -->
<filter>
<filter-name>openSessionFilter</filter-name>
<filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>openSessionFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- openSessionFilter加載配置結束 -->
</web-app>
2.spring配置
spring的配置文件名爲applicationContext.xml,這裏文件的名字是和上面web.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: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.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- 加載屬性文件 -->
<context:property-placeholder location="WEB-INF/config/sshDB.properties" />
<!-- 使用 annotation -->
<context:annotation-config />
<!-- 使用 annotation 自動註冊bean,並檢查@Controller, @Service, @Repository註解已被注入 -->
<context:component-scan base-package="com.ssh" />
<!-- 配置數據源 -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="${ssh.jdbc.driverClassName}"></property>
<property name="url" value="${ssh.jdbc.url}"></property>
<property name="username" value="${ssh.jdbc.username}"></property>
<property name="password" value="${ssh.jdbc.password}"></property>
</bean>
<!-- 配置sessionFactory -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource">
<ref bean="dataSource"/>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.OracleDialect</prop>
<!-- <prop key="hibernate.hbm2ddl.auto"></prop> -->
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
</props>
</property>
<!-- 包掃描的方式加載entity類 -->
<property name="packagesToScan" value="com.ssh.entity"></property>
</bean>
<!-- 事務管理器 -->
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<!-- 用註解來實現事務管理 -->
<tx:annotation-driven transaction-manager="transactionManager" />
</beans>
3.struts2文件配置
這個就不解釋了。。
<?xml version="1.0" encoding="UTF-8"?>
<struts>
<!-- 開啓使用開發模式,詳細錯誤提示 -->
<constant name="struts.devMode" value="false" />
<!-- 將對象交給spring管理 -->
<constant name="struts.objectFactory" value="spring" />
<!-- 指定資源編碼類型 -->
<constant name="struts.i18n.encoding" value="UTF-8" />
<!-- 指定每次請求到達,重新加載資源文件 -->
<constant name="struts.i18n.reload" value="false" />
<!-- 指定每次配置文件更改後,自動重新加載 -->
<constant name="struts.configuration.xml.reload" value="false" />
<!--
國際化資源文件
<constant name="struts.custom.i18n.resources" value="resources/content/Language" />
默認後綴名
<constant name="struts.action.extension" value="do,action,jhtml,," /> -->
</struts>
4.entity實體類
package com.ssh.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import org.hibernate.annotations.GenericGenerator;
@Entity
@Table(name = "BASE_USER")
public class User {
private String id; //用戶id
private String userName; //用戶名
private String password; //用戶密碼
@Id
@Column(name="USERID")
@GeneratedValue(generator="system-uuid")
@GenericGenerator(name = "system-uuid",strategy="uuid")
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
@Column(name = "USERNAME")
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
@Column(name = "PASSWORD")
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
5.dao層接口
package com.ssh.dao;
import com.ssh.entity.User;
public interface IUserDao {
//添加用戶
public void saveUser(User user);
//根據用戶名和密碼查詢用戶,判斷用戶是否可以登錄成功
public boolean getUserByNameAndPassword(User user);
//根據用戶名查詢用戶,判斷是否註冊成功
public boolean getUserByName(String userName);
}
dao接口實現類
package com.ssh.dao.impl;
import java.util.List;
import javax.annotation.Resource;
import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.ssh.dao.IUserDao;
import com.ssh.entity.User;
@Repository
public class UserDao implements IUserDao{
@Resource
@Autowired
private SessionFactory sessionFactory;
@Override
public void saveUser(User user){
sessionFactory.getCurrentSession().save(user);
}
@Override
public boolean getUserByNameAndPassword(User user){
String hql = "from User where userName=? and password = ?";
Query query = sessionFactory.getCurrentSession().createQuery(hql)
.setParameter(0, user.getUserName())
.setParameter(1, user.getPassword());
List list = (List) query.list();
if(list.size() > 0 ){
return true;
}
return false;
}
@Override
public boolean getUserByName(String userName){
String hql = "from User where userName=?";
Query query = sessionFactory.getCurrentSession().createQuery(hql)
.setParameter(0, userName);
List list = (List) query.list();
if(list.size() > 0 ){
return true;
}
return false;
}
}
6.service層接口
package com.ssh.service;
import com.ssh.entity.User;
public interface IUserService {
//添加用戶
public void saveUser(User user);
//根據用戶名和密碼查詢用戶,判斷用戶是否可以登錄成功
public boolean getUserByNameAndPassword(User user);
//根據用戶名查詢用戶,判斷是否註冊成功
public boolean getUserByName(String userName);
}
service層接口實現類
這裏一定注意的是,註解@Transactional一定要加上,否則將會報錯
package com.ssh.service.impl;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.ssh.dao.IUserDao;
import com.ssh.entity.User;
import com.ssh.service.IUserService;
@Service
@Transactional
public class UserService implements IUserService{
@Resource
private IUserDao iUserDao;
@Override
public void saveUser(User user){
iUserDao.saveUser(user);
}
@Override
public boolean getUserByNameAndPassword(User user){
return iUserDao.getUserByNameAndPassword(user);
}
@Override
public boolean getUserByName(String userName){
return iUserDao.getUserByName(userName);
}
}
7.action類
這是ssh框架的一個核心,前臺的請求都是跳轉到這裏來實現數據處理,同時,這裏也很容易出錯,看清楚extends繼承的是誰,大家務必細心喔
package com.ssh.action;
import javax.annotation.Resource;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import com.opensymphony.xwork2.ActionSupport;
import com.ssh.entity.User;
import com.ssh.service.IUserService;
/**
* 用戶控制器的實現,判斷登錄的用戶名以及密碼是否存在
* @author Administrator
*
*/
@Namespace("/user")
@Controller
public class UserAction extends ActionSupport {
private static final long serialVersionUID = -6608326471441433394L;
@Resource
private IUserService iUserService;
private User user;
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
/**
* 註冊新用戶
* @return
*/
@Action(value="regAction",results={
@Result(name="regSuccess",location="/regSucc.jsp"),
@Result(name="regFaile",location="/regFaile.jsp")
})
public String register(){
System.out.println("註冊id: "+user.getId() +" 註冊的用戶名: "+user.getUserName()+" 密碼: "+user.getPassword());
iUserService.saveUser(user);
Boolean check = iUserService.getUserByName(user.getUserName());
if(check){
System.out.println("reg seccess");
return "regSuccess";
}else{
System.out.println("reg faile");
return "regFaile";
}
}
/**
* 檢查用戶登錄
* @return
*/
@Action(value="loginAction",results={
@Result(name="LoginSuccess",location="/loginSucc.jsp"),
@Result(name="LoginFaile",location="/loginFaile.jsp")
})
public String login(){
Boolean check = iUserService.getUserByNameAndPassword(user);
if(check){
System.out.println("login seccess");
return "LoginSuccess";
}else{
System.out.println("login faile");
return "LoginFaile";
}
}
}
8.前臺頁面,這裏爲了簡便點,我就只貼出登錄頁面的代碼
<?xml version="1.0" encoding="UTF-8" ?>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<style type="text/css">
#iframe{
width: 250px;
vertical-align: middle;
}
p{
margin: 20px auto;
}
span{
font:15px normal inherit;
color:#333a3a;
float: left;
}
input{
float: right;
border: 1px solid #ccc;
}
.inputFloat {
float: none;
margin-top: 15px;
margin-left: 100px;
}
a{
float: none;
margin-top: 20px;
margin-left: 100px;
}
</style>
<title>登錄</title>
</head>
<body>
<div id="iframe">
<form method="post" action="user/loginAction">
<p id="pp"><span>用戶名:</span><input type="text" name="user.userName" /></p>
<p><span>密碼:</span><input type="text" name="user.password" /></p>
<p><input type="submit" value="登錄" class="inputFloat" /></p>
<a href="<%=path %>/reg.jsp" title="新用戶">新用戶</a>
</form>
</div>
</body>
</html>
最後是,給出源碼的下載鏈接:
http://download.csdn.net/detail/tianxiezuomaikong/9648841
另外推薦一篇不錯的文章,借鑑學習下:
http://www.oschina.net/code/snippet_147955_5079