javaweb实现登录界面使用servlet/jsp/xml技术

Javaweb-login-s登录界面使用servlet技术组件器,用jsp来写html代码,servlet来写java代码,实现动态界面的效果

基本步骤:

1.首先得配置jar文件,用build path方法,用于连接数据库

2.需要注意的是得建一个sql数据库用来存储需要验证的数据(用户名和密码)

下面是具体的实施步骤:

www.csdn.net.javaweblogin.dao
UserDao.java:用户验证类
package www.csdn.net.javaweblogin.dao;

import www.csdn.net.javaweblogin.domain.User;

public interface UserDao {
	/**
	 * 用户登录验证
	 */
	public boolean checkLogin(String name,String pass);
	
	/**
	 * 用户登录验证
	 */
	public User checkLogins(String name,String pass);
	
	
}
www.csdn.net.javaweblogin.domain
User.java:user表与User类实体映射
package www.csdn.net.javaweblogin.domain;

import java.io.Serializable;
/**
 * user表与User类实体映射
 * @author Administrator
 *
 */
//实现可序列化接口
public class User implements Serializable{
	/**
	 * 可序列化标识
	 */
	private static final long serialVersionUID = 1L;
	/*映射的实现
	 * 
	 * `id` int(11) NOT NULL AUTO_INCREMENT,                
    `name` varchar(40) DEFAULT NULL,                     
    `pass` varchar(12) DEFAULT NULL,                     
    `instr` varchar(200) DEFAULT NULL,   */   
	private Integer id;
	private String name;
	private String pass;
	private String instr;
	public User() {
		super();
		// TODO Auto-generated constructor stub
	}
	public User(Integer id, String name, String pass, String instr) {
		super();
		this.id = id;
		this.name = name;
		this.pass = pass;
		this.instr = instr;
	}
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getPass() {
		return pass;
	}
	public void setPass(String pass) {
		this.pass = pass;
	}
	public String getInstr() {
		return instr;
	}
	public void setInstr(String instr) {
		this.instr = instr;
	}
	@Override
	public String toString() {
		return "User [id=" + id + ", name=" + name + ", pass=" + pass
				+ ", instr=" + instr + "]";
	}
	
}
www.csdn.net.javaweblogin.util
DBConn.java:单例模式
package www.csdn.net.javaweblogin.util;

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

import com.mysql.jdbc.PreparedStatement;
/**
 * 单例模式
 * (Singleton)
 * @author Administrator
 *
 */
public class DBConn {
	/**
	 * 封装一个私有的静态变量
	 */
	private static Connection conn;
	
	/**
	 * 封装一个公有静态返回私有变量的方法
	 * @return
	 */
	public static Connection getConn(){
		if(conn==null){
			try {
//				加载驱动
				Class.forName("com.mysql.jdbc.Driver");
//				获取连接对象
				conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/javaweb-db", "xxxx, xxxx");
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return conn;
	}
	/**
	 * 释放资源
	 * @param pstmt
	 * @param rs
	 */
	
	public static void release(PreparedStatement pstmt,ResultSet rs){
		
		if(pstmt!=null){
			try {
				pstmt.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		if(rs!=null){
			try {
				rs.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}
www.csdn.net.javaweblogin.dao.impl
UserDaoImpl.java:实现数据库的连接,封装属性,实现方法
package www.csndn.net.javaweblogin.dao.impl;
import java.sql.ResultSet;
import java.sql.SQLException;
import www.csdn.net.javaweblogin.dao.UserDao;
import www.csdn.net.javaweblogin.domain.User;
import www.csdn.net.javaweblogin.util.DBConn;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.PreparedStatement;
public class UserDaoImpl implements UserDao {
	// 封装属性
	private Connection conn;
	private PreparedStatement pstmt;
	private ResultSet rs;
	@Override
	public boolean checkLogin(String name, String pass) {
		// 第一步:声明返回值变量
		boolean flag = false;
		// 第二步:定义sql语句
		String sql = "select id,name,pass,instr from user where name=? and pass=?";
		// 第三步:获取连接对象
		conn = (Connection) DBConn.getConn();
		try {
			// 第四步:根据sql语句获取预处理对象
			pstmt = (PreparedStatement) conn.prepareStatement(sql);
			// 第五步:为占位符赋值
			int index = 1;
			pstmt.setString(index++, name);
			pstmt.setString(index++, pass);
			// 第六步:执行查询操作
			rs = pstmt.executeQuery();
			// 第七步:判断
			if (rs.next()) {
				flag = true;
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return flag;
	}
	@Override
	public User checkLogins(String name, String pass) {
		// 第一步:声明返回值变量
		User entity = null;
		// 第二步:定义sql语句
		String sql = "select id,name,pass,instr from user where name=? and pass=?";
		// 第三步:获取连接对象
		conn = (Connection) DBConn.getConn();
		try {
			// 第四步:根据sql语句获取预处理对象
			pstmt = (PreparedStatement) conn.prepareStatement(sql);
			// 第五步:为占位符赋值
			int index = 1;
			pstmt.setString(index++, name);
			pstmt.setString(index++, pass);
			// 第六步:执行查询操作
			rs = pstmt.executeQuery();
			// 第七步:判断
			if (rs.next()) {
				// 创建对象
				entity = new User();
				// 为对象赋值
				entity.setId(rs.getInt("id"));
				entity.setName(rs.getString("name"));
				entity.setPass(rs.getString("pass"));
				entity.setInstr(rs.getString("instr"));
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return entity;
	}
}
www.csdn.net.servlet
LoginServlet.java:利用servlet技术写java代码:
package www.csdn.net.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import www.csdn.net.javaweblogin.dao.UserDao;
import www.csdn.net.javaweblogin.domain.User;
import www.csndn.net.javaweblogin.dao.impl.UserDaoImpl;
public class LoginServlet extends HttpServlet {
	/**
		doGet的方法
	 */
	//2.全局创建
	private UserDao userDao = new UserDaoImpl();
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
//8.解决乱码问题
		request.setCharacterEncoding("UTF-8");
		
		//1.
		String name = request.getParameter("uname");
		String pass = request.getParameter("upass");
		//3.登录成功返回一个user对象
		User user = userDao.checkLogins(name, pass);
//		4.
		if(user!=null){
//			9.存入到cookie中 ,首先你要看有没有当前的cookie
			Cookie cookies[]=request.getCookies();
//			14.声明当前的cookie
			Cookie autoCookie=null;
//			10.判断cookie是否为空
			if(cookies!=null){
//				11.
				for(Cookie cookie:cookies){
//					12.获取具体的cookie
					String cookieName=cookie.getName();
					
//					13.判断
					if("auto".equals(cookieName)){
//						15.
						autoCookie=cookie;
					}
				}		
			}
//			16.判断cookie是否存在,下面是存在的情况
			if(autoCookie!=null){
//				19.获取cookie的值
				String value=autoCookie.getValue();
//				20.与要记录的新值比较,加上!,说明是不相等的情况
				if(!value.equalsIgnoreCase(name+","+pass)){
//					21.如果不等,就重新赋值
					autoCookie.setValue(name+","+pass);
					//32.设置路径,设置路径的目的是为了加密,让它显示在指定的页面,其他页面访问不到,用到cookie技术.注意:加上:/javaweb-login-s名称
					autoCookie.setPath("/javaweb-login-s/login.jsp");	
					//					22.
					response.addCookie(autoCookie);
				}
			}else{
//				17.不存在的情况下 创建新的cookie
				autoCookie=new Cookie("auto",name+","+pass);
//32.设置路径,设置路径的目的是为了加密,让它显示在指定的页面,其他页面访问不到,用到cookie技术 .注意:加上:/javaweb-login-s名称
			autoCookie.setPath("/javaweb-login-s/login.jsp");		
				//				18.响应过去
				response.addCookie(autoCookie);
			}
//			7.存入到request域中
			request.setAttribute("user", user);
			//6.转发
			request.getRequestDispatcher("./sc.jsp").forward(request, response);
	}else{
		//5.重定向
		response.sendRedirect("./login.jsp");
	}
}
	/**
		doPost的方法
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}
InitLoginServlet.java:cookie存值
package www.csdn.net.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class InitLoginServlet extends HttpServlet {
	/**
		doGet的方法
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		 //27.
		  String value=null;
		  //23.获取所有的cookie信息
		  Cookie cookies[]=request.getCookies();
		  //24.判断cookie是否为null
		  if(cookies!=null){
		  //25.遍历
		  for(Cookie cookie:cookies){
		  	//26.判断
		  	if("auto".equalsIgnoreCase(cookie.getName())){
		  	//28.
			value=cookie.getValue();
				break;
				}
		  	}
		  }
		  //31.
		  String name="";
		  String pass="";
		  //29.判断value值是否为null
		  if(value!=null){
		  //30.拆分
		  	String values[]=value.split(",");
		  	//31.赋值
		  	name=values [0];
		  	pass=values [1];
		  }
//		32
		  request.setAttribute("name",name);
		  request.setAttribute("pass",pass);
//		  33.//转发
		  request.getRequestDispatcher("./login.jsp").forward(request, response);
	}
	/**
		doPost的方法
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}
}
Login.jsp: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 'login.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="./login.do" method="post">
   <table>
  	<tr><td>用户名:</td>
  		<td><input type="text" name="uname" value="${name} " /></td>
  	</tr>
  	<!-- 当前页  page request session application-->
   	<tr><td>密码:</td>
  		<td><input type="password" name="upass" value="${pass}"/></td>
  	</tr>
   <tr>
  		<td colspan="2"><input type="submit" value="登录"/>
  		<input type="reset" value="重置"/>
  		</td>
  	</tr>
   </table>
   </form>
  </body>
</html>
Sc.jsp: jsp技术实现登录成功后的界面
<%@ page language="java" import="java.util.*,www.csdn.net.javaweblogin.domain.User" 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 'sc.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>
  <%-- <%
  User user=(User)request.getAttribute("user");
  String userName=user.getName();
   %> --%>
   <h1>欢迎${user.name}登录</h1>
  </body>
</html>
Web.xml;中间转化层
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>javaweb-login-s</display-name>
  <servlet>
    <description> </description>
    <servlet-name>LoginServlet</servlet-name>
    <servlet-class>www.csdn.net.servlet.LoginServlet</servlet-class>
  </servlet>
  <servlet>
    <description> </description>
    <servlet-name>InitLoginServlet</servlet-name>
    <servlet-class>www.csdn.net.servlet.InitLoginServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>LoginServlet</servlet-name>
    <url-pattern>/login.do</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>InitLoginServlet</servlet-name>
    <url-pattern>/initLogin.do</url-pattern>
  </servlet-mapping>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
</web-app>










©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页