JavaWeb | Myeclispe基于MVC的登入实现

步骤如下:

1、建立web project项目

2、导入连接数据库的jdbc包

这个包去安装Oracle的位置找:如下位置

3、搭建MVC的框架:模型层,视图层,控制层

模型层:DAO

package com.ljl.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import com.ljl.entity.UserEntity;
import com.sun.org.apache.bcel.internal.generic.NEW;

public class UserDao {
	private String url = "jdbc:oracle:thin:@localhost:1521:ORCL";
	private String dbuser = "scott";
	private String dbpwd = "123456";
	private String sql = "";

	private Connection conn = null;
	private PreparedStatement pstmt = null;
	private ResultSet rs = null;

	//定义一个集合
	private List<UserEntity> data = new ArrayList<UserEntity>();
	


	/** 
	 * @Title:        login 
	 * @Description:  TODO  登入   
	 */
	public UserEntity login(String ename, String epwd) {

		try {

			Class.forName("oracle.jdbc.OracleDriver");
			conn = DriverManager.getConnection(url, dbuser, dbpwd);

			sql = "select username,password,email from users where username=?";
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, ename);
			rs = pstmt.executeQuery();

			if (rs.next()) {
				//Integer id = rs.getInt("id");
				String dbepwd = rs.getString("password");
				String email = rs.getString("email");
				if (epwd.equals(dbepwd)) {
					UserEntity users = new UserEntity(ename, dbepwd, email);
					return users;
				}
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				if (rs != null) {
					rs.close();
				}
				if (pstmt != null) {
					pstmt.close();
				}
				if (conn != null) {
					conn.close();
				}
			} catch (Exception e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();

			}
		}

		return null;

	}

	/** 
	 * @Title:        selectByName 
	 * @Description:  TODO  通过用户名查询信息  
	 */
	public List<UserEntity> selectByName(String username) {
		try {
			Class.forName("oracle.jdbc.OracleDriver");
			conn = DriverManager.getConnection(url, dbuser, dbpwd);
			
			//模糊查询
			//sql ="SELECT username,password,email FROM users WHERE username LIKE ('%'||'?'||'%')";
			sql = "select username,password,nvl(email,'暂无邮箱')as email from users where username like ?";
			//sql = "select username,password,email from users where username like '?'";
			pstmt = conn.prepareStatement(sql);
			System.out.println(sql);
			pstmt.setString(1,"%"+ username +"%");
			
			rs = pstmt.executeQuery();
			//遍历结果集
			while(rs.next()) {
				String name = rs.getString("username");
				String dbepwd = rs.getString("password");
				String email = rs.getString("email");
				
				UserEntity user = new UserEntity(name, dbepwd, email);
				data.add(user);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				if (rs != null) {
					rs.close();
				}
				if (pstmt != null) {
					pstmt.close();
				}
				if (conn != null) {
					conn.close();
				}
			} catch (Exception e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
	
			}
		}
		return data;
		
	}

	/** 
	 * @Title:        addUser 
	 * @Description:  TODO 添加注册    
	 */
	public boolean addUser(UserEntity u) {
	       
	        boolean boo = false;

	        try {
	        	Class.forName("oracle.jdbc.OracleDriver");
				conn = DriverManager.getConnection(url, dbuser, dbpwd);

	            String sql  ="insert into users(username,password,email)values(?,?,?)";
	            pstmt = conn.prepareStatement(sql);

	            //运用实体对象进行参数赋值
	           // pstmt.setInt(1, u.getId());
	            pstmt.setString(1, u.getUsername());
	            pstmt.setString(2, u.getPassword());
	            pstmt.setString(3, u.getEmail());

	            int result = pstmt.executeUpdate();
	            if(result > 0){
	                boo = true;
	                System.out.println("插入数据成功");
	            }else{
	                System.out.println("未插入数据");
	            }
	        } catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} finally {
				try {
					if (rs != null) {
						rs.close();
					}
					if (pstmt != null) {
						pstmt.close();
					}
					if (conn != null) {
						conn.close();
					}
				} catch (Exception e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();

				}
			}
	        return boo;
	    }
}

视图层:jsp【login.jsp,success.jsp,fail.jsp】

login.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>

<title>登入</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta http-equiv="pragma" 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" href="./css/login.css">

</head>

<body>
	<form id="form1" name="form1" method="post" action="login">
		<div class="login">
			<div class="center">
				<h1>Login</h1>
				<div class="inputLi">
					<strong>账户</strong> <input type="text" name="ename" id="name" placeholder="请输入账户名" />
				</div>
				<div class="inputLi">
					<strong>密码</strong> <input type="password" name="epwd" id="pwd" placeholder="请输入您的密码">
				</div>
				<div class="inputLi">
					<button>登录</button>
					<input type="reset" name="button" id="button" value="重置" />
				</div>
				<center>没有账号,点击<a href="register.jsp" target="_blank">注册</a></center>
			</div>
		</div>
	</form>

</body>

</html>

success.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>成功!</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">
	-->
<style>
.child {
	position: fixed;
	top: 50%;
	left: 50%;
	margin-top: -75px;
	margin-left: -100px;
}

.background {
	background-image: linear-gradient(120deg, #18bd43 0%, #66a6ff 100%);
}
</style>

</head>

<body class="background">
	<div class="child">
		<center>
			<%
				if (session.getAttribute("myuser") != null) {
			%>
			<h1>成功!</h1>
			<%
				} else {
					response.sendRedirect("login.jsp");
				}
			%>

			<br>
			<form id="form1" name="form1" method="post" action="select">
				<p>
					用户查询: <label for="name"></label> <input type="text" name="name" id="name" />
				</p>
				<p>
					<input type="submit" name="button" id="button" value="查询" />
				</p>
			</form>
			
			<%
			if(session.getAttribute("cxerrro")!=null){
				session.removeAttribute("cxerro");
			%>
			<h1>对不起,无此用户信息</h1>
			<%
			}
			 %>
		</center>
	</div>


</body>
</html>

fail.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>失败!</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">
	-->
	<style>
.child {
	position: fixed;
	top: 50%;
	left: 50%;
	margin-top: -75px;
	margin-left: -100px;
}
.background{
    background-image: linear-gradient(120deg, #bd18a9 0%, #f14021 100%);
	
}
</style>

  </head>
  
  <body class="background">
  <div class="child">
		<center>
			<h1>失败!</h1> <br>
			<br>
		</center>
	</div>
  
  </body>
</html>

控制层:servlet

package com.ljl.Servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.ljl.dao.UserDao;
import com.ljl.entity.UserEntity;

/**
 * Servlet implementation class LoginServlet2
 */
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public LoginServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		/*
		 * 1.获得并解析用户请求
		 * 2.调用业务逻辑类
		 * 3.获得结果
		 * 4.根据结果选择相应的视图响应(转发或重定向)
		 */
		//1.
		String ename = request.getParameter("ename");
		String epwd = request.getParameter("epwd");
		//2.
		UserDao ed = new UserDao();
		//3.
		UserEntity emp = ed.login(ename, epwd);
		
		//4.
		if (emp!=null) {
			//5.启动session
			HttpSession session = request.getSession();
			session.setAttribute("myuser", emp);
			response.sendRedirect("success.jsp");
		}else {
			
			response.sendRedirect("fail.jsp");
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		this.doGet(request, response);
	}

}

效果图

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值