javaweb-servlet登录注册

由servlet,jsp实现登录,注册,修改密码
1.数据库名login 表名t_user
在这里插入图片描述
2.项目文件
在这里插入图片描述
3.项目代码
3.1jsp
3.1.1login.jsp



<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>登陆页面</title>
    
</head>
<body>
<%
	//声明java代码块进行错误提示语逻辑校验
	Object obj=request.getAttribute("flag");
	if(obj!=null){
%>
<div style="text-align; center;">
<span style = "font-size:15px;color:red;font-weight:bold;">用户名或者密码错误</span>
</div>
<%} %>
<%
	//声明java代码块进行修改密码提示语逻辑校验
	Object pwd=session.getAttribute("pwd");
	if(pwd!=null){
%>
<div style="text-align; center;">
<span style = "font-size:15px;color:red;font-weight:bold;">密码修改成功</span>
</div>
<%}
	session.removeAttribute("pwd");
	%>
<form action="UserServlet" method="post">
	<input type="hidden" name="oper" value="login">

        账号:<input type="text" name="uname"><br>

        密码:<input type="password" name="pwd"><br>

        <input type="submit" value= "登录">

        
        </form>
        <lable><a href="regist.jsp">注册</a></lable>

</body>
</html>
    
3.1.2main.jsp

```java
<%@ page language="java"  contentType="text/html; charset=UTF-8"
     pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<dd>个人信息
	<ul>
	<li><a href="userinfo.jsp">查看个人信息</a></li>
	<li><a href="pwd.jsp">修改密码</a></li>
	</ul>
	</dd>
	<dd>管理信息
	<ul>
	<li><a href="UserServlet?oper=show">查看用户信息</a></li>
	
	</ul>
	</dd>

</body>
</html> 

3.1.3pwd.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<!-- 引入jQuery文件 -->
<script type="text/javascript" src="js/jquery.min.js"></script>
<!-- 声明jQuery代码域 -->
<script type="text/javascript">
	$(function(){
		$("fm").submit(function(){
			if($("#newPwd").val==""){
				alert("新密码不能为空");
			}else if($("#cfPwd").val==""){
				alert("确认密码不能为空");
			}else if($("#newPwd").val!=$("#cfPwd").val){
				alert("两次密码不一致");
			}else{
				return true;
			}
		});
	});
</script>
</head>
<body>
	<div>修改密码</div>
	<form action="UserServlet" method="post" id="fm">
		<input type="hidden" name="oper" value="pwd"/>
		<ul>
		<li><label>新密码&nbsp&nbsp&nbsp</label> <input name="newPwd" id=newPwd type="text"/></li>
		<li><label>确认密码</label><input name="" id="cfPwd" type="text"/></li>
		<li><label>&nbsp</label><input name="" type="submit" value="保存"/></li>
		
		</ul>
	</form>
</body>
</html>

3.1.4regist.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="UserRegistServlet" method="post">
		ID: <input type="text" name="uid"><br>
	        用户名:<input type="text" name="uname"><br>
	
	        密    码:<input type="password" name="pwd"><br>
	         性别   :男:<input type="radio" name="sex" value="1">:<input type="radio" name="sex" value="0"><br>
	    年龄<input type="text" name="age"><br>
	    
	       出生年月:<input type="text" name="birth"><br>
		
	        <input type="submit" value= "注册">

        

        </form>
</body>
</html>

3.1.5ShowUser.jsp

<%@ page language="java" import="com.suse.demo.pojo.*,java.util.*" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<table>
	<thead>
	<tr>
	<th>用户ID</th>
	<th>用户名</th>
	<th>密码</th>
	<th>性别</th>
	<th>年龄</th>
	<th>出生年月</th>
	</tr>
	</thead>
	<tbody>
	<!-- 由servlet查询到的lu数组来去对应的数据 -->
	<%
		List<User> lu=(ArrayList<User>)request.getAttribute("lu");
		for(User u:lu){
	%>


		<tr>
		<td><%=u.getUid() %></td>
		<td><%=u.getUname() %></td>
		<td><%=u.getPwd() %></td>
		<td><%=u.getSex() %></td>
		<td><%=u.getAge() %></td>
		<td><%=u.getBirth() %></td>
		</tr>
	<%} %>
	</tbody>
</table>
</body>
</html>

3.1.6userinfo.jsp

<%@ page language="java" import="com.suse.demo.pojo.*" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<table>
	<thead>
	<tr>
	<th>用户ID</th>
	<th>用户名</th>
	<th>密码</th>
	<th>性别</th>
	<th>年龄</th>
	<th>出生年月</th>
	</tr>
	</thead>
	<tbody>
	<!-- 在session中直接获取数据 
	td标签中的报错不影响-->
	<tr>
	<td><%=((User)session.getAttribute("user")).getUid()%></td>
	<td><%=((User)session.getAttribute("user")).getUname()%></td>
	<td><%=((User)session.getAttribute("user")).getPwd()%></td>
	<%
		String sex = ((User)session.getAttribute("user")).getSex();
	if("1".equals(sex)){
	%>
	<td></td>
	<%}else{ %>
	<td></td>
	<%} %>
	<td><%=((User)session.getAttribute("user")).getAge()%></td>
	<td><%=((User)session.getAttribute("user")).getBirth()%></td>
	</tr>
	</tbody>
</table>
</body>
</html>

3.2数据池连接技术
在这里插入图片描述

dbcp.properties文件
driverClassName=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/login?useSSL=false&serverTimezone=UTC
username=root
password=123456
initialSize=10
maxActive=20
maxWait=10000

连接池代码

package com.suse.demo.util;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
import javax.sql.DataSource;
import org.apache.commons.dbcp.BasicDataSourceFactory;
public class JDBCPoolUtil1 {
	private static DataSource dataSource;
	static {
		Properties p = new Properties();
		InputStream in = 
				JDBCPoolUtil1.class.getClassLoader().getResourceAsStream("dbcp.properties");
		try {
			p.load(in);
			dataSource = BasicDataSourceFactory.createDataSource(p);
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static Connection getConnection() {
		Connection conn=null;
		try {
			conn = dataSource.getConnection();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return conn;
	}
}

User.java

package com.suse.demo.pojo;

/**

 * 把数据库中查询到的结果保存到这个对象中

 * 

 *

 */

public class User {
	private int uid;	
	private String uname;
	private String pwd;
	private String sex;
	private int age;
	private String birth;
	public int getUid() {
		return uid;
	}
	public void setUid(int uid) {
		this.uid = uid;
	}
	public String getUname() {
		return uname;
	}
	public void setUname(String uname) {
		this.uname = uname;
	}
	public String getPwd() {
		return pwd;
	}
	public void setPwd(String pwd) {
		this.pwd = pwd;
	}
	public String getSex() {
		return sex;
	}
	public void setSex(String sex) {
		this.sex = sex;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public String getBirth() {
		return birth;
	}
	public void setBirth(String birth) {
		this.birth = birth;
	}
	@Override
	public String toString() {
		return "User [uid=" + uid + ", uname=" + uname + ", pwd=" + pwd + ", sex=" + sex + ", age=" + age + ", birth="
				+ birth + "]";
	}
	public User(int uid, String uname, String pwd, String sex, int age, String birth) {
		super();
		this.uid = uid;
		this.uname = uname;
		this.pwd = pwd;
		this.sex = sex;
		this.age = age;
		this.birth = birth;
	}
	public User() {
		super();
		// TODO Auto-generated constructor stub
	}
	
	
	
}


UserServlet

package com.suse.demo.servlet;

import java.io.IOException;
import java.util.List;

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.suse.demo.pojo.User;
import com.suse.demo.service.UserService;
import com.suse.demo.service.impl.UserServiceImpl;

/**
 * Servlet implementation class UserServlet
 */
@WebServlet("/UserServlet")
public class UserServlet extends HttpServlet {
	//获取service对象
	UserService us = new UserServiceImpl();
	private static final long serialVersionUID = 1L;
  @Override
  
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
	req.setCharacterEncoding("utf-8");
	resp.setContentType("text/html;charset=utf-8");
	//根据不同请求调用不同的请求方法   有jsp中的oper确定
	//获取操作符
	String oper=req.getParameter("oper");
	if("login".equals(oper)) {
		//调用登录处理方法
		checkUserLogin(req,resp);
	}else if("reg".equals(oper)) {
		//调用注册
	
	}
	else if("pwd".equals(oper))	{
		//调用密码修改
		userChangePwd(req,resp);
	}
	else if("show".equals(oper))	{
		//调用显示所有的用户
		userShow(req,resp);
	}
	else {
		System.out.println("没有找到对应的操作符"+oper);
	}

}
  //显示所有用户信息
  private void userShow(HttpServletRequest req, HttpServletResponse resp) {
	List<User> lu = us.userShowService();
	if(lu!=null) {
		req.setAttribute("lu", lu);
		//请求转发
		try {
			req.getRequestDispatcher("ShowUser.jsp").forward(req, resp);
			return;
		} catch (ServletException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
}
//用户修改密码
  private void userChangePwd(HttpServletRequest req, HttpServletResponse resp)  {
	// TODO Auto-generated method stub
	  //获取新密码
	  String newPwd=req.getParameter("newPwd");
	//从session获取用户信息
	  User u =(User)req.getSession().getAttribute("user");
	  int uid=u.getUid();
	  //处理请求
	  int index=us.userChangePwdService(newPwd,uid);
	  if(index>0) {
		  HttpSession hs= req.getSession();
		  hs.setAttribute("pwd","true");	
		  //重定向到登录页面
		  
		  try {
			resp.sendRedirect("login.jsp");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	  }
}
//处理登录
private void checkUserLogin(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
	// TODO Auto-generated method stub
		//获取请求信息
		String uname=req.getParameter("uname");
		String pwd=req.getParameter("pwd");
		//处理请求 信息
			//获取service层对象
			
			//校验
			User u = us.checkUserLoginService(uname, pwd);
			//System.out.println(u);
		//响应处理结果
			if(u!=null) {
				try {
					//获取session对象
					HttpSession hs = req.getSession();
					//将用户数据存储到session中
					hs.setAttribute("user", u);
					resp.sendRedirect("main.jsp");
					return;
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}else {
				//添加标识符到request中
				req.setAttribute("flag", 0);
				//请求转发   /表示根目录
				req.getRequestDispatcher("/login.jsp").forward(req, resp);
				return;
			}
	
}

}

UserRegistServlet

package com.suse.demo.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 com.suse.demo.pojo.User;
import com.suse.demo.service.UserService;
import com.suse.demo.service.impl.UserServiceImpl;

/**
 * Servlet implementation class UserRegistServlet
 */
@WebServlet("/UserRegistServlet")
public class UserRegistServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
      

	/**
	 * @see HttpServlet#service(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		req.setCharacterEncoding("utf-8");
		resp.setContentType("text/html;charset=utf-8");
		//获取请求信息    从页面拿取的数据都是String类型
			int uid=req.getParameter("uid")!=""?Integer.parseInt(req.getParameter("uid")):0;
			String uname=req.getParameter("uname");
			String pwd=req.getParameter("pwd");
			String sex=req.getParameter("sex");
			int age=req.getParameter("age")!=""?Integer.parseInt(req.getParameter("age")):0;
			String birth=req.getParameter("birth");
			//给方法传参
			User u=new User(uid, uname, pwd, sex, age, birth);
		//处理请求信息
			//调用业务层处理
			UserService us = new UserServiceImpl();
			int index=us.userRegistService(u);
			if(index>0) {
				req.getRequestDispatcher("/login.jsp").forward(req, resp);
			}
		//响应处理结果
	}

}

UserService.java

package com.suse.demo.service;

import java.util.List;

import com.suse.demo.pojo.User;

public interface UserService {
	User checkUserLoginService(String uname,String pwd);
	//修改用户密码
	int userChangePwdService(String newPwd, int uid);
	//获取所有的用户信息
	List<User> userShowService();
	//注册功能
	int userRegistService(User u);
}

UserServiceImpl.java

package com.suse.demo.service.impl;


import java.util.List;

import com.suse.demo.dao.UserDao;
import com.suse.demo.dao.impl.UserDaoImpl;
import com.suse.demo.pojo.User;
import com.suse.demo.service.UserService;

public class UserServiceImpl implements UserService {
	//声明Dao层对象
	UserDao ud = new UserDaoImpl();

	@Override
	public User checkUserLoginService(String uname, String pwd) {
		// TODO Auto-generated method stub
		return ud.checkUserLoginDao(uname, pwd);
	}

	@Override
	public int userChangePwdService(String newPwd, int uid) {
		// TODO Auto-generated method stub
		return ud.userChangePwdDao(newPwd,uid);
	}
	//获取所有的用户信息
	@Override
	public List<User> userShowService() {
		
		return ud.userShowDao();
	}

	@Override
	public int userRegistService(User u) {
		// TODO Auto-generated method stub
		return ud.userRegistDao(u);
	}





}

UserDao.java

package com.suse.demo.dao;

import java.util.List;

import com.suse.demo.pojo.User;

/**
 * 根据用户名和密码查询用户信息
 * @author Lenovo
 *
 */
public interface UserDao {
	 User checkUserLoginDao(String uname,String pwd);
	 //根据用户ID修改密码
	int userChangePwdDao(String newPwd, int uid);
	//获取所有的用户信息
	List<User> userShowDao();
	//注册
	int userRegistDao(User u);
}

UserDaoImpl.java

package com.suse.demo.dao.impl;

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

import com.suse.demo.dao.UserDao;
import com.suse.demo.pojo.User;
import com.suse.demo.util.JDBCPoolUtil1;

public class UserDaoImpl implements UserDao{

	@Override
	public User checkUserLoginDao(String uname, String pwd) {
		Connection conn = JDBCPoolUtil1.getConnection();
		String sql = "select * from t_user where uname=? and pwd=?";
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
			 ps = conn.prepareStatement(sql);
			 ps.setString(1, uname);
			 ps.setString(2, pwd);			 
			 rs = ps.executeQuery();
			 if(rs.next()) {
				 User u = new User();
				 u.setUid(rs.getInt("uid"));
				 u.setUname(rs.getString("uname"));
				 u.setPwd(rs.getString("pwd"));
				 u.setAge(rs.getInt("age"));
				 u.setSex(rs.getString("sex"));
				 u.setBirth(rs.getString("birth"));
				 return u;
			 }
		} catch (SQLException e) {
			e.printStackTrace();
		}finally {
			try {
				rs.close();
				ps.close();
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return null;
	}

	@Override
	public int userChangePwdDao(String newPwd, int uid) {
		// TODO Auto-generated method stub
		int index=-1;
		Connection conn = JDBCPoolUtil1.getConnection();
		String sql = "update t_user set pwd=? where uid=?";
		PreparedStatement ps = null;
		
		try {
			 ps = conn.prepareStatement(sql);
			 ps.setString(1, newPwd);
			 ps.setInt(2, uid);			 
			 index = ps.executeUpdate();
		
		} catch (SQLException e) {
			e.printStackTrace();
		}finally {
			try {
				
				ps.close();
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return index;
	}

	@Override
	public List<User> userShowDao() {
		Connection conn = JDBCPoolUtil1.getConnection();
		String sql = "select * from t_user";
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
			 ps = conn.prepareStatement(sql);		 
			 rs = ps.executeQuery();
			 List<User> lu = null;
			 //给集合赋值
			 lu=new ArrayList<User>();
			 if(rs.next()) {
				 User u= new User();
				 u.setUid(rs.getInt("uid"));
				 u.setUname(rs.getString("uname"));
				 u.setPwd(rs.getString("pwd"));
				 u.setAge(rs.getInt("age"));
				 u.setSex(rs.getString("sex"));
				 u.setBirth(rs.getString("birth"));
				 //将对象存储在集合中
				 lu.add(u);
				 return lu;
			 }
		} catch (SQLException e) {
			e.printStackTrace();
		}finally {
			try {
				rs.close();
				ps.close();
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return null;
	}

	@Override
	public int userRegistDao(User u) {
		// TODO Auto-generated method stub
		Connection conn = JDBCPoolUtil1.getConnection();
		String sql = "insert into t_user value(?,?,?,?,?,?)";
		PreparedStatement ps = null;
		int index=-1;
		//ResultSet rs = null;
		try {
			 ps = conn.prepareStatement(sql);
			 ps.setInt(1, u.getUid());
			 ps.setString(2, u.getUname());
			 ps.setString(3, u.getPwd());
			 ps.setString(4, u.getSex());
			 ps.setInt(5, u.getAge());
			 ps.setString(6, u.getBirth());
			 //执行
			 index = ps.executeUpdate();
			 
		} catch (SQLException e) {
			e.printStackTrace();
		}finally {
			try {
				
				ps.close();
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return index;
	}

}

发布了5 篇原创文章 · 获赞 0 · 访问量 60

猜你喜欢

转载自blog.csdn.net/markya/article/details/105059475