j2ee使用struts实现用户的登陆及注册


1、项目整体的目录结构


2、index.jsp用户登录页面,设为web应用的首页。页面中应该包括用户名和密码的输入框以及登录和注册按钮,具体代码及解释已经在下面的code中写得很详细了。当时在js代码里分配action时,对连接action的路径的地方弄了好久,后来查了很多资料才恍然

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <%@taglib uri="/struts-tags" prefix="s" %>




    
    
登录注册页
<script type="text/javascript">
	function login_()
	{
	document.getElementById("login").action="<%=request.getContextPath()%>/login.action";
	<%--
	" <%=request.getContextPath()%>"表示返回根目录路径;此时namespace为"/",若namespace为/root1,
	则此时应该为document.getElementById("login").action="<%=request.getContextPath()%>/root1/login.action";
	login.action中的login为struts中名为login的action ;注意:login.action的action不能少。
	 --%>
	document.getElementById("login").submit();
	}
	function registor_()
	{
	document.getElementById("login").action="<%=request.getContextPath()%>/regist.action";
	document.getElementById("login").submit();
	} 
</script>



    
    

    
    
用户名:
密码:
<%-- 使用struts标签 --%> <%-- --%>
3、LoginAction.java主要是对提交的事物进行处理。主要包括登录和注册两种方法

package org.action;

import java.util.Map;

import org.dao.DbService;
import org.model.User;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
@SuppressWarnings("serial")
public class LoginAction extends ActionSupport{
	private User user;//定义一个User类的对象

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}
	/*public String execute(){
		if(user.getUsername().equals("ky")&&user.getPassword().equals("123")){
			return SUCCESS;}
		else
			return ERROR;
	}*/
	
	//登陆方法login()
	public String login()throws Exception {
		/*if(user.getUsername().equals("ky")&&user.getPassword().equals("123")){
			System.out.print("name=ky");
			return SUCCESS;
		}
		if(user.getUsername().equals("zzzz")&&user.getPassword().equals("111")){
			System.out.print("name=zzzz");
			return SUCCESS;
		}
		else {
			System.out.print("name=error");
			return ERROR;
		}*/
		DbService dbService = new DbService();
		user = dbService.hasUser(user.getUsername(),user.getPassword());
		if(user.getUsername()==null) {
			this.addFieldError(user.getUsername(), "用户或密码不正确!");
			System.out.print("用户或密码不正确!\n");
			return "login_error";//登录失败
		} else {
			ActionContext actionContext = ActionContext.getContext();
			Map session = actionContext.getSession();
			session.put("user", user.getUsername());
		}
		return "login_success";//登陆成功
	}
	
	//注册方法regist()
	public String regist()throws Exception {
		User user_=new User();
		user_.setUsername(user.getUsername());
		user_.setPassword(user.getPassword());
		DbService dbService=new DbService();
		if(dbService.hasSameUser(user.getUsername())){
			this.addFieldError(user.getUsername(), "用户名已存在!");
			System.out.print("用户名已存在!\n");
			return "regist_error";//注册失败
		}
		else{
			dbService.addUser(user_);
		}
		return "regist_success";//注册成功
		}
	
}
4、DbConnection.java 定义一个类,主要实现Mysql数据库的连接

package org.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.mysql.jdbc.Driver;
/*
 * hh.todd@qq.com
 * 
 *配置jdbc,连接到MySQL数据库
 * 
 *要将jdbc的驱动导入到工程中
 * 
 * */

public class DbConnection{
	static{
		try{
			Class.forName("com.mysql.jdbc.Driver"); 
			//保证相应的Driver类已经被加载到jvm中
		}
		catch (ClassNotFoundException e) {
			// TODO: handle exception
			System.out.print("Error loading Mysql Driver!");  
			e.printStackTrace();
		}
		/*try {
			com.mysql.jdbc.Driver driver=new com.mysql.jdbc.Driver();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}*/
	}
	public static Connection getConnection(){
		Connection con=null;
		System.out.print("access getConnection()"); 
		String url="jdbc:mysql://127.0.0.1:3306/new_schema";
		//连接到MySQL中名叫new_schema的数据库;
		String user="root";
		//登陆到MySQL的用户名;
		String password="1111";
		//登陆到MySQL的密码;
		try{
			con=DriverManager.getConnection(url, user, password);
			//Attempts to establish a connection to the given database URL
		}catch (SQLException e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return con;
	}
	
	//定义closeConnection()方法
	public static void closeConnection(ResultSet rs,PreparedStatement ps,Connection con){
		if(rs!=null){
			try{
				System.out.print("rs.close();!");  
				rs.close();
			}catch (SQLException e) {
				// TODO: handle exception
				e.printStackTrace();
			}
		}
		if(ps!=null){
			try{
				System.out.print("ps.close()!"); 
				ps.close(); 
			}catch (SQLException e) {
				// TODO: handle exception
				e.printStackTrace();
			}
		}
		if(con!=null){
			try{
				System.out.print("con.close();!");  
				con.close();
			}catch (SQLException e) {
				// TODO: handle exception
				e.printStackTrace();
			}
		}
	}
}
5、DbService.java 主要实现对提交数据的操作,如查找用户,增加用户数据。。。

package org.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.model.User;

public class DbService {
	
	//添加注册用户
	public void addUser(User user){
		Connection connection=DbConnection.getConnection();
		PreparedStatement ps=null;
		String sql="insert into simple_tb (username,password) values(?,?)";
		try{
			ps=connection.prepareStatement(sql);
			System.out.println("\n======="+user.getUsername());
		    System.out.println("\n======="+user.getPassword());
			ps.setString(1, user.getUsername());//将数据写入数据库
			ps.setString(2, user.getPassword());
			ps.executeUpdate();
			//Executes the SQL statement in this PreparedStatement object;
		}catch (SQLException e) {
			// TODO: handle exception 
			e.printStackTrace();
		}
		
	}
	
	//查找用户是否存在
	public User hasUser(String username,String password){
		User user=new User();
		Connection connection=DbConnection.getConnection();
		PreparedStatement ps=null;
		ResultSet rs=null;
		String sql="select * from simple_tb where username=? and password=?";
		try {
			ps=connection.prepareStatement(sql); 
			ps.setString(1, username);
			//key-value中的key对应着sql语句中的第几个“?”
			ps.setString(2, password);
			rs=ps.executeQuery();
			/*Executes the SQL query in this PreparedStatement object and
			 *  returns the ResultSet object generated by the query.*/

			if(rs.next()){	//从第一行数据开始查找
				System.out.println("\n======="+rs.getString(1));
			    System.out.println("\n======="+rs.getString(2));
				user.setUsername(rs.getString("username"));//将查找到的数据返回
				user.setPassword(rs.getString("password"));
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			DbConnection.closeConnection(rs, ps, connection);
		}
		return user;
	}
	
	//查找用户名是否已经被注册
	public Boolean hasSameUser(String username){
		String name=null;
		Connection connection=DbConnection.getConnection();
		PreparedStatement ps=null;
		ResultSet rs=null;
		String sql="select * from simple_tb where username=?";
		try {
			ps=connection.prepareStatement(sql);
			ps.setString(1, username);
			rs=ps.executeQuery();
			if(rs.next()){
				name=rs.getString("username");
				if(name.equals(username))
					return true;
				else
					return false;
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			DbConnection.closeConnection(rs, ps, connection);
		}
		return false;
	}

}


6、struts的配置


    
    


    
    
  
     
     
  
      
      
	
      
      
		
       
       
        
        /Login_success.jsp
       
       
		
       
       
        
        /login_error.jsp
       
       
	
      
       
	
      
      
		
       
       
        
        /regist_success.jsp
       
       
		
       
       
        
        /regist_error.jsp
       
       
	
      
       
	
      
      
	
      
      
  
     
     

    
    

运行效果图:




   






整个项目的源码下载:http://download.csdn.net/detail/u012612399/7258769

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值