Servlet JavaBean

本文详细介绍了一个基于Java的用户登录系统的设计与实现过程,包括UserBean类的属性与方法,MySqlDao类的数据库连接,UserDao类的登录验证与用户信息更新,以及UserServlet类的请求处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

UserBean.java

package user;

import java.sql.Timestamp;

public class UserBean {
	private String account;
	private String nickname;
	private String pwd;
	private Timestamp lasttime;
	private int loginnum;
	private String lastip;
	
	public UserBean() {}
	
	public UserBean(String accout,String pwd) {
		this.account =accout;
		this.pwd = pwd;
	}
	public UserBean(String account,String pwd,String nickname) {
		this(account,pwd);
		this.nickname = nickname;		
	}

	
	public String getAccount() {
		return account;
	}
	public void setAccount(String account) {
		this.account = account;
	}
	public String getNickname() {
		return nickname;
	}
	public void setNickname(String nickname) {
		this.nickname = nickname;
	}
	public String getPwd() {
		return pwd;
	}
	public void setPwd(String pwd) {
		this.pwd = pwd;
	}
	public Timestamp getLasttime() {
		return lasttime;
	}
	public void setLasttime(Timestamp date) {
		this.lasttime = date;
	}
	public int getLoginnum() {
		return loginnum;
	}
	public void setLoginnum(int loginnum) {
		this.loginnum = loginnum;
	}
	public String getLastip() {
		return lastip;
	}
	public void setLastip(String lastip) {
		this.lastip = lastip;
	}
	
}

MySqlDao.java

package user;
import java.sql.DriverManager;
import java.sql.SQLException;

import javax.naming.NamingException;

import com.mysql.jdbc.Connection;

public class MySqlDao {
	static String driver = "com.mysql.jdbc.Driver";
	static String url = "jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8"; 
	static String user = "root";
	static String password = "123456";
	static Connection aConnection;
	
	public static Connection connectDB() throws SQLException,NamingException{
		try{
			Class.forName(driver);
			aConnection = (Connection) DriverManager.getConnection(url,user,password);
			if(aConnection.isClosed())
			{
				System.out.print("Succeeded!");
			}
		}catch(ClassNotFoundException e){
			System.out.println(e);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		return aConnection;
		}	

}

UserDao.java

package user;

import java.sql.ResultSet;
import java.sql.SQLException;
import javax.naming.NamingException;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.PreparedStatement;

public class UserDao {
	private static Connection conn;	
	public UserDao() throws NamingException{
		 if(conn==null)
		    {   
		        try
		        {
		            conn=MySqlDao.connectDB();        

		        }
		        catch(SQLException se)
		        {
		            se.printStackTrace();
		        }
		    }	
	}
	public boolean loginUser(String account,String pwd) {
		ResultSet rsResultSet = null;
		PreparedStatement pstate = null;
		String password = null;
		try {
			String sql = "select ui_pwd from userinfo where ui_account="+account;
			pstate = (PreparedStatement) conn.prepareStatement(sql);
			rsResultSet = pstate.executeQuery();
			while(rsResultSet.next()) {
				password = rsResultSet.getString("ui_pwd");
			}
			if (password.equals(pwd)) {
				return true;
			}
		 }catch(SQLException e)
		        {
		            e.printStackTrace();
		        }
		        finally
		        {
		            try
		            {
		                pstate.close(); 
		            }
		            catch(SQLException e)
		            {
		                e.printStackTrace();
		            }
		        }
		return false;		
	}
	
	public String[] selectUser(String account) throws SQLException
	{
	        ResultSet rs = null;
	        PreparedStatement pstate = null;
	        String[] arr = new String[2];
	        try
	        {   
	        	String sql = "select ui_nickname,ui_loginnum from userinfo where ui_account="+account; 
	        	pstate=(PreparedStatement) conn.prepareStatement(sql);
	        	rs = pstate.executeQuery(sql);	        	
	        	while(rs.next()){
		 			arr[0] = String.valueOf(rs.getInt("ui_loginnum"));
		 			arr[1] = rs.getString("ui_nickname");
		 		}
	        }
	        catch(SQLException e)
	        {
	            e.printStackTrace();
	        }
	        finally
	        {
	            try
	            {
	                pstate.close(); 
	            }
	            catch(SQLException e)
	            {
	                e.printStackTrace();
	            }
	        }
			return arr; 

	}
	
	public void updateUser(UserBean user) {
		String sql = "update userinfo set ui_lasttime=?,ui_loginnum=?,ui_lastip=? where ui_account=?";
		PreparedStatement ps = null;
		try {
			ps = (PreparedStatement) conn.prepareStatement(sql);
			ps.setTimestamp(1, user.getLasttime());
			ps.setInt(2,user.getLoginnum());
			ps.setString(3, user.getLastip());
			ps.setString(4, user.getAccount());
			ps.executeUpdate();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally
        {
            try
            {
                ps.close(); 
            }
            catch(SQLException e)
            {
                e.printStackTrace();
            }
        }   
		
	}
	

}

UserServlet.java

package user;

import java.io.IOException;
import java.sql.SQLException;
import java.sql.Timestamp;

import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/UserServlet")
public class UserServlet extends HttpServlet{
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	public UserServlet() {
	super();
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		
		String account = req.getParameter("account");
		String pwd = req.getParameter("pwd");
		String lastip = req.getRemoteAddr();
		UserBean userBean = new UserBean(account,pwd);
		UserDao userDao;
		try {
			userDao = new UserDao();
			Timestamp timeStamp = new Timestamp(System.currentTimeMillis()); 
			userBean.setLasttime(timeStamp);
			userBean.setLastip(lastip);
		 	String nickname = null;
		 	String[] arr = new String[2]; 
		 	int loginnum = 0;		
			 	if(userDao.loginUser(account, pwd)){
			 		try {
			 			arr = userDao.selectUser(account);
						loginnum = Integer.parseInt(arr[0]);
						nickname = arr[1];						
				 		loginnum+=1;
				 		userBean.setLoginnum(loginnum);
				 		userBean.setNickname(nickname);
				 		userDao.updateUser(userBean);
					} catch (SQLException e) {
						e.printStackTrace();
					}
			 		 req.setAttribute("user", userBean);
			         req.getRequestDispatcher("login.jsp").forward(req, resp);	 
			}
		} catch (NamingException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}		
		
	}
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		
	}
	  

}

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app>
	<servlet>
	    <servlet-name>UserServlet</servlet-name>
	    <servlet-class>user.UserServlet</servlet-class>
	</servlet>
	  <servlet-mapping>
    <servlet-name>UserServlet</servlet-name>
    <!-- 访问的网址 -->
    <url-pattern>/User/UserServlet</url-pattern>
  </servlet-mapping>
  <welcome-file-list>
    <welcome-file>login.html</welcome-file>
  </welcome-file-list>

</web-app>

login.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>UserLogin</title>
<style>
.content{
margin:auto;
width:50%;
height:450px;
font-family:"Microsoft YaHei",Consolas;
border:1px solid #b0b0b0;
border-radius:5px;
}
.title{
width:100%;
height:70px;
background:#36f;
}
form{
margin:80px 20px;
height:200px;
}
h3{
text-decroation:none;
display:inline-block;
color:#fff;
font-weight:normal;
}
p{
margin:20px 100px;
}
label{
width:80px;
height:30px;
display:inline-block;
text-align:right;
font-size:16px;
line-height:30px;
}
input[type=text],input[type=password]{
width:200px;
height:20px;
}
a{
text-decroation:none;
font-size:14px;
color:#66f;
}
.btn{
background:#36f;
color:#fff;
font-size:16px;
width:80px;
height:35px;
margin:30px 80px;
border:2px solid #fff;
border-radius:5px;
}
.btn:hover{
background:#00f;
}
.foot{
margin:-70px 250px;
font-size:10px;
}
img{
margin:10px;
float:left;
}
</style>
</head>
<body>
<div class="content">
<div class="title">
<img src="picture/news.png" width=50 height=50>
<h3>欢迎使用</h3>
</div>
<div>
<form action="UserServlet" method="post" onSubmit="return login()">
<p>
<label>用户名:</label>
<input type="text" name="account">
</p>
<p>
<label>密&nbsp;&nbsp;&nbsp;码:</label>
<input type="password" name="pwd">
<a>忘记密码?</a>
</p>
<p>
<input type="submit" class="btn" value="登录" >
<input type="button" class="btn" value="注册" style="margin-left:-70px">
</p>
</form>
</div>
<p class="foot">关于我们&copy;2018</p>
</div>
</body>
<script type="text/javascript">
function login(){
	var name = document.getElementName("account");
	var passwd = document.getElementName("pwd");
	if("".equals(name)||"".equals(passwd)){
		alert("用户名或密码不能为空!");
		return false;
	}else{
		return true;
	}	
}
</script>
</html>

login.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page import="user.UserBean" %>   
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>WelcomePage</title>
<style>
div{
margin:auto;
width:70%;
font-family:"Microsoft YaHei";
font-size:18px;
}
table, table tr td { 
border:2px solid #3366ff;
padding:4px 15px;
}
table {
width: 400px;
min-height: 30px; 
line-height: 30px; 
text-align: left; 
border-collapse: collapse;
} 
</style>
</head>
<body>
<% UserBean userBean=(UserBean)request.getAttribute("user"); %>

<div>
<table>
<tr>
<td colspan=2>用户信息</td>
</tr>
<tr>
<td>账号:</td>
<td><%=userBean.getAccount()%></td>
</tr>
<tr>
<td>昵称:</td>
<td><%=userBean.getNickname()%></td>
</tr>
<tr>
<td>登录次数:</td>
<td><%=userBean.getLoginnum()%></td>
</tr>
<tr>
<td>登录时间:</td>
<td><%=userBean.getLasttime()%></td>
</tr>
<tr>
<td>最后登录ip:</td>
<td><%=userBean.getLastip()%></td>
</tr>
</table>
</div>
</body>
</html>

致qq:

[1] 获取当时时间:Timestamp timeStamp = new Timestamp(System.currentTimeMillis()); 

DateTime  YYYY-MM-DD HH:mm:ss   TimeStamp YYYY-MM-DD HH:mm:ss

Date YYYY-MM-DD  

Time HH:mm:ss

[2] 传递ResultSet 注意 preparedstatement.close() 后 resultset 是不可用的 返回结果可以使用数组 string[]

[3] 获取resultset 结果集 可以使用 int id = rs.getInt(1) 起始坐标为1 ,也可以使用 int id = rs.getInt("id");

[4] int->string String.valueOf(int)  string->int Integer.parseInt(string)

[5] 传递使用 javabean 

中间跳转:

 req.setAttribute("user", userBean);
 req.getRequestDispatcher("login.jsp").forward(req, resp);    实现跳转

使用页:

<% UserBean userBean=(UserBean)request.getAttribute("user"); %>

  

 

图片:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值