`
x125521853
  • 浏览: 71354 次
  • 性别: Icon_minigender_1
  • 来自: 武汉
社区版块
存档分类
最新评论

登录和注册(struts2+hibernate+spring)

    博客分类:
  • Item
阅读更多

一:添加三框架jar包

 

二:model层(student.java)    

package com.wdpc.ss2h.model;

public class Student {
	private String id;
	private String userName;//创建姓名
	private String userPwd;//创建密码

	//无参构造
	public Student() {
		super();
	}

	//有参构造
	public Student(String userName, String userPwd) {
		super();
		this.userName = userName;
		this.userPwd = userPwd;
	}

	//get,set方法
	public String getId() {
		return id;
	}

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

	public String getUserName() {
		return userName;
	}

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

	public String getUserPwd() {
		return userPwd;
	}

	public void setUserPwd(String userPwd) {
		this.userPwd = userPwd;
	}
}

   //model层 student配置文件(Student.hbm.xml) 

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
	<class name="com.wdpc.ss2h.model.Student" table="student">
		<id name="id" type="java.lang.String" column="id">
			<generator class="uuid.hex"></generator>
		</id>
		<property name="userName" type="java.lang.String" column="userName" />
		<property name="userPwd" type="java.lang.String" column="userPwd" />
	</class>
</hibernate-mapping>

    此映射文件要放到model层下,和student类放在一起

   //dao层 (StudentDao.java) 

package com.wdpc.ss2h.dao;

import com.wdpc.ss2h.model.Student;

public interface StudentDao {
	//登录
	public Student findName(Student student) throws Exception;
	//注册
	public void createStudent(Student student) throws Exception;
}

     创建dao层接口

   //实现dao层(StudentDaoImpl.java)

package com.wdpc.ss2h.dao.impl;

import java.util.List;
import org.hibernate.Query;
import org.hibernate.SessionFactory;
import com.wdpc.ss2h.dao.StudentDao;
import com.wdpc.ss2h.model.Student;

public class StudentDaoImpl implements StudentDao {
	private SessionFactory sessionFactory;
	//注册
	public void createStudent(Student student) throws Exception {
		sessionFactory.getCurrentSession().save(student);
	}

	//登录
	public Student findName(Student student) throws Exception {
		Query query = sessionFactory.getCurrentSession().createQuery(
		"from Student where userName=:name and userPwd=:password");
		query.setParameter("name",student.getUserName());
		query.setParameter("password",student.getUserPwd());
		List<Student> list = query.list();		
		if (list.size() > 0)
			return list.get(0);
		else
			return null;
	}

	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}	
}

    实现StudentDao.java接口方法

  //service层(StudentService.java)

package com.wdpc.ss2h.service;

import com.wdpc.ss2h.model.Student;

public interface StudentService {
	//登录
	public Student findName(Student student) throws Exception;
	//注册
	public void createStudent(Student student) throws Exception;
}

  //实现service层(StudentServiceImpl.java)

package com.wdpc.ss2h.service.impl;

import com.wdpc.ss2h.dao.StudentDao;
import com.wdpc.ss2h.model.Student;
import com.wdpc.ss2h.service.StudentService;

public class StudentServiceImpl implements StudentService {
	private StudentDao studentDao;
	
	public void createStudent(Student student) throws Exception {
		studentDao.createStudent(student);
	}

	public Student findName(Student student) throws Exception {
		return studentDao.findName(student);
	}

	public void setStudentDao(StudentDao studentDao) {
		this.studentDao = studentDao;
	}	
}

  //BaseAction.java

package com.wdpc.ss2h.comms;

import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import org.apache.struts2.interceptor.SessionAware;
import com.opensymphony.xwork2.ActionSupport;

public abstract class BaseAction extends ActionSupport implements
		ServletResponseAware, ServletRequestAware, SessionAware {
	protected HttpServletResponse response;
	protected HttpServletRequest request;
	protected Map<String, Object> session;

	public void setServletResponse(HttpServletResponse response) {
		this.response = response;
	}

	public void setServletRequest(HttpServletRequest request) {
		this.request = request;
	}

	public void setSession(Map<String, Object> session) {
		this.session = session;
	}

	public HttpServletResponse getResponse() {
		return response;
	}

	public void setResponse(HttpServletResponse response) {
		this.response = response;
	}

	public HttpServletRequest getRequest() {
		return request;
	}

	public void setRequest(HttpServletRequest request) {
		this.request = request;
	}

	public Map getSession() {
		return session;
	}
}

  //action层 (StudentAction.java) 

package com.wdpc.ss2h.action;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import java.util.Random;
import javax.imageio.ImageIO;
import com.opensymphony.xwork2.ModelDriven;
import com.wdpc.ss2h.comms.BaseAction;
import com.wdpc.ss2h.model.Student;
import com.wdpc.ss2h.service.StudentService;

public class StudentAction extends BaseAction implements ModelDriven<Student>{
	private Student student;
	private InputStream imageStream;
	private Map<String, Object> session;
	private StudentService studentService;
	private String randCode;//验证码
	private String message;//显示错误信息
	
	public String index(){
		return "index";
	}

	// 验证码
	public String getCheckCodeImage(String str, int show,
			ByteArrayOutputStream output) {
		Random random = new Random();
		BufferedImage image = new BufferedImage(80, 30,
				BufferedImage.TYPE_3BYTE_BGR);
		Font font = new Font("Arial", Font.PLAIN, 24);
		int distance = 18;
		Graphics d = image.getGraphics();
		d.setColor(Color.WHITE);
		d.fillRect(0, 0, image.getWidth(), image.getHeight());
		d.setColor(new Color(random.nextInt(100) + 100,
				random.nextInt(100) + 100, random.nextInt(100) + 100));
		for (int i = 0; i < 10; i++) {
			d.drawLine(random.nextInt(image.getWidth()), random.nextInt(image
					.getHeight()), random.nextInt(image.getWidth()), random
					.nextInt(image.getHeight()));
		}
		d.setColor(Color.BLACK);
		d.setFont(font);
		String checkCode = "";
		char tmp;
		int x = -distance;
		for (int i = 0; i < show; i++) {
			tmp = str.charAt(random.nextInt(str.length() - 1));
			checkCode = checkCode + tmp;
			x = x + distance;
			d.setColor(new Color(random.nextInt(100) + 50,
					random.nextInt(100) + 50, random.nextInt(100) + 50));
			d.drawString(tmp + "", x, random.nextInt(image.getHeight()
					- (font.getSize()))
					+ (font.getSize()));
		}
		d.dispose();
		try {
			ImageIO.write(image, "jpg", output);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return checkCode;
	}

	public String execute() throws Exception {
		ByteArrayOutputStream output = new ByteArrayOutputStream();
		String checkCode = getCheckCodeImage(
				"ABCDEFGHJKLMNPQRSTUVWXYZ123456789", 4, output);
		this.session.put("CheckCode", checkCode);
		// 这里将output stream转化为 inputstream
		this.imageStream = new ByteArrayInputStream(output.toByteArray());
		output.close();
		return SUCCESS;
	}
	
	//登录
	public String login(){
		String CheckCode = (String)request.getSession().getAttribute("CheckCode");
		if(!(CheckCode.equalsIgnoreCase(randCode))){
			message ="验证码输入有误!";
			return "index";					
		}
		try {
			studentService.findName(student);
			return "login";			
		} catch (Exception e) {
			e.printStackTrace();
			return "index";
		}		
	}
	
	public String register(){
		return "register";
	}
	
	//注册
	public String createStudent(){
		try{
			studentService.createStudent(student);
			return "success";
		} catch (Exception e) {
			e.printStackTrace();
			return "index";
		}
	}
	
	public Student getStudent() {
		return student;
	}

	public void setStudent(Student student) {
		this.student = student;
	}

	public InputStream getImageStream() {
		return imageStream;
	}

	public void setImageStream(InputStream imageStream) {
		this.imageStream = imageStream;
	}

	public Map<String, Object> getSession() {
		return session;
	}

	public void setSession(Map<String, Object> session) {
		this.session = session;
	}	
	
	public Student getModel() {
		student = new Student();
		return student;
	}

	public StudentService getStudentService() {
		return studentService;
	}

	public void setStudentService(StudentService studentService) {
		this.studentService = studentService;
	}
	
	public String getRandCode() {
		return randCode;
	}

	public void setRandCode(String randCode) {
		this.randCode = randCode;
	}

	public String getMessage() {
		return message;
	}

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

  //StudentAction-createStudent-validation.xml配置注册验证 

<!DOCTYPE validators PUBLIC
        "-//OpenSymphony Group//XWork Validator 1.0.2//EN"
        "http://www.opensymphony.com/xwork/xwork-validator-1.0.3.dtd">
<validators>
	<field name="userName">
		<field-validator type="requiredstring">
			<message>用户名必须填写</message>
		</field-validator>
		<field-validator type="stringlength">
			<param name="minLength">6</param>
			<param name="maxLength">12</param>
			<message>用户名必须在${minLength}~${maxLength}位之间</message>
		</field-validator>
	</field>
	<field name="userPwd">
		<field-validator type="requiredstring">
			<param name="trim">true</param>
			<message>密码必须填写</message>
		</field-validator>
		<field-validator type="stringlength">
			<param name="minLength">6</param>
			<param name="maxLength">20</param>
			<message>密码必须在${minLength}~${maxLength}位之间</message>
		</field-validator>		
	</field>
</validators>

     此文件放到action层,和StudentAction.java放在一起

    //StudentAction-login-validation.xml配置登录验证   

<!DOCTYPE validators PUBLIC
        "-//OpenSymphony Group//XWork Validator 1.0.2//EN"
        "http://www.opensymphony.com/xwork/xwork-validator-1.0.3.dtd">
<validators>
	<field name="userName">
		<field-validator type="requiredstring">
			<message>用户名必须填写</message>
		</field-validator>
		<field-validator type="stringlength">
			<param name="minLength">6</param>
			<param name="maxLength">12</param>
			<message>用户名必须在${minLength}~${maxLength}位之间</message>
		</field-validator>
	</field>
	<field name="userPwd">
		<field-validator type="requiredstring">
			<message>请正确填写密码</message>
		</field-validator>
		<field-validator type="stringlength">
			<param name="minLength">6</param>
			<param name="maxLength">20</param>
			<message>密码必须在${minLength}~${maxLength}位之间</message>
		</field-validator>		
	</field>
</validators>

     此文件放到action层,和StudentAction.java放在一起

  

   //配置hibernate.cfg.xml  

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
	<session-factory>
		<!-- 设置使用数据库的语言 -->
		<property name="dialect">org.hibernate.dialect.MySQL5Dialect</property>
		<property name="Hibernate.current_session_context_class">thread</property>
		<!-- 设置是否显示执行的语言 -->
		<property name="show_sql">true</property>
		<!--property name="hbm2ddl.auto">create</property-->
		<!-- 数据库连接属性设置 -->
		<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
		<property name="connection.url">jdbc:mysql://localhost:3306/test?useUnicode=true&amp;characterEncoding=utf-8</property>
		<property name="connection.username">root</property>
		<property name="connection.password">wdpc</property>
		<!-- 设置 c3p0连接池的属性-->
		<property name="connection.useUnicode">true</property>
		<property name="hibernate.c3p0.max_statements">100</property>
		<property name="hibernate.c3p0.idle_test_period">3000</property>
		<property name="hibernate.c3p0.acquire_increment">2</property>
		<property name="hibernate.c3p0.timeout">5000</property>
		<property name="hibernate.connection.provider_class">
			org.hibernate.connection.C3P0ConnectionProvider
		</property>
		<property name="hibernate.c3p0.validate">true</property>
		<property name="hibernate.c3p0.max_size">3</property>
		<property name="hibernate.c3p0.min_size">1</property>
		<!-- 加载映射文件-->
		<mapping resource="com/wdpc/ss2h/model/Student.hbm.xml" />
	</session-factory>
</hibernate-configuration>

     此配置文件放在src目录下

 

   //配置struts.xml文件   

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

<struts>
	<!-- 设置一些全局的常量开关 -->
	<constant name="struts.i18n.encoding" value="UTF-8" />
	<constant name="struts.action.extension" value="do,action" />
	<constant name="struts.serve.static.browserCache " value="false" />
	<constant name="struts.configuration.xml.reload" value="true" />
	<constant name="struts.devMode" value="true" />
	<constant name="struts.enable.DynamicMethodInvocation" value="false" />
	
	<package name="ss2h" extends="struts-default">
		<action name="index" class="StudentAction" method="index">
			<result name="index">/WEB-INF/page/login.jsp</result>
		</action>
		<action name="checkCode" class="StudentAction" method="execute">
			<result name="success" type="stream">
				<param name="contentType">image/jpeg</param>
				<param name="contentCharSet">UTF-8</param>
				<param name="inputName">imageStream</param>
			</result>
		</action>
		<action name="login" class="StudentAction" method="login">
			<result name="login">/WEB-INF/page/success.jsp</result>
			<result name="index">/WEB-INF/page/login.jsp</result>
			<result name="input">/WEB-INF/page/login.jsp</result>
		</action>
		<action name="register" class="StudentAction" method="register">
			<result name="register">/WEB-INF/page/register.jsp</result>
		</action>
		<action name="createStudent" class="StudentAction" method="createStudent">
			<result name="success">/WEB-INF/page/success.jsp</result>
			<result name="index">/WEB-INF/page/register.jsp</result>
			<result name="input">/WEB-INF/page/register.jsp</result>
		</action>
	</package>
</struts>

     此配置文件放在src目录下

 

   //配置spring(applicationContext.xml)文件  

<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/beans 
           http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context-2.5.xsd           
           http://www.springframework.org/schema/aop
           http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
           http://www.springframework.org/schema/tx
           http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
    <context:annotation-config />
	<context:component-scan base-package="com.wdpc.ss2h" />
	<aop:aspectj-autoproxy />
	<bean id="sessionFactory"
		class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
		<property name="configLocation" value="classpath:hibernate.cfg.xml">
		</property>
	</bean>
	<bean id="studentDao" class="com.wdpc.ss2h.dao.impl.StudentDaoImpl">
		<property name="sessionFactory" ref="sessionFactory" />
	</bean>
	<bean id="studentService" class="com.wdpc.ss2h.service.impl.StudentServiceImpl">
		<property name="studentDao" ref="studentDao" />
	</bean>
		<bean id="StudentAction" class="com.wdpc.ss2h.action.StudentAction" scope="prototype">
		<property name="studentService" ref="studentService" />
	</bean>
	<bean id="txManager"
		class="org.springframework.orm.hibernate3.HibernateTransactionManager">
		<property name="sessionFactory" ref="sessionFactory" />
	</bean>
	<tx:annotation-driven transaction-manager="txManager" />
	<tx:advice id="txAdvice" transaction-manager="txManager">
		<tx:attributes>
			<tx:method name="find*" read-only="true"/>
			<tx:method name="*" rollback-for="Exception" />
		</tx:attributes>
	</tx:advice>
	<aop:config>
		<aop:pointcut id="txPointcut"
			expression="execution(* com.wdpc.ss2h.service..*.*(..))" />
		<aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut" />
	</aop:config>
</beans>

    此配置文件放在src目录下

 

   //配置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">
	<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>
	</filter>
	<filter-mapping>
		<filter-name>struts2</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

   

   //index.jap页面  

<%@ page language="java" pageEncoding="utf-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<c:redirect url="/index.do"/>

 

   //login.jsp页面  

<%@ page language="java" pageEncoding="utf-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<c:set var="basePath" value="${pageContext.request.contextPath}" />
<%@ taglib uri="/struts-tags" prefix="s"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
  	<script type="text/javascript">
		function change(obj){
			obj.src="${basePath}/checkCode.do?time=" + new Date().getTime();
		}
    </script>
  </head>
  <body>
  	<div>
  	<form action="${basePath}/login.do" method="post">
  		<div style="color: red;">
  			<s:fielderror />
  			${message}
  		</div>
  		<div>
  			<label>用户名:</label>
  			<label><input type="text" name="userName" /></label><br />
  			<label>密&nbsp;&nbsp;&nbsp;&nbsp;碼:</label>
  			<label><input type="password" name="userPwd" /></label><br />
  			<label>验证碼:</label>			
  			<label><input type="text" name="randCode" /></label><br />
  			<label>&nbsp;&nbsp;&nbsp;&nbsp;<img src="${basePath}/checkCode.do" width="100px"	height="25px" alt="看不清,换一张" style="cursor: pointer;" onclick="change(this)" /></label>
  		</div>
  		<div>
  			<label><input type="submit" value="登錄" /></label>
  			<label><input type="button" value="註冊" onclick="window.location='${basePath}/register.do'"/></label>
  		</div>
  	</form>
  	</div>
  </body>
</html>

 

   //register.jsp页面   

<%@ page language="java" pageEncoding="utf-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<c:set var="bathPath" value="${pageContext.request.contextPath}"/>
<%@ taglib uri="/struts-tags" prefix="s"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
  </head>
  <body>
  	<div>
  	<form action="${bathPath}/createStudent.do" method="post">
  		<div style="color: red;"><s:fielderror /></div>
  		<div>
  			<label>用&nbsp;户&nbsp;名:</label>
		 	<input type="text" name="userName"/>
		 	<label id="chage1"></label><br/>
		 	<label>*正确填写用户名,6-12位之间请用英文小写、下划线、数字。</label><br/>
		 	<label>用户密码:</label>
		 	<input type="password" name="userPwd" /><br/>
		 	<label>*正确填写密码,6-12位之间请用英文小写、下划线、数字。</label><br/>
		 	<label>确认密码:</label>
		 	<input type="password" name="pwd2"/><br/>
		 	<label>*两次密码要一致,请用英文小写、下划线、数字。</label><br/>
  		</div>
  		<div>
  			<label><input type="submit" value="註冊" /></label>
  			<label><input type="reset" value="取消" /></label>
  		</div>
  	</form>
  	</div>
  </body>
</html>

 

   //登录和注册成功页面success.jsp  

<%@ page language="java" pageEncoding="utf-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
  </head>
  <body>
  	登录成功!
  	注册成功!
  </body>
</html>

     此login.jsp,register.jsp,success.jsp放到/WEB-INF/page目录下:    

 

  • 大小: 11.2 KB
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics