struts2+spring实现简单用户登录注册

在前面demo的基础上再做一个涉及数据库访问,分层结构的简单用户登录注册例子,步骤如下:

1.新建user表,sql语句如下

DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
  `id` int(11) NOT NULL auto_increment,
  `name` char(128) NOT NULL,
  `credits` int(11) default '0',
  `password` varchar(32) NOT NULL,
  `last_visit` datetime default NULL,
  `last_ip` varchar(23) NOT NULL,
  PRIMARY KEY  (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

2.新建注册页面register.jsp,登录的页面还是前面的index.jsp,两者很相似

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'register.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">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->

  </head>
  
  <body>
  	<form action="Register" method="post">
  	
	<Table>
		<Tr>
			<td>用户名:</Td>
			<td><input type="text" name="username" /></Td>
		</Tr>
		<Tr>
			<td>密码:</Td>
			<td><input type="password" name="password" /></Td>
		</Tr>
		<Tr>
			<td><input type="submit" name="submit" value="注册"/></Td>
			<td><input type="reset" name="reset" value="重置"/></Td>
		</Tr>
	</Table> 
  	
  	
  	</form>  
  </body>
</html>

3.导入所需要的包mysql-connector-java(jdbc驱动),spring里的jdbc,transaction包,commoms-dbcp,commons-pool(两者配合使用完成数据库连接池),导入完成后要在spring配置文件中进行配置,配置文件在后面给出

4.由于用户注册需对密码进行md5加密,所以先给出md5加密的工具类Md5Encode.java,此文件为网上看到的,直接拿来用的

package com.struts2.util;

import java.security.MessageDigest;

public class Md5Encode {
	
	private final static String[] hexDigits={
		"0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"};
	

	public static String byteArrayToHexString(byte[] b){
		StringBuffer resultSb=new StringBuffer();
		for(int i=0;i<b.length;i++){
			resultSb.append(byteToHexString(b[i]));
		}
		return resultSb.toString();
	}
	
	private static String byteToHexString(byte b){
		int n=b;
		int d1=0;
		int d2=0;
		if(n<0){
			n=256+n;
			d1=n/16;
			d2=n%16;
		}
		return hexDigits[d1]+hexDigits[d2];
	}
	
	public static String MD5Encode(String origin){
		String resultString=null;
		try{
			resultString=new String(origin);
			MessageDigest md=MessageDigest.getInstance("MD5");
			resultString=byteArrayToHexString(md.digest(resultString.getBytes()));
		}catch(Exception e){
			
		}
		return resultString;
	}
}

5.在程序里添加dao,model与service(前面例子已经添加过)

    加好后,先在model package里加入实体类Usre.java

package com.struts2.model;

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

public class User implements Serializable{
	private int uid;
	private String username;
	private String password;
	private int credits;
	private String lastIp;
	private Date lastVisit;
	public int getUid() {
		return uid;
	}
	public void setUid(int uid) {
		this.uid = uid;
	}
	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 int getCredits() {
		return credits;
	}
	public void setCredits(int credits) {
		this.credits = credits;
	}
	public String getLastIp() {
		return lastIp;
	}
	public void setLastIp(String lastIp) {
		this.lastIp = lastIp;
	}
	public Date getLastVisit() {
		return lastVisit;
	}
	public void setLastVisit(Date lastVisit) {
		this.lastVisit = lastVisit;
	}
	
	
}

dao与Service里最好加上接口包,在这里,我只在dao里加了接口包,并在里面写了dao接口类IUserDao.java

package com.struts2.dao.impl;

import com.struts2.model.User;

public interface IUserDao  {
	public void addUser(User user);
	public void delUser(User user);
	public User findUserByName(String username);
	public void updateUser(User user);
	public boolean checkUser(String username,String password);
	public boolean register(User user);
}

下面是实现接口的UserDao.java

package com.struts2.dao;

import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import com.struts2.dao.impl.IUserDao;
import com.struts2.model.User;

public class UserDao implements IUserDao  {
	private JdbcTemplate jdbcTemplate;
	
	//注入
	
	public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
		this.jdbcTemplate = jdbcTemplate;
	}
	
	public void addUser(User user) {
		// TODO Auto-generated method stub
		
	}

	

	public void delUser(User user) {
		// TODO Auto-generated method stub
		
	}

	public User findUserByName(String username) {
		// TODO Auto-generated method stub
		return null;
	}

	public void updateUser(User user) {
		// TODO Auto-generated method stub
		
	}

	public boolean checkUser(String username, String password) {
		// TODO Auto-generated method stub
		System.out.println(password);
		String sql="select count(*) from user where name=? and password=? ";
		int count=jdbcTemplate.queryForInt(sql,new Object[]{username,password});
		return count>0;
	}

	public boolean register(User user)  {
		// TODO Auto-generated method stub
		System.out.println("beign dao");
		String sql="insert into  user (name,credits,password,last_visit,last_ip) values (?,?,?,?,?)";
		Object[] args={user.getUsername(),user.getCredits(),user.getPassword(),user.getLastVisit(),user.getLastIp()};
		try{
			jdbcTemplate.update(sql, args);
			
		}catch (DataAccessException e)
		{
			e.printStackTrace();
			return false;
		}
	
		return true;
		
	}
	
	
}

有些方法加上了,没实现,其中对数据库的操作是使用了spring里封装的jdbc

最后就是Service了,我把登录和注册写成了两个Service类,好的做法应该写成一个UserService类,里面写两个方法就可以了

既然写了两个文件,就都贴出来吧

LoginService.java

package com.struts2.service;

import com.struts2.dao.UserDao;
import com.struts2.model.User;

public class LoginService {
	private UserDao userdao;
	public boolean login(User user) throws Exception{
		boolean flag=false;
		if(userdao.checkUser(user.getUsername(), user.getPassword())){
			flag=true;
		}
		return flag;
	}
	public void setUserdao(UserDao userdao) {
		this.userdao = userdao;
	}
	
	
}

RegisterService.java

package com.struts2.service;

import com.struts2.dao.UserDao;
import com.struts2.model.User;

public class RegisterService {
	private UserDao userDao;
	public boolean Register(User user){
		System.out.println("begin Service");
		return userDao.register(user);
		
	}
	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}
	

}

6.在编写完分层后,添加ReigsterAction.java并修改前面的LoginAction.java

RegisterAction.java

package com.struts2.action;

import java.util.Date;
import java.util.Map;

import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.struts2.model.User;
import com.struts2.service.RegisterService;
import com.struts2.util.Md5Encode;

import org.apache.struts2.ServletActionContext;

public class RegisterAction extends ActionSupport implements Action{
	private String username;
	private String password;
	
	private RegisterService registerService;
	public String execute() throws Exception{
		System.out.println("begin action");
		
		
		User user=new User();
		user.setUsername(username);
		user.setPassword(Md5Encode.MD5Encode(password));
		user.setCredits(10);
		user.setLastVisit(new Date());
		user.setLastIp(ServletActionContext.getRequest().getRemoteAddr());
		if(this.registerService.Register(user)){
			return this.SUCCESS;
		} else{
			return this.ERROR;
		}
		
		
	}
	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 void setRegisterService(RegisterService registerService) {
		this.registerService = registerService;
	}
	
}

LoginAction.java

package com.struts2.action;

import java.util.Map;

import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.struts2.model.User;
import com.struts2.service.LoginService;
import com.struts2.util.Md5Encode;

public class LoginAction extends ActionSupport implements Action{
	private static final long serialVersionUID  =   1L ;
	private String username;
	private String password;
	
	private LoginService loginService;
	
	@Override
	public void validate()
	{
		
	}
	
	
	public String execute() throws Exception
	{	
		
		User user=new User();
		user.setUsername(username);
		user.setPassword(Md5Encode.MD5Encode(password));
		boolean result=this.loginService.login(user);
		if(result){
			return this.SUCCESS;
		}else{
			return this.ERROR ;
		}	
		
	}

	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 LoginService getLoginService() {
		return loginService;
	}

	public void setLoginService(LoginService loginService) {
		this.loginService = loginService;
	}
	
	
	
}

7.配置struts.xml,配置新的action

<?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>
   
   <constant name="struts.objectFactory" value="spring"></constant>
   
   
	<package name="strutsqs"  extends="struts-default">
		<action name="Login" class="com.struts2.action.LoginAction">
			<result name="success">/welcome.jsp</result>
			<result name="error">/error.jsp</result>
		</action>
		<action name="Register" class="com.struts2.action.RegisterAction">
			<result name="success">/welcome.jsp</result>
			<result name="error">/error.jsp</result>
		</action>
	</package>
</struts>

8.最后给出最重要的spring配置文件applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>  
<!DOCTYPE beans PUBLIC    
    "-//SPRING//DTD BEAN//EN"   
    "http://www.springframework.org/dtd/spring-beans.dtd">  
<beans> 
	<!-- 数据源配置 -->
	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
		<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
		<property name="url" value="jdbc:mysql://localhost:3306/spring"></property>
		<property name="username" value="root"></property>
		<property name="password" value="root"></property>
	</bean> 
	<!-- 定义Spring JDBC模板类bean -->
	<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
		<property name="dataSource" ref="dataSource"></property>
	</bean>
	<!-- dao -->
	<bean id="userDao" class="com.struts2.dao.UserDao">
		<property name="jdbcTemplate" ref="jdbcTemplate" ></property>
	</bean>
	<!-- service -->
	<bean id="registerService" class="com.struts2.service.RegisterService">
		<property name="userDao" ref="userDao"></property>
	</bean>
	<bean id="loginService" class="com.struts2.service.LoginService">
		<property name="userdao" ref="userDao"></property>
	</bean>
	<!-- action -->
    <bean id="login" class="com.struts2.action.LoginAction">
    	<property name="loginService" ref="loginService"></property>
    </bean> 
    <bean id="register" class="com.struts2.action.RegisterAction">
    	<property name="registerService" ref="registerService"></property>
    </bean> 
</beans>  

从上面明显可以看出层之间的依赖关系,action-->service-->dao--->jdbc模板--->数据源

你可能感兴趣的:(struts2+spring实现简单用户登录注册)