JAVA WEB登陆界面基本代码
java用户登录界面的代码
java用户登录界面的代码以下是一个简单的Java用户登录界面的代码示例,其中包括了GUI界面设计和用户验证的代码:```javaimport javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JTextField;import javax.swing.JPasswordField;import javax.swing.JButton;import java.awt.event.ActionListener;import java.awt.event.ActionEvent;public class LoginWindow extends JFrame implements ActionListener {private JLabel usernameLabel, passwordLabel;private JTextField usernameTextField;private JPasswordField passwordField;private JButton loginButton;public LoginWindow() {setTitle("用户登录");setSize(400, 200);setLocationRelativeTo(null);setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);usernameLabel = new JLabel("用户名:");passwordLabel = new JLabel("密码:");usernameTextField = new JTextField();passwordField = new JPasswordField();loginButton = new JButton("登录");loginButton.addActionListener(this);setLayout(null);usernameLabel.setBounds(50, 30, 80, 25);passwordLabel.setBounds(50, 70, 80, 25);usernameTextField.setBounds(130, 30, 200, 25);passwordField.setBounds(130, 70, 200, 25);loginButton.setBounds(150, 120, 100, 25);add(usernameLabel);add(passwordLabel);add(usernameTextField);add(passwordField);add(loginButton);setVisible(true);}public void actionPerformed(ActionEvent e) {String username = usernameTextField.getText();String password = newString(passwordField.getPassword());if (isValidUser(username, password)) {System.out.println("用户登录成功!");// 在这里可以跳转到下一个界面} else {System.out.println("用户名或密码错误!");}}private boolean isValidUser(String username, String password) {// 在这里实现用户验证的代码// 比如查询数据库是否有该用户并且密码是否匹配等等// 如果验证成功则返回true,否则返回falsereturn false;}public static void main(String[] args) {new LoginWindow();}}```该代码创建了一个窗口界面,包括“用户名”和“密码”两个文本框,以及一个“登录”按钮。
javaweb课程设计源码参考
javaweb课程设计源码参考JavaWeb课程设计源码参考一、引言JavaWeb课程设计是计算机科学与技术专业的一门重要课程。
在这门课程中,学生需要掌握JavaWeb开发的基本知识和技能,并通过实践来加深对所学知识的理解。
本文将为大家提供一些JavaWeb课程设计的源码参考,帮助学生更好地完成课程设计。
二、登录页面登录页面是JavaWeb课程设计中常见的一个功能模块。
下面是一个简单的登录页面源码参考:```java<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %><!DOCTYPE html><html><head><title>登录页面</title></head><body><form action="login" method="post"><label for="username">用户名:</label><input type="text" id="username" name="username"><br><br><label for="password">密码:</label><input type="password" id="password" name="password"><br><br><input type="submit" value="登录"></form></body></html>```三、登录功能实现登录功能是JavaWeb课程设计中的核心功能之一。
javaweb登录界面源代码
javaweb登录界⾯源代码⼤概流程:在java web项⽬中导⼊sqljdbc4的包在java Resources中完成java代码在webContent 下建⽴⼀个存放⾃⼰写jsp的⽂件夹将sqljdbc4和jstl-1.2 包粘贴载WEB-INF⽂件下的lib⽂件下。
java web 登录界⾯源代码:1.Data_uil.javaimport java.sql.*;public class Data_uil{public Connection getConnection(){try{Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");}catch(ClassNotFoundException e){e.printStackTrace();}String user="***";String password="***";String url="jdbc:sqlserver://127.0.0.1:1433;DatabaseName=***";Connection con=null;try{con=DriverManager.getConnection(url,user,password);}catch(SQLException e){e.printStackTrace();}return con;}public String selectPassword(String username){Connection connection=getConnection();String sql="select *from login where username=?";PreparedStatement preparedStatement=null;ResultSet result=null;String password=null;try{preparedStatement=connection.prepareStatement(sql);preparedStatement.setString(1,username);result=preparedStatement.executeQuery();//可执⾏的查询if(result.next())password=result.getString("password");}catch(SQLException e){e.printStackTrace();}finally{close(preparedStatement);close(result);close(connection);}System.out.println("找到的数据库密码为:"+password);return password;}public void close (Connection con){try{if(con!=null){con.close();}}catch(SQLException e){e.printStackTrace();}}public void close (PreparedStatement preparedStatement){try{if(preparedStatement!=null){preparedStatement.close();}}catch(SQLException e){e.printStackTrace();}}public void close(ResultSet resultSet){try{if(resultSet!=null){resultSet.close();}}catch(SQLException e){e.printStackTrace();}}}2.login_check.jsp:<%@ page language="java" contentType="text/html; charset=utf-8"pageEncoding="utf-8"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "/TR/html4/loose.dtd"> <html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"><title>验证⽤户密码</title></head><body><jsp:useBean id="util" class="util.Data_uil" scope="page" /><%String username=(String)request.getParameter("username");String password=(String)request.getParameter("password");if(username==null||"".equals(username)){out.print("<script language='javaScript'> alert('⽤户名不能为空');</script>");response.setHeader("refresh", "0;url=user_login.jsp");}else{System.out.println("输⼊的⽤户名:"+username);String passwordInDataBase=util.selectPassword(username);System.out.println("密码:"+passwordInDataBase);if(passwordInDataBase==null||"".equals(passwordInDataBase)){out.print("<script language='javaScript'> alert('⽤户名不存在');</script>");response.setHeader("refresh", "0;url=user_login.jsp");}else if(passwordInDataBase.equals(password)){out.print("<script language='javaScript'> alert('登录成功');</script>");response.setHeader("refresh", "0;url=loginSucces.jsp");}else{out.print("<script language='javaScript'> alert('密码错误');</script>");response.setHeader("refresh", "0;url=user_login.jsp");}}%></body></html>3.loginSucces.jsp<%@ page language="java" contentType="text/html; charset=utf-8"pageEncoding="utf-8"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "/TR/html4/loose.dtd"> <html><head><meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"><title>Insert title here</title></head><body><hr size="10" width="26%" align="left" color="green"><font size="6" color="red" >登录成功 </font><hr size="10" width="26%" align="left" color="green"></body></html>er_login.jsp<%@ page language="java" contentType="text/html; charset=utf-8"pageEncoding="utf-8"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "/TR/html4/loose.dtd"> <html><head><meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"><title>登录界⾯</title></head><body background="C:\Users\win8\workspace\Login\image\9dcbdc339e72a5663b5c289fb5573c13_10.jpg" > <center><br><br><br><br><br><br><h1 style="color:yellow">Login</h1><br><form name="loginForm" action="login_check.jsp" method="post"><table Border="0" ><tr ><td>账号</td><td><input type="text" name="username"></td></tr><tr><td>密码</td><td><input type="password" name="password"></td></tr></table><br><input type="submit" value="登录" style="color:#BC8F8F"></form></center></body></html>运⾏结果截图:。
JAVA web用户登录完整代码
java action:LoginForm form=(LoginForm)actionForm;ActionMessages errors = new ActionMessages();System.out.println(";form.getAction()=";+form.getAction());if (";login";.equals(form.getAction())) {System.out.println(";----------------login--------------";);AuthCodeCookie authCodeCookie = new AuthCodeCookie(request,response);if (!authCodeCookie.getAuthCode().equals(form.getAuthCode())) {//验证码不正确errors.add(";error.login.authcode";, new ActionMessage(";error.login.authcode";));this.saveErrors(request, errors);return mapping.getInputForward();}User user = this.getUserService().get(form.getUserId());if(user==null){errors.add(";er";, new ActionMessage(";er";));this.saveErrors(request, errors);return mapping.getInputForward();}Util util = new Util();if(!util.hash(form.getPassword()).equals(user.getPassword())){errors.add(";error.login.password";, new ActionMessage(";error.login.password";));this.saveErrors(request, errors);return mapping.getInputForward();}// 一旦登录成功,创建sessionHttpSession session = request.getSession();UserSession userSession = new UserSession();userSession.setUser(user);session.setAttribute(ER_SESSION_KEY, userSession);//把UserSession传递到下个页面// 并且修改用户登录时间,登录次数+1user.setLastLoginDate(Util.getCurrentDate(";yyyyMMdd hhmmss";));user.setLoginTimes(Integer.valueOf(user.getLoginTimes().intValue()+1));this.getUserService().update(user);System.out.println(";----------------------------------------------------";) ;// // 获取用户对应的系统应用菜单List allModuleList = this.getModuleService().getModuleTree(Integer.parseInt(user.getMenuLevel()));//0代表根菜单// List allModuleList = this.getModuleService().getModuleTree(1);//0代表主菜单// System.out.println(";allModuleList.size=";+allModuleList.size()); // for(int i=0;i<;allModuleList.size();i++){//System.out.println(";";+((Module)allModuleList.get(i)).getModuleName());// }Iterator menu = allModuleList.iterator();Vector parentV = new Vector();Vector childV = new Vector();Module m;while (menu.hasNext()) {m = (Module) menu.next();if(user.getPermission().indexOf(";[";+m.getId()+";]";)!=-1){if (m.getParentId().intValue() == 0) {parentV.add(m);} else {childV.add(m);}}}request.getSession().setAttribute(";parentVector";, parentV);request.getSession().setAttribute(";childVector";, childV);System.out.println(";初始化完毕";);return mapping.findForward(";userPanel";);}jsp:<;%@ page contentType=";text/html;charset=UTF-8";%>;<;%@ taglib uri=";/WEB-INF/struts-bean.tld"; prefix=";bean";%>;<;%@ taglib uri=";/WEB-INF/struts-html.tld"; prefix=";html";%>;<;%@ taglib uri=";/WEB-INF/struts-logic.tld"; prefix=";logic";%>;<;jsp:useBean id=";user_session"; scope=";session";type=";erSession"; />;<;%er user = null;if (user_session != null)user = user_session.getUser();//根据权限获得菜单,这里权限用Telephone替代一下先String str = user.getTelephone();%>;<;html>;<;head>;<;meta http-equiv=";Content-Type"; content=";text/html; charset=UTF-8";>;<;title>;LEFT<;/title>;<;link rel=";stylesheet"; href=";css/style.css"; type=";text/css";>;<;script language=";JavaScript";>;<;!--function doExit(){if (confirm(";您确定要退出帐单门户系统吗?";)){window.open(";login.portal?action=logout";,";_parent";,";";);}}//-->;<;/script>;<;script language=";JavaScript";>;var w=200;function closenavi() {w-=200;if (w>;-10) {window.parent.testframeset.cols = ''+w+',*';repeat=setTimeout(";closenavi()";,10);}else {clearTimeout(repeat);w=200;}}function loginOutPage() {document.forms[1].SIGN_OFF.click();}function initIt(){divCount = document.all.tags(";DIV";);for (i=0; i<;divCount.length; i++) {obj = divCount(i);if (obj.className == ";child"; || obj.className == ";child1";) obj.style.display = ";none";;}}function expandIt(el) {obj = eval(";page"; + el);obj2 = eval(";main"; + el);if (obj.style.display == ";none";) {obj.style.display = ";block";;}else {obj.style.display = ";none";;}}onload = initIt;var judge=0;function expandall(o) {if (judge==0) {divCount2 = document.all.tags(";DIV";);for (i=0; i<;divCount2.length; i++) {obj2 = divCount2(i);if (obj2.className == ";child"; || obj.className == ";child1"; || obj2.style.display == ";none";){obj2.style.display = ";block";;}if (obj2.className == ";menu";){//obj2.all.tags('img')[0].src='images/treeimg/tminus.gif';obj2.all.tags('img')[0].src='images/openfolder1.gif';}}judge=1;o.src='images/icon-closeall.gif';o.alt='全部折叠';}else {divCount2 = document.all.tags(";DIV";);for (i=0; i<;divCount2.length; i++) {obj2 = divCount2(i);if (obj2.className == ";child"; || obj.className == ";child1"; || obj2.style.display == ";block";){obj2.style.display = ";none";;}if (obj2.className == ";menu";){obj2.all.tags('img')[0].src='images/folder1.gif';}}judge=0;o.src='images/icon-expandall.gif';o.alt='全部展开';}}function quit(form) {window.close()}function loginOutPage() {document.forms[0].SIGN_OFF.click();}<;/script>;<;/head>;<;body bgcolor=";#D8DADA"; class=";bodyTop";>;<;center>;<;table width=";161"; border=";0"; cellspacing=";0"; cellpadding=";0";>;<;tr>;<;td>;<;table style=";margin-top: 10px; margin-bottom: 10px"; width=";138";border=";0"; align=";center"; cellpadding=";0"; cellspacing=";0";>;<;tr>;<;td>;<;img src=";images/001.jpg"; width=";138"; height=";6";>;<;/td>;<;/tr>;<;tr>;<;td class=";msBack";>;<;table width=";130"; border=";0"; align=";center"; cellpadding=";3";cellspacing=";0";>;<;tr>;<;td width=";19";>;<;img src=";images/em44.gif"; width=";19"; height=";19";>;<;/td>;<;td class=";message";>;您有新的帐单信息<;/td>;<;/tr>;<;tr>;<;td>;<;img src=";images/em44.gif"; width=";19"; height=";19";>;<;/td>;<;td class=";message";>;您有新的支付信息<;/td>;<;/tr>;<;/table>;<;/td>;<;/tr>;<;tr>;<;td>;<;img src=";images/002.jpg"; width=";138"; height=";6";>;<;/td>;<;/tr>;<;/table>;<;/td>;<;/tr>;<;/table>;<;logic:iterate id=";module"; name=";parentVector";type=";com.worthtech.billportal.bean.Module";indexId=";index";>;<;%int i = ((ng.Integer) pageContext.findAttribute(";index";)).intValue();%>;<;div id=<;%=";main"; + i%>; class=";title";onClick=";expandIt(<;%=";"; + i%>;); return false";>;<;%if(str.indexOf(";[";+module.getId()+";]";)!=-1){%>;<;table class=";TableLeftTop"; style=";margin-top: 10px"; width=";138";border=";0"; cellspacing=";0"; cellpadding=";4";>;<;tr>;<;td background=";images/LeftMenuBack.jpg";>;<;div align=";center";>;<;%=module.getModuleName()%>;<;/div>;<;/td>;<;/tr>;<;/table>;<;%}%>;<;/div>;<;div id=<;%=";page"; + i%>; class=";child";>;<;table class=";TableLeftView"; width=";170"; border=";0"; cellspacing=";0";cellpadding=";0";>;<;logic:iterate id=";childModule"; name=";childVector";type=";com.worthtech.billportal.bean.Module";>;<;%if(str.indexOf(";[";+childModule.getId()+";]";)!=-1&;&;childModule.getParent ID().intValue()==module.getId().intValue()){%>;<;tr>;<;td width=";44";>;<;div align=";right";>;<;img src=";images/t.gif"; width=";19"; height=";20";>;<;/div>;<;/td>;<;td width=";161";>;<;a href=<;%=childModule.getActionURL()%>; target=";mainFrame";>;<;%=childModule.getModuleName()%>;<;/a>;<;/td>;<;/tr>;<;%}%>;<;/logic:iterate>;<;/table>;<;/div>;<;/logic:iterate>;<;table style=";margin-top: 10px"; width=";161"; border=";0";cellspacing=";0"; cellpadding=";2";>;<;tr>;<;td>;<;table width=";141"; border=";0"; align=";center"; cellpadding=";2";cellspacing=";0";>;<;tr>;<;td>;<;div align=";center";>;<;a href=";#"; onclick=";doExit();";>;<;imgsrc=";images/ico01.gif";width=";65"; height=";15"; border=";0";class=";MouseOver";>; <;/a>;<;/div>;<;/td>;<;td>;<;div align=";center";>;<;ahref=";user.portal?action=password";target=";mainFrame";>;<;imgclass=";MouseOver";src=";images/ico02.gif";width=";65"; height=";15"; border=";0";>;<;/a>;<;/div>;<;/td>;<;/tr>;<;/table>;<;/td>;<;/tr>;<;/table>;<;/center>;<;/body>;<;/html>;。
javaWeb项目实现简单的登录注册
JavaWeb项目实现登录注册一.电脑,eclipse,tomcat,mysql数据库数据库连接架包二.项目开始1.打开eclipse创建一个新的JavaWeb项目,将下载的数据库连接架包放到WebContent 目录下的WEB-INFO中的lib下,右键加入构建路劲。
2.在WebContent下新建一个login.jsp的登录页面代码如下:<%@page language="java"contentType="text/html; charset=UTF-8"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""/TR/html4/loose.dtd"><html><head><base href="<%=basePath%>"><!--可以在所有获取静态资源地方自动加上根路径,这样就一定能获取到静态资源了 --><meta http-equiv="Content-Type"content="text/html; charset=UTF-8"><title>登录页面</title><link rel="stylesheet"type="text/css"href="css/bootstrap.css"/><script type="text/javascript"src="js/jquery-3.4.1.js"></script></head><body style="background-color: #ccc"><center><h1>登录页面</h1><font color="blue">${message}</font><font color="red"id="info"></font><form class="form-inline"action="<%=basePath%>UserServlet?infos=login"method="post"><div class="form-group"><label for="exampleInputName2">账号</label><input type="text"class="form-control"name="username"id="username"placeholder="请输入账号"> </div><br/><div class="form-group"><label for="exampleInputEmail2">密码</label><input type="password"class="form-control" name="password"id="password"placeholder="请输入密码"> </div><br/><input type="submit"value="立即登录"class="btn btn-default"></form><a href="<%=basePath%>register.jsp">没有注册?去注册</a></center></body></html>3.创建注册界面register.jsp代码如下:<%@page language="java"contentType="text/html; charset=UTF-8"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""/TR/html4/loose.dtd"><html><head><base href="<%=basePath%>"><!--可以在所有获取静态资源地方自动加上根路径,这样就一定能获取到静态资源了 --><meta http-equiv="Content-Type"content="text/html; charset=UTF-8"><title>登录页面</title><link rel="stylesheet"type="text/css"href="css/bootstrap.css"/><body style="background-color: #ccc"><center><h1>注册页面</h1><font color="blue"><ahref="<%=basePath%>login.jsp">${message}</a></font> <font color="red"id="info"></font><form class="form-inline"action="<%=basePath%>UserServlet?infos=register" method="post"><div class="form-group"><label for="exampleInputName2">账号</label><input type="text"class="form-control" name="username"id="username"placeholder="请输入账号"> </div><br/><div class="form-group"><label for="exampleInputEmail2">密码</label><input type="password"class="form-control" name="password"id="password"placeholder="请输入密码"> </div><br/><div class="form-group"><label for="exampleInputEmail2">确认密码<input type="password"class="form-control" name="codepassword"id="codepassword"placeholder="请输入密码"></div><br/><input type="submit"value="立即注册"class="btn btn-default"></form></center></body></html>4.创建登录成功的界面,系界面需要显示出登录成功用户的信息,包括账户和密码代码如下:<%@page language="java"contentType="text/html; charset=UTF-8"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""/TR/html4/loose.dtd"><html><head><base href="<%=basePath%>"><!--可以在所有获取静态资源地方自动加上根路径,这样就一定能获取到静态资源了 --><meta http-equiv="Content-Type"content="text/html; charset=UTF-8"><title>主页面</title><script type="text/javascript"src="js/jquery-3.4.1.js"></script></head><body style="background-color: #ccc"><center><label>${ername}</label><br><label>${user.password}</label><br></center></body></html>5.编写数据库配置文件JDBC. propertiesdriver=com.mysql.jdbc.Driverurl=jdbc:mysql://localhost:3306/pc(数据库名字)username=root(数据库账户)password=root(数据库密码)6.创建数据库连接工具代码如下:package com.fs.ss.utils; import java.io.IOException; import java.io.InputStream; import java.sql.Connection; import java.sql.DriverManager; importjava.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Properties;public class DBConMysql {static Properties p = null; public final static DBConMysql dbm = new DBConMysql();private DBConMysql(){}public static DBConMysql getDbm(){return dbm;}static{InputStream in= DBConMysql.class.getClassLoader().getResourceAsStream("JDBC.pr operties");p = new Properties();try {p.load(in);} catch (IOException e) {e.printStackTrace();}finally {try {in.close();} catch (IOException e) {e.printStackTrace();}}}public Connection getCon(){try {Class.forName(p.getProperty(" driver"));Connection con;try {con = DriverManager.getConnection(p.g etProperty("url"),p.getProperty("username"),p.getProperty("password"));return con;} catch (SQLException e) {e.printStackTrace();}} catch (ClassNotFoundException e) {e.printStackTrace();}return null;}public static void main(String[] args) {System.out.println(DBConMysql .getDbm().getCon());}public void closeStatement(Statement st){ try {if(st!=null){st.close();}} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}}public voidclosePreparedStatement(Prepared Statement ps){try {if(ps!=null){ps.close();}} catch (SQLException e) {e.printStackTrace();}}public void closeResultSet(ResultSet rs){ try {if(rs!=null){rs.close();}} catch (SQLException e) {e.printStackTrace();}}}可以运行测试是否连接上了数据库,连接成功会在控制台打印出数据库连接字符串7.完成数据库操作和实现注册登录功能User代码:package com.fs.ss.model;import java.io.Serializable;public class implements Serializable{private String username;private String password;public User(){}public User(String username,String password){ ername = username;this.password = password;}public String getUsername() {return username;}public void setUsername(String username) {ername = username;}public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}@Overridepublic String toString() {return"User [username="+ username+ ", password=" + password + "]";}}UserDao代码:package com.fs.ss.dao;import java.sql.Connection; importjava.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List;import er; importcom.fs.ss.utils.DBConMysql; public class UserDao { Connection con = DBConMysql.getDbm().getCon();PreparedStatement ps = null; Statement sm = null; ResultSet rs = null;/*** 插入数据* @param user* @return*/public int insertUser(User user){try {con.setAutoCommit(false);ps = con.prepareStatement("insert into user values(?,?)");ps.setString(1,user.getUsername());ps.setString(2,user.getPassword());int i = ps.executeUpdate();mit();return i;} catch (SQLException e) {try {con.rollback();} catch (SQLException e1) {// TODO Auto-generated catch blocke1.printStackTrace();}}finally{if(ps!=null){ DBConMysql.getDbm().closePrep aredStatement(ps);}}return 0;}/*** 查询所有用户信息* @return*/public List<User> queryAllUsers(){ArrayList<User> users = new ArrayList<>();try {sm = con.createStatement();rs = sm.executeQuery("select * from user");while(rs.next()){User user = new User(rs.getString(1),rs.getString(2));users.add(user);}return users;} catch (SQLException e) {e.printStackTrace();}finally {if(sm!=null){ DBConMysql.getDbm().closeStat ement(sm);}}return null;}/*** 按username来查询用户* @param username* @return*/public User queryUserByUsername(String username) {try {ps = con.prepareStatement("select * from user where username=?");ps.setString(1, username);rs = ps.executeQuery();if(rs.next()){User user = new User(rs.getString(1),rs.getString(2));return user;}else{return null;}} catch (SQLException e) {e.printStackTrace();}finally {if(ps!=null){ DBConMysql.getDbm().closePrep aredStatement(ps);}}return null;}}UserService代码:package com.fs.ss.service; import erDao; import er; public class UserService { UserDao userDao = new UserDao(); public UserqueryByUsername(String username) {// TODO Auto-generated method stubreturnuserDao.queryUserByUsername(use rname);}public int insertUsername(User user) {// TODO Auto-generated method stubreturnuserDao.insertUser(user);}}UserServlet代码:package com.fs.ss.service; import erDao;import er; public class UserService { UserDao userDao = new UserDao(); public User queryByUsername(String username) {// TODO Auto-generated method stubreturnuserDao.queryUserByUsername(use rname);}public int insertUsername(User user) {// TODO Auto-generated method stubreturnuserDao.insertUser(user);}}UserServlet代码:package com.fs.ss.controller;import java.io.IOException; import java.io.PrintWriter; import java.util.List;importjavax.servlet.ServletException; importjavax.servlet.annotation.WebSer vlet;importjavax.servlet.http.HttpServlet; importjavax.servlet.http.HttpServletR equest;importjavax.servlet.http.HttpServletResponse;import er; importerService; @WebServlet("/UserServlet") public class UserServlet extends HttpServlet{/** */private static final long serialVersionUID = 1L;@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //设置编码req.setCharacterEncoding("utf -8");resp.setContentType("text/htm l;charset=utf-8");//拿到方法String infos = req.getParameter("infos");UserService userService = new UserService();/*** 登录*/if(infos.equals("login")){//拿到输入框的值String username = req.getParameter("username");String password = req.getParameter("password");User user = userService.queryByUsername(use rname);//判断输入框的值与注册的是否匹配if(user.getUsername().equals( username) && user.getPassword().equals(passw ord)){//账户和密码匹配//将用户信息存储到请求头,方便再成功页面显示用户信息req.setAttribute("user",user) ;//重定向到success.jsp页面req.getRequestDispatcher("/in dex.jsp").forward(req, resp);}else{if(user.getUsername()==null){//用户不存在req.setAttribute("message","用户不存在!");req.getRequestDispatcher("/lo gin.jsp").forward(req, resp);}elseif(!user.getPassword().equals(p assword)){//密码不匹配req.setAttribute("message","密码错误!");req.getRequestDispatcher("/lo gin.jsp").forward(req, resp);}}}/*** 注册*/if(infos.equals("register")){ //拿到输入框的值String username = req.getParameter("username");String password = req.getParameter("password");String codepassword = req.getParameter("codepassword" );if(codepassword.equals(passwo rd)){User user = new User(username,password);int i =userService.insertUsername(user );req.setAttribute("message","注册成功!请登录");req.getRequestDispatcher("/re gister.jsp").forward(req, resp);}else{req.setAttribute("message","注册失败!");req.getRequestDispatcher("/re gister.jsp").forward(req, resp);}}}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throwsServletException, IOException { doGet(req, resp);}}三.运行项目,在浏览器中访问项目效果图:这是登录页面,先点击注册进行注册一个账号,我们以0000,0000为例这是注册界面,输入账号,密码,确认密码后点击注册提示注册成功,请登录信息说明注册完成,点击回到登录页面输入用户,密码,登录登录成功显示用户信息到此,我们简单的注册登录已经完成。
用java写一个登陆注册界面代码
用java写一个登陆注册界面代码Java程序如下:importjava.awt.GridLayout;importjava.awt.event.ActionEvent; importjava.awt.event.ActionListener;importjava.util.ArrayList;importjava.util.List;importjavax.swing.JButton;importjavax.swing.JFrame;importjavax.swing.JLabel;importjavax.swing.JOptionPane;importjavax.swing.JPasswordField;importjavax.swing.JTextField;//登录窗体类publicclassMainextendsJFrameimplementsActionListener,Runnab le{privatestaticfinallongserialVersionUID=1L;protectedJLabellblPrompt,lblTime,lblUserName,lblPassword ;protectedJTextFieldtxtUserName;protectedJPasswordFieldtxtPassword;protectedJButtonbtnLogin,btnRegister;protectedstaticThreadthread=null; publicstaticvoidmain(String[]args){Data.init();MainfrmLogin=newMain();thread=newThread(frmLogin);thread.start();}publicMain(){super(用户登录);initComponent();}//初始化控件publicvoidinitComponent(){lblPrompt=newJLabel(登录剩余时间(秒):);lblTime=newJLabel(60);lblUserName=newJLabel(用户名:);lblPassword=newJLabel(密码:);txtUserName=newJTextField(10);txtPassword=newJPasswordField(10);btnLogin=newJButton(登录);btnRegister=newJButton(注册);btnLogin.addActionListener(this);btnRegister.addActionListener(this);this.setLayout(newGridLayout(4,2));this.add(lblPrompt);this.add(lblTime);this.add(lblUserName);this.add(txtUserName);this.add(lblPassword);this.add(txtPassword);this.add(btnLogin);this.add(btnRegister);txtUserName.setFocusable(true);this.setSize(400,200);this.setVisible(true);}@OverridepublicvoidactionPerformed(ActionEvente){JButtonbtn=(JButton)e.getSource();if(btn==btnLogin){if(txtUserName.getText().equals()||txtUserName.getText() .trim().equals()){JOptionPane.showMessageDialog(this,用户名不能为空!,登录失败,JOptionPane.ERROR_MESSAGE);return;}if(txtPassword.getText().equals()){JOptionPane.showMessageDialog(this,登录密码不能为空!,登录失败,JOptionPane.ERROR_MESSAGE);return;}StringuserName=null;Stringpassword=null;userName=txtUserName.getText().trim();password=txtPassword.getText();inti;for(i=0;iData.customers.size();i++){if(Data.customers.get(i).getUserName().equals(userName)& amp;&Data.customers.get(i).getPassword().equals(passwor d)){break;}}if(iData.customers.size()){JOptionPane.showMessageDialog(this,欢迎您,+userName,登录成功,RMATION_MESSAGE);}else{JOptionPane.showMessageDialog(this,登录失败,请检查用户名和密码是否正确......,登录失败,JOptionPane.ERROR_MESSAGE);}}elseif(btn==btnRegister){this.dispose();newRegister();}}@Overridepublicvoidrun(){while(true){try{Thread.sleep(1000);intnum=Integer.valueOf(lblTime.getText());if(num=0){JOptionPane.showMessageDialog(this,时间到,窗口即将关闭!,登录失败,RMATION_MESSAGE);System.exit(0);}else{num--;}lblTime.setText(String.valueOf(num));}catch(Exceptione){e.printStackTrace();}}}}//用户注册窗体类classRegisterextendsJFrameimplementsActionListener{ privatestaticfinallongserialVersionUID=1L;protectedJLabellblUserName,lblPassword,lblConfirmedPassw ord;protectedJTextFieldtxtUserName;protectedJPasswordFieldtxtPassword,txtConfirmedPassword;protectedJButtonbtnRegister,btnReset;publicRegister(){super(用户注册);initComponent();}//初始化控件publicvoidinitComponent(){lblUserName=newJLabel(用户名:);lblPassword=newJLabel(密码:);lblConfirmedPassword=newJLabel(确认密码:);txtUserName=newJTextField(10);txtPassword=newJPasswordField(10);txtConfirmedPassword=newJPasswordField(10);btnReset=newJButton(重置);btnRegister=newJButton(注册);btnReset.addActionListener(this);btnRegister.addActionListener(this);this.setLayout(newGridLayout(4,2));this.add(lblUserName);this.add(txtUserName);this.add(lblPassword);this.add(txtPassword);this.add(lblConfirmedPassword);this.add(txtConfirmedPassword);this.add(btnRegister);this.add(btnReset);txtUserName.setFocusable(true);this.setSize(400,200);this.setVisible(true);}@OverridepublicvoidactionPerformed(ActionEvente){JButtonbtn=(JButton)e.getSource();if(btn==btnRegister){if(txtUserName.getText().equals()||txtUserName.getText() .trim().equals()){JOptionPane.showMessageDialog(this,用户名不能为空!,注册失败,JOptionPane.ERROR_MESSAGE);return;}if(txtPassword.getText().equals()){JOptionPane.showMessageDialog(this,登录密码不能为空!,注册失败,JOptionPane.ERROR_MESSAGE);return;}if(txtConfirmedPassword.getText().equals()){JOptionPane.showMessageDialog(this,确证密码不能为空!,注册失败,JOptionPane.ERROR_MESSAGE);return;}if(!txtConfirmedPassword.getText().equals(txtPassword.ge tText())){JOptionPane.showMessageDialog(this,两次密码必须一致!,注册失败,JOptionPane.ERROR_MESSAGE);return;}StringuserName=null;Stringpassword=null;inti;userName=txtUserName.getText().trim();password=txtPassword.getText();for(i=0;iData.customers.size();i++){if(Data.customers.get(i).getUserName().equals(userName)) {break;}}if(iData.customers.size()){JOptionPane.showMessageDialog(this,该用户名已经被注册,请选用其他用户名!,注册失败,JOptionPane.ERROR_MESSAGE);}else{Data.customers.add(newCustomer(userName,password));JOptionPane.showMessageDialog(this,恭喜+userName+注册成功,请牢记您的用户名和密码。
JavaWeb登陆功能实现代码
JavaWeb登陆功能实现代码本⽂实例为⼤家分享了JavaWeb登陆功能的⽅法,供⼤家参考,具体内容如下⾸先我们要JavaWeb登陆的基本流程:JSP页⾯发送请求——>Servlet——>Servlet通过调⽤⽅法从数据库中得到数据并将结果返回页⾯。
我们先建⽴三个jsp页⾯,包括login.jsp(登陆页⾯)、index.jsp(显⽰登陆成功后的信息)、error.jsp(登录失败的页⾯),其中后两个页⾯的内容可以随意写,⽽login.jsp页⾯的主要内容如下:<form action="LoginServlet" method="post">⽤户名:<input type="text" name="userName"/>密码:<input type="password" name="password"/><input type="submit" value="提交"/></form>在login.jsp⽂件的开头我们需要将pageEncoding="ISO-8859-1"改为pageEncoding="utf-8"(同时不要忘记设置开发⼯具的编码格式,不然jsp页⾯会显⽰乱码)根据⽤户名和密码两个属性我们建⽴相应的实体类,并添加get和set⽅法,代码如下:public class User {private String userName;private String password;public String getUserName() {return userName;}public void setUserName(String userName) {erName = userName;}public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}}⽽jsp页⾯中的action=“LoginServlet”是指将请求发送到Servlet处理。
用户登录界面代码
系统入口类中这样:LoginFrame lf=new LoginFrame();lf.setVisible(true);LoginFrame 中,按钮“OK”的监听事件这样:……//连接数据库,并验证用户名和密码if(success)//验证成功MainFrame mf=new MainFrame();mf.setVisible(true);dispose(); //销毁LoginFrameelse提示错误信息2import javax.swing.*;import java.awt.*;import java.awt.event.*;//下面代码创建JFrame框架窗体class FrameTest extends JFrame{public FrameTest(){super("客户登录");setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);setVisible(true);setSize(406,195);}}//下面代码创建JPanel面板,并将面板添加到框架窗体class PanelTest extends FrameTest{JPanel panelObj;public PanelTest(){panelObj=new JPanel();getContentPane().add(panelObj);}}//下面代码创建javax.swing控件,并将控件添加到面板class ComponentTest extends PanelTest //构造组件类{JLabel labelName; //姓名JLabel labelMima; //密码JTextField textName; //文本框JTextField textMima; //文本框JButton buttonObj1; //确定按钮JButton buttonObj2; //重置按钮public ComponentTest(){labelName =new JLabel("姓名 ");labelMima =new JLabel("密码 ");textName =new JTextField(25);textMima =new JTextField(15);buttonObj1 =new JButton("确定");buttonObj2 =new JButton("重置");buttonObj1.setEnabled(true); //使能buttonObj2.setEnabled(false); //不使能panelObj.add(labelName);panelObj.add(textName);panelObj.add(labelMima);panelObj.add(textMima);panelObj.add(buttonObj1);panelObj.add(buttonObj2);}}//下面代码创建GridBagLayout布局管理器,并将布局应用到面板class LayoutManagerTest extends ComponentTest //构造布局类{GridBagLayout gbLayoutObj;GridBagConstraints gbcObj;public LayoutManagerTest(){gbLayoutObj=new GridBagLayout();gbcObj=new GridBagConstraints();panelObj.setLayout(gbLayoutObj);gbcObj.anchor=GridBagConstraints.EAST;gbcObj.gridx=1;gbcObj.gridy=1;gbLayoutObj.setConstraints(labelName,gbcObj);gbcObj.gridy=2;gbLayoutObj.setConstraints(labelMima,gbcObj);gbcObj.gridy=3;gbLayoutObj.setConstraints(buttonObj1,gbcObj);gbcObj.anchor=GridBagConstraints.WEST;gbcObj.gridx=2;gbcObj.gridy=1;gbLayoutObj.setConstraints(textName,gbcObj);gbcObj.gridy=2;gbLayoutObj.setConstraints(textMima,gbcObj);gbcObj.gridy=3;gbLayoutObj.setConstraints(buttonObj2,gbcObj);}}class EventTest extends LayoutManagerTest{ButtonEvent bEObj;public EventTest(){bEObj=new ButtonEvent(); //创建事件类对象buttonObj1.addActionListener(bEObj); //注册监听器buttonObj2.addActionListener(bEObj); //注册监听器}class ButtonEvent implements ActionListener{public void actionPerformed(ActionEvent e){Object obj=e.getSource();Object[] options={" 确定 "," 取消 "};if(obj==buttonObj1){String strObj1=textName.getText();String strObj2=textMima.getText();String str1=new String("警告!姓名不能为空.");String str2=new String("警告!密码不能为空.");//if(strObj1.length()==0||strObj2.length()==0)// {if(strObj1.length()==0){ //String str1=new String("警告!姓名不能为空.");JOptionPane.showOptionDialog(null,str1,"警告窗口!",JOptionPane.DEFAULT_OPTION,JOptionPane.WARNING_MESSAGE,null,options,o ptions[0]);return;}else{if(strObj2.length()==0){ // String str2=new String("警告!密码不能为空.");JOptionPane.showOptionDialog(null,str2,"警告窗口!",JOptionPane.DEFAULT_OPTION,JOptionPane.WARNING_MESSAGE,null,options,o ptions[0]);return;}// }// }else{String str3=new String("文本框内容是:\n姓名:"+strObj1+"\n密码"+strObj2);JOptionPane.showOptionDialog(null,str3,"确定窗口!", JOptionPane.DEFAULT_OPTION,RMATION_MESSAGE,null,optio ns,options[0]);buttonObj1.setEnabled(false);buttonObj2.setEnabled(true);}}}if(obj==buttonObj2){buttonObj2.setEnabled(false);buttonObj1.setEnabled(true);textName.setText("");textMima.setText("");String str1=new String("你单击了\" 重置(E) \",清空文本框。
java 网页设计 实现用户登陆
Login项目结构:1、/*创建一个数据库*/create database Myusers character set UTF8; /*创建用户表*/create table users(id varchar(32) primary key,name varchar(20),pwd varchar(20));/*初始化数据*/insert into users values(001,'李潇',123); insert into users values(002,'Jack',111); insert into users values(003,'Rose',222); 结果:2、准备index.jsp页面<%@page language="java"contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%><!DOCTYPE html PUBLIC"-//W3C//DTD HTML 4.01 Transitional//EN" "/TR/html4/loose.dtd"><script type="text/javascript">function check(){var nm = document.getElementsByName("name")[0].value;nm = nm.trim();if(nm==""){alert("请输入用户名");document.getElementsByName("name")[0].focus();return false;}var pwd = document.getElementsByName("pwd")[0].value;pwd = pwd.trim();if(pwd==""){alert("请输入密码 ");document.getElementsByName("pwd")[0].focus();return false;}http.send("name="+nm+"pwd="+pwd);//发出数据}</script><html><head><meta http-equiv="Content-Type"content="text/html;charset=UTF-8"><title>Insert title here</title></head><body><form action="LoginServlet"method="post"><table border="0"align="center"cellpadding="2" cellspacing="0"><tr align="center"><td height="30"colspan="2"style="border-bottom:1px; color: blue"><strongstyle="font-size: 14px;">请登录</strong></td> </tr><tr><td height="30"nowrap><fontcolor="000F60"><strong>用户名:</strong></font></td><td><input type="text"name="name"style="width: 160px;" /></td></tr><tr><td height="30"nowrap><strong><fontcolor="000F60">密码:</font></strong></td><td><input type="password"name="pwd"style="width: 160px;" /></td></tr><tr><td height="30"nowrap colspan="2"><strong><fontcolor="red"></font></strong></td></tr><tr><td height="30"></td><td><input type="submit"onclick="check()"value="登录"/><input type="reset"value="重置"/></td></tr></table></form></body></html>运行结果:3、Loginselvlet处理用户登录信息,若登录成功则显示到succ.jsp页面上,某则重新登录public class LoginServlet extends HttpServlet {private static final long serialVersionUID = 1L;private LoginService service = new LoginService();protected void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {request.setCharacterEncoding("UTF-8");response.setContentType("text/html;charset=UTF-8");PrintWriter out = response.getWriter();String name = request.getParameter("name");String pwd = request.getParameter("pwd");try {User u = service.select(name, pwd);if (u != null) {System.err.println("succ..");request.getSession().setAttribute("name", name);response.sendRedirect("http://localhost/login/jsp/succ.jsp" );} else {System.err.println("filed..");response.sendRedirect("http://localhost/login/jsp/failed.js p");}} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}}}4、Loginselvlet调用Loginservice,Loginservice再调用loginDao,在dao层调用数据库的数据以下为dao层代码:public class LoginDao {public User select(String name, String pwd) throws Exception {ComboPooledDataSource ds=newComboPooledDataSource("user");QueryRunner run = new QueryRunner(ds);String sql = "select * from users where name=?"+ "and pwd=?";return run.query(sql, new BeanHandler<User>(User.class), name, pwd);}}以下为该项目的运行结果,具体代码见Login项目,导入Eclipse即可1、只输入用户名2、只输入密码3、输入数据库中不存的用户4、输入数据库中存在的用户(李潇/123)。
javaweb系统登陆注册界面关键代码
1、制作企业信息管理系统的登陆页面2.制作企业信息管理系统的注册页面3.使用JavaScript完成登陆页面和注册页面的验证功能,具体要求如下:1)登录页面验证用户名、密码不能为空。
2)注册页面验证:用户名只能由数字和字母组成密码只能由数字或字母组成,长度为6~12位,两次密码必须相同邮箱、电话、邮编格式必须正确4.在各个文本框之后(提示关键词:innerHTML)或者使用小窗口(提示关键词:alert)弹出相应的错误信息/*用户名只能由数字或字母组成*/function User(){var value = document.getElementById("user").value;var curretuser =/^[A-Za-z0-9]+$/;if(curretuser.test(value)){}else{window.alert("请输入字母或者数字!!!");}}/*密码只能由数字或字母组成,长度为6~12位*/function Password(){var value = document.getElementById("password").value;var curretuser = /^[A-Za-z0-9]{6,12}$/;if(curretuser.test(value)){}else{window.alert("错误!密码只能由数字或字母组成,长度为6-12位!!!");}}/*两次密码必须一样*/function TestPassword(){var value = document.getElementById("password").value;var value1 = document.getElementById("password2").value;if(value==value1){}else{window.alert("两次输入的密码必须一样!!!");}}邮箱格式必须正确function Email(){var value = document.getElementById("email").value;var value1 = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;if(value1.test(value)){}else{window.alert("邮箱格式错误!!!");}电话号码必须符合规范function Phone(){var value = document.getElementById("phone").value;var value1 = /^\d{3,4}\-?\d{8}$/;if(value1.test(value)){}else{window.alert("电话号码格式错误!!!");}}邮编书写符合规范function Code(){var value = document.getElementById("code").value;var value1 = /^\d{6}$/;if(value1.test(value)){}else{window.alert("邮编格式错误!!!");}}Login(登录)页面:<style type="text/css">.container {width: 400px;height: 400px;position:relative;}.B{position: absolute; top: 130px; left: 200px; bottom: 250px; right: 100px; } </style><body bgcolor="#52BDFE"><div class="container"><table background="1.jpg" width="700" height="400"><tr><td width="20%"></td><td width="20%"><form></form><td width="9%"></tr></table></div><div class="B"><table bgcolor="#FFFFFF"><tr><td height="30"><font color="#0000CC">请登录!</font></td><td></td></tr><tr><td height="30">*用户名:</td><td><input type="text" name="text1" id="user"></td></tr><tr><td height="30">*密码:</td><td><input type="password" name="password1" id="password" /></td></tr><tr><td height="30">*验证码:</td><td><input type="text" name="text2" id="checknumber" /></td></tr><tr><td height="30"><a href="register.html"><fontcolor="#FF00FF">没账号?去注册</font></a></td><td><input name="button" type="button" value="登录"onClick="User(),Password(),Checknumber()"/></td></tr></table></div>欢迎(首页)界面:<%@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>welcome.jsp</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 type="text/css">.dqwz {position: absolute; top: 120px ; left: 190px;}.welcome {position: absolute; top: 230px ; left: 600px;}.text {position: absolute; top: 300px ; left: 500px;}.picture{position: absolute; top: 390px ; left: 600px;}.end{position: absolute; top: 600px ; left:5px;}</style></head><body><img src="images/lab0401.png"width="1350"height="100"><table cellpadding="5"cellspacing="0"border="0"bgcolor="#D3D3D3"><tr><td width="120"height="1"><li>首页面</li></td><tr><td width="120"height="1"><li>通讯管理</li></td></tr><tr><td width="120"height="1"><ul><li>通讯录管理</li></ul></td>></tr> <tr><td width="120"height="1"><ul><li>短消息管理</li></ul></td></tr> <tr><td width="120"height="1"><li>个人管理</li></td><td></td></tr><tr><td width="120"height="1"><ul><li>日程安排</li></ul></td></tr><tr><td width="120"height="1"><ul><li>工作记录</li></ul></td></tr><tr><td width="120"height="1"><li>企业管理</li></td><td></td></tr><tr><td width="120"height="1"><ul><li>公司公告</li></ul></td></tr><tr><td width="120"height="1"><ul><li>工作会议</li></ul></td></tr><tr><td width="120"height="1"><li>退出</li></td></tr></table><div class="dqwz"><table><p>当前位置:首页面<a href="login02.jsp">【退出】</a></p></table></div><div class="welcome"><table><img src="images/lab0403.PNG"></table></div><div class="text"><table><p><h1>欢迎使用企业信息管理系统</h1></p></table></div><div class="picture"><table><img src="images/lab0402.jpg"width="150"height="150"></table></div><div class="end"><table style="bottom: 300px" height="50"width="1430"><tr><td height="50"colspan="2"align="center"bgcolor="#ADFF2F">Copyright© 1998 - 2015 XX大学XX学院XX班级 All Rights Reserved</td></tr></table></div></body></html>。
Java Web两种登录页面实现方式
public static ResultSet selectALL() throws SQLException{ String sql = "select * from user" ; Connection conn = null; PreparedStatement preStmt = null; conn = DBManager.getConnection(); preStmt = conn.prepareStatement(sql); ResultSet rs = preStmt.executeQuery() ; if (preStmt != null) preStmt.close(); if (conn != null) conn.close(); return rs; } }
4
登陆查询
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub String username = request.getParameter("username") ; String password = request.getParameter("password1") ; Boolean flag = false; try { flag = DaoOperation.select(username,password); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } if(flag){ response.sendRedirect("result.jsp"); }else{ response.sendRedirect("error.jsp"); } }
JavaWeb实现简单登录、注册功能
JavaWeb实现简单登录、注册功能1.⾸先创建⼀个简单的动态Javaweb项⽬2.然后⼿动建⽴⽂件⽬录:项⽬创建好之后,在src下建⼏个包:controller:控制器,负责转发请求,对请求进⾏处理,主要存放servlet;dao:数据库管理,主要是写数据库操作⽅法;model:存放实体类;service:业务逻辑的处理;util:存放⼯具类,在这⾥我主要是把数据库加载驱动和创⽴连接、关闭连接封装成了⼀个静态类。
ps:别忘了在lib⽂件夹⾥放⼊这个jar包,⽤以连接数据库。
3.下⾯直接贴上对应的代码:src代码:1package com.maike.controller;23import java.io.IOException;4import javax.servlet.ServletException;5import javax.servlet.annotation.WebServlet;6import javax.servlet.http.HttpServlet;7import javax.servlet.http.HttpServletRequest;8import javax.servlet.http.HttpServletResponse;910import erService;11import erServiceImpl;1213/**14 * Servlet implementation class RegisterServlet15*/16 @WebServlet("/RegisterServlet")17public class RegisterServlet extends HttpServlet {18 UserService userService = new UserServiceImpl();19private static final long serialVersionUID = 1L;2021/**22 * @see HttpServlet#HttpServlet()23*/24public RegisterServlet() {25super();26// TODO Auto-generated constructor stub27 }2829/**30 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)31*/32protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 33// TODO Auto-generated method stub34 response.getWriter().append("Served at: ").append(request.getContextPath());35 }3637/**38 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)39*/40protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 41// TODO Auto-generated method stub42 request.setCharacterEncoding("utf-8");43 String userName = request.getParameter("userName");44 String userPwd = request.getParameter("userPwd");45 String userRePwd = request.getParameter("userRePwd");4647int k = userService.insertUser(userName,userPwd,userRePwd);4849if(k > 0) {50 request.getRequestDispatcher("login.jsp").forward(request, response);51 }else {52 request.getRequestDispatcher("register.jsp").forward(request, response);53 }54 }5556 }RegisterServlet1package com.maike.controller;23import java.io.IOException;4import javax.servlet.ServletException;5import javax.servlet.annotation.WebServlet;6import javax.servlet.http.HttpServlet;7import javax.servlet.http.HttpServletRequest;8import javax.servlet.http.HttpServletResponse;910import erService;11import erServiceImpl;1213/**14 * Servlet implementation class LoginServlet15*/16 @WebServlet("/LoginServlet")17public class LoginServlet extends HttpServlet {18 UserService userService = new UserServiceImpl();19private static final long serialVersionUID = 1L;2021/**22 * @see HttpServlet#HttpServlet()23*/24public LoginServlet() {25super();26// TODO Auto-generated constructor stub27 }2829/**30 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)31*/32protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 33// TODO Auto-generated method stub34 response.getWriter().append("Served at: ").append(request.getContextPath());35 }3637/**38 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)39*/40protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 41// TODO Auto-generated method stub42 request.setCharacterEncoding("utf-8");43 String userName = request.getParameter("userName");44 String uesrPwd = request.getParameter("userPwd");4546int k = userService.judgeLogin(userName,uesrPwd);47if(k > 0) {48 request.getRequestDispatcher("success.jsp").forward(request, response);49 }else {50 request.getRequestDispatcher("login.jsp").forward(request, response);51 }52 }5354 }LoginServlet1package com.maike.dao;23import er;45public interface UserDao {67int insert(String userName,String userPwd);8 User selectByName(String userName);910 }UserDao1package com.maike.dao;23import java.sql.Connection;4import java.sql.PreparedStatement;5import java.sql.ResultSet;6import java.sql.SQLException;78import er;9import com.maike.util.ConnectionUtil;1011public class UserDaoImpl implements UserDao {12 Connection con = null;13 PreparedStatement pt = null;14 ResultSet rs = null;15 String sql;1617 @Override18public int insert(String userName, String userPwd) {19// TODO Auto-generated method stub20int k = 0;21 sql = "insert into user value(null,?,?)";22try {23 con = ConnectionUtil.getConnection();24 pt = con.prepareStatement(sql);25 pt.setString(1, userName);26 pt.setString(2, userPwd);27 k = pt.executeUpdate();28 } catch (SQLException e) {29// TODO Auto-generated catch block30 e.printStackTrace();31 }finally {32 ConnectionUtil.closeRe(con, pt);33 }34return k;35 }3637 @Override38public User selectByName(String userName) {39// TODO Auto-generated method stub40 sql = "select * from user where user_name = ?";41 User user = new User();42try {43 con = ConnectionUtil.getConnection();44 pt = con.prepareStatement(sql);45 pt.setString(1, userName);46 rs = pt.executeQuery();4748while(rs.next()) {49 user.setUserId(rs.getInt("user_id"));50 user.setUserName(rs.getString("user_name"));51 user.setUserPwd(rs.getString("user_pwd"));52 }53 } catch (SQLException e) {54// TODO Auto-generated catch block55 e.printStackTrace();56 }finally {57 ConnectionUtil.closeRe(con, pt, rs);58 }59return user;60 }6162 }UserDaoImpl1package com.maike.model;23public class User {45private int userId;67private String userName;89private String userPwd;1011public int getUserId() {12return userId;13 }1415public void setUserId(int userId) {erId = userId;17 }1819public String getUserName() {20return userName;21 }2223public void setUserName(String userName) {erName = userName;25 }2627public String getUserPwd() {28return userPwd;29 }3031public void setUserPwd(String userPwd) {erPwd = userPwd;33 }3435 @Override36public String toString() {37return "User [userId=" + userId + ", userName=" + userName + ", userPwd=" + userPwd + "]";38 }3940 }User1package com.maike.service;23public interface UserService {45int insertUser(String userName,String userPwd,String userRePwd);6int judgeLogin(String userName,String userPwd);78 }UserService1package com.maike.service;23import erDao;4import erDaoImpl;5import er;67public class UserServiceImpl implements UserService {8 UserDao userDao = new UserDaoImpl();910/**11 * insertUser: 实现注册功能.<br/>12*/13 @Override14public int insertUser(String userName, String userPwd, String userRePwd) {15// TODO Auto-generated method stub16int k = 0;17if(userName == "" || userName == null || userPwd == "" || userRePwd == null) {18return k;19 }20if(!userPwd.equals(userRePwd)) {21return k;22 }2324 k = userDao.insert(userName,userPwd);2526return k;27 }2829/**30 * judgeLogin:登录判断 .<br/>31*/32 @Override33public int judgeLogin(String userName, String userPwd) {34// TODO Auto-generated method stub35int k = 0;36if(userName == "" || userName == null || userPwd == ""|| userPwd == null) {37return k;38 }39 User user = userDao.selectByName(userName);4041if(!userPwd.equals(user.getUserPwd())) {42 k = 0;43 }else {44 k = 1;45 }46return k;47 }4849 }1package com.maike.util;23import java.sql.Connection;4import java.sql.DriverManager;5import java.sql.PreparedStatement;6import java.sql.ResultSet;7import java.sql.SQLException;89public class ConnectionUtil {10private static String url = "jdbc:mysql://127.0.0.1/nanfeng?characterEncoding=utf8&useSSL=true"; 11private static String rootName = "root";12private static String rootPwd = "zz201608";1314private ConnectionUtil() {};1516static {17try {18/*加载驱动*/19 Class.forName("com.mysql.jdbc.Driver");20 } catch (ClassNotFoundException e) {21// TODO Auto-generated catch block22 e.printStackTrace();23 }24 }2526/**27 * getConnection:创建连接.<br/>28 * @return29 * @throws SQLException30*/31public static Connection getConnection() throws SQLException {32return DriverManager.getConnection(url,rootName,rootPwd);33 }3435/**36 * closeRe:关闭连接.<br/>37 * @param con38 * @param pt39 * @param rs40*/41public static void closeRe(Connection con,PreparedStatement pt,ResultSet rs) {42if(rs != null) {43try {44 rs.close();45 } catch (SQLException e) {46// TODO Auto-generated catch block47 e.printStackTrace();48 }finally {49if(pt != null) {50try {51 pt.close();52 } catch (SQLException e) {53// TODO Auto-generated catch block54 e.printStackTrace();55 }finally{56if(con != null) {57try {58 con.close();59 } catch (SQLException e) {60// TODO Auto-generated catch block61 e.printStackTrace();62 }63 }64 }65 }66 }67 }68 }6970/**71 * closeRe:关闭连接.<br/>72 * @param con73 * @param pt74*/75public static void closeRe(Connection con,PreparedStatement pt) {76if(pt != null) {77try {78 pt.close();79 } catch (SQLException e) {80// TODO Auto-generated catch block81 e.printStackTrace();82 }finally {83if(con != null) {84try {85 con.close();86 } catch (SQLException e) {87// TODO Auto-generated catch block88 e.printStackTrace();89 }90 }91 }92 }93 }9495 }jsp页⾯代码:1 <%@ page language="java" contentType="text/html; charset=utf-8"2 pageEncoding="utf-8"%>3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "/TR/html4/loose.dtd">4 <html>5 <head>6 <meta http-equiv="Content-Type" content="text/html; charset=utf-8">7 <title>登录页⾯</title>8 </head>9 <body>10 <br><br><br>11 <h3 align = "center">登录页⾯</h3>12 <hr>13 <form align = "center" action="LoginServlet" method="post">14 <table align = "center" border="0">15 <tr><td>⽤户名</td><td><input type="text" name="userName" ></td></tr>16 <tr><td>密码</td><td><input type="password" name="userPwd" ></td></tr>17 <tr><td align = "center"><input type="submit" value = "登录" style="color:blue" ></td><td align = "right"><button><a href = "register.jsp" style="color:blue" >注册</a></button></td></tr>18 </table>1920 </form>2122 </body>23 </html>login.jsp1 <%@ page language="java" contentType="text/html; charset=utf-8"2 pageEncoding="utf-8"%>3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "/TR/html4/loose.dtd">4 <html>5 <head>6 <meta http-equiv="Content-Type" content="text/html; charset=utf-8">7 <title>注册页⾯</title>8 </head>9 <body>10 <br><br><br>11 <h3 align = "center">注册页⾯</h3>12 <hr>13 <form align = "center" action="RegisterServlet" method="post">14 <table align = "center" border="0">15 <tr><td>⽤户名</td><td><input type="text" name="userName" ></td></tr>16 <tr><td>密码</td><td><input type="password" name="userPwd" ></td></tr>17 <tr><td>确认密码</td><td><input type="password" name="userRePwd" ></td></tr>18 <tr><td align = "center" colspan="2"><input type="submit" value = "注册" style="color:blue" ></td></tr>19 </table>2021 </form>22 </body>23 </html>register.jsp创建数据库:1 CREATE TABLE nanfeng.`user` (2 user_id INT NOT NULL AUTO_INCREMENT,3 user_name varchar(100) NULL,4 user_pwd varchar(100) NULL,5 CONSTRAINT user_pk PRIMARY KEY (user_id)6 )7 ENGINE=InnoDB8 DEFAULT CHARSET=utf89 COLLATE=utf8_general_ci;4.最后,启动服务器,界⾯效果出来了。
javaee编写简单登录界面代码
javaee编写简单登录界面代码下面是一个使用 JavaEE 编写的简单登录界面的示例代码,包含了一个登录表单和一个登录按钮:```html<!DOCTYPE html><html><head><title>登录界面</title></head><body><h1>登录</h1><form action="/login" method="post"><label for="username">用户名:</label><br><input type="text" id="username" name="username"><br><label for="password">密码:</label><br><input type="password" id="password" name="password"><br><input type="submit" value="登录"></form></body></html>```上述代码是一个简单的 HTML 表单,用户可以输入用户名和密码,然后点击登录按钮进行登录操作。
表单的 `action` 属性指定了提交表单时请求发送到的 URL,`method` 属性指定了请求的方式(这里是 POST)。
请注意,上述示例只是一个简单的登录界面,没有进行实际的登录验证逻辑。
JavaWeb简单用户登录注册实例代码(有验证码)
JavaWeb简单⽤户登录注册实例代码(有验证码)需求编写login登录界⾯(⽤户名,密码,验证码,登陆按钮,注册按钮)设计关系数据库(编号,⽤户名,密码)编写注册功能,将数据存储在数据库中。
(姓名不能重复,设为主键,重复会注册失败)编写登录功能。
⾸先获取验证码,先判断验证码是否正确,不正确则显⽰验证码错误。
验证码正确后再获取⽤户名和密码,进⾏数据库的搜索⽐对,若正确则重定向到成功的界⾯,并且将⽤户名显⽰。
jar包技术选型Servlet + JSP + Mysql + JDBCTemplate + Druid + BeanUtils + Tomcat效果图验证码或者⽤户名和密码错误Navicat Premium 显⽰Mysql内容登录成功源码登录主界⾯ login.jsp<%@ page contentType="text/html;charset=UTF-8" language="java" %><html><head><title>Login</title><script><%-- 增加时间戳来更换验证码图⽚ --%>window.onload=function(){document.getElementById("img").onclick=function(){this.src = "/daydayup/checkCodeServlet?time" + new Date().getTime();}}<%-- ⽤于打开注册的窗⼝--%>function reg() {window.open("register.jsp");}</script><style>div{color: red;}</style></head><body><form action="/daydayup/loginServlet" method="post"><table><tr><td>⽤户名</td><td><input type="text" name="username"></td></tr><tr><td>密码</td><td><input type="text" name="password"></td></tr><tr><td>验证码</td><td><input type="text" name="checkcode"></td></tr><tr><td colspan="2"><img id="img" src="/daydayup/checkCodeServlet" alt=""></td> </tr><tr><td><input type="submit" value="登录"></td><td><input type="button" value="注册" onclick="reg()" ></td></table></form><div>${requestScope.login_error}</div><div>${requestScope.checkcode_error}</div></body></html>注册界⾯ register.jsp<%@ page contentType="text/html;charset=UTF-8" language="java" %><html><head><title>Title</title></head><body><form action="/daydayup/registerServlet" method="post"><table><tr><td>⽤户名</td><td><input type="text" name="username"></td></tr><tr><td>密码</td><td><input type="text" name="password"></td></tr><tr><td><input type="submit" value="确定注册"></td></tr></table></form><div>${requestScope.register_success}</div><div>${requestScope.register_error}</div></body></html>成功界⾯ success.jsp<%@ page contentType="text/html;charset=UTF-8" language="java" %><html><head><title>Title</title></head><body><%-- <h1>${er},欢迎您</h1> --%><h1><%=request.getSession().getAttribute("user")%>,欢迎您</h1></body></html>先编辑好JDBCUtils⼯具类package cn.code.util;import com.alibaba.druid.pool.DruidDataSourceFactory;import javax.sql.DataSource;import java.io.IOException;import java.io.InputStream;import java.sql.Connection;import java.sql.SQLException;import java.util.Properties;/*** JDBC⼯具类使⽤Durid连接池*/public class JDBCUtils {private static DataSource ds;static{try {//加载配置⽂件Properties pro = new Properties();//使⽤ClassLoader加载配置⽂件,获取字节输⼊流InputStream is = JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties");pro.load(is);//初始化连接池对象ds = DruidDataSourceFactory.createDataSource(pro);} catch (Exception e) {e.printStackTrace();}}/*** 获取连接池对象*/public static DataSource getDataSource(){return ds;}/*** 获取连接connection对象*/public static Connection getConnection() throws SQLException {return ds.getConnection();}}创建我们的⽤户类实体Userpackage cn.code.domain;/*⽤户的实体类*/public class User {private int id ;private String username;private String password;public int getId() {return id;}public void setId(int id) {this.id = id;}public String getUsername() {return username;}public void setUsername(String username) {ername = username;}public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}@Overridepublic String toString() {return "User{" +"id=" + id +", username='" + username + '\'' +", password='" + password + '\'' +'}';}}编写Dao来操作数据库,⾥⾯有login和add两个⽅法 Userdao package cn.code.dao;import er;import cn.code.util.JDBCUtils;import org.springframework.dao.DataAccessException;import org.springframework.jdbc.core.BeanPropertyRowMapper;import org.springframework.jdbc.core.JdbcTemplate;import java.sql.Connection;import java.sql.SQLException;import java.sql.Statement;/*** 操作数据库中User表的类*/public class UserDao {//声明JDBCTemplate对象,以便⽅法公⽤private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());/*** 登录⽅法** @param loginUser ⽬前只有⽤户名和密码* @return user包含⽤户全部数据*/public User login(User loginUser) {//编写SQLString sql = "select * from user where username = ? and password = ?";//调⽤query⽅法try {User user = template.queryForObject(sql,new BeanPropertyRowMapper<User>(User.class),loginUser.getUsername(), loginUser.getPassword());return user;} catch (DataAccessException e) {e.printStackTrace();return null;}}/*** 注册⽅法** @param user ⽬前只包含⽤户名和密码* @return 是否注册成功*/public boolean add(User user){//编写SQLString sql = "insert into user (username,password) VALUES('" + user.getUsername() + "','" + user.getPassword() + "')"; boolean flag = false;int num = 0;try {//创建数据库连接Connection conn = JDBCUtils.getConnection();Statement state = null;flag = false;num = 0;state = conn.createStatement();num = state.executeUpdate(sql);} catch (SQLException e) {e.printStackTrace();}if(num >0) flag = true;return flag;}}登录的Servletpackage cn.code.servlet;import erDao;import er;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 java.io.IOException;@WebServlet("/loginServlet")public class LoginServlet extends HttpServlet {protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //设置字符编码request.setCharacterEncoding("utf-8");//获取参数String username = request.getParameter("username");String password = request.getParameter("password");String checkcode = request.getParameter("checkcode");//获取⽣成的验证码HttpSession session = request.getSession();String checkcode_session =(String) session.getAttribute("checkcode_session");//防⽌验证码存储删除Session中存储的验证码session.removeAttribute("checkcode_session");//判断验证码是否正确if(checkcode_session != null && checkcode_session.equalsIgnoreCase(checkcode)){//equalsIgnoreCase忽略⼤⼩写的⽐较//验证码正确User loginUser = new User();loginUser.setUsername(username);loginUser.setPassword(password);User user = new UserDao().login(loginUser);if(user != null){//⽤户名以及密码正确//登录成功//存储⽤户信息session.setAttribute("user",username); //因为是两次请求,所以⽤Session//重定向到success.jspresponse.sendRedirect(request.getContextPath()+"/success.jsp");}else{//⽤户名及密码错误//登录失败//存储提⽰信息到requestrequest.setAttribute("login_error","⽤户名或密码错误");//转发到登录页⾯request.getRequestDispatcher("/login.jsp").forward(request,response);}}else{//验证码不正确//存储提⽰信息到requestrequest.setAttribute("checkcode_error","验证码错误");//转发到登录页⾯request.getRequestDispatcher("/login.jsp").forward(request,response);}}protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response);}}注册的Servletpackage cn.code.servlet;import erDao;import er;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 java.io.IOException;@WebServlet("/registerServlet")public class RegisterServlet extends HttpServlet {protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8");String username = request.getParameter("username");String password = request.getParameter("password");User registerUser = new User();registerUser.setUsername(username);registerUser.setPassword(password);boolean flag = new UserDao().add(registerUser);if(flag) {request.setAttribute("register_success","注册成功");request.getRequestDispatcher("/register.jsp").forward(request,response);}else{request.setAttribute("register_error","账号以被注册,注册失败");request.getRequestDispatcher("/register.jsp").forward(request,response);}}protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request,response);}}在页⾯中画验证码(可点击更换)Servletpackage cn.code.checkcode;import javax.imageio.ImageIO;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 java.awt.*;import java.awt.image.BufferedImage;import java.io.IOException;import java.util.Random;//简易验证码@WebServlet("/checkCodeServlet")public class CheckCodeServlet extends HttpServlet {protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { int width = 100;int height = 50;//创建⼀对象,在内存中代表图⽚(验证码图⽚对象)BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_BGR);//美化图⽚//填充背景⾊Graphics g = image.getGraphics();//画笔对象g.setColor(Color.ORANGE);g.fillRect(0,0,width,height);//画边框g.setColor(Color.BLUE);g.drawRect(0,0,width-1,height-1);String str = "QWERTYUIOPASDFGHJKLZXCVBNM1234567890zxcvbnmlkjhgfdsaqwertyuiop";//⽣成随机⾓标StringBuilder sb = new StringBuilder();Random ran = new Random();for (int i = 1; i <= 4; i++) {int index = ran.nextInt(str.length());//获取字符char ch = str.charAt(index);sb.append(ch);//写验证码g.drawString(ch+"",width/5*i,height/2);}String checkcode_session = sb.toString();//将验证码存⼊sessionrequest.getSession().setAttribute("checkcode_session",checkcode_session);//画⼲扰线g.setColor(Color.RED);//随机⽣成坐标点for (int i = 0 ;i<6;i++) {int x1 = ran.nextInt(width);int x2 = ran.nextInt(width);int y1 = ran.nextInt(height);int y2 = ran.nextInt(height);g.drawLine(x1,y1,x2,y2);}//将图⽚输出到页⾯展⽰ImageIO.write(image, "jpg", response.getOutputStream());}protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {this.doPost(request, response);}}到此这篇关于JavaWeb简单⽤户登录注册实例代码(有验证码)的⽂章就介绍到这了,更多相关JavaWeb ⽤户登录注册内容请搜索以前的⽂章或继续浏览下⾯的相关⽂章希望⼤家以后多多⽀持!。
JavaWeb实现用户登录注册功能实例代码(基于Servlet+JSP+JavaBean模式)
1dom4j ⽤于操作XML ⽂件2⽤于解析XPath 表达式3⼯具类,⽤于处理bean 对象4的依赖jar 包5jstl 标签库和EL 表达式依赖包6jstl 标签库和EL 表达式依赖包存放系统的JavaBean 类(只包含简单的属性以及属性对应的get 和set ⽅法,不包含具体的业务处理⽅法),提供给【数据访问层】、【业务处理层】、【Web 层】来使⽤2存放访问数据库的操作接⼝类数据访问层3存放访问数据库的操作接⼝的实现类4存放处理系统业务接⼝类业务处理层5存放处理系统业务接⼝的实现类6存放作为系统控制器的Servlet Web 层(表现层)7存放为⽤户提供⽤户界⾯的servlet(UI 指的是user interface)8存放系统的⽤到的过滤器(Filter)9存放系统的⽤到的监听器()10存放系统的通⽤⼯具类,提供给【数据访问层】、【业务处理层】、【Web 层】来使⽤ 11存放系统的测试类JavaWeb 实现⽤户登录注册功能实例代码(基于Servlet+JSP+JavaBean 模式)下⾯通过通过图⽂并茂的⽅式给⼤家介绍JavaWeb 实现⽤户登录注册功能实例代码,⼀起看看吧。
Servlet+JSP+JavaBean 模式(MVC)适合开发复杂的web 应⽤,在这种模式下,servlet 负责处理⽤户请求,jsp 负责数据显⽰,javabean 负责封装数据。
Servlet+JSP+JavaBean 模式程序各个模块之间层次清晰,web 开发推荐采⽤此种模式。
这⾥以⼀个最常⽤的⽤户登录注册程序来讲解Servlet+JSP+JavaBean 开发模式,通过这个⽤户登录注册程序综合案例,把之前的学过的XML 、Xpath 、Servlet 、jsp 的知识点都串联起来。
在MyEclipse 中新创建⼀个webmvcframework 项⽬,导⼊项⽬所需要的开发包(jar 包),创建项⽬所需要的包,在java 开发中,架构的层次是以包的形式体现出来的⼀个良好的JavaWeb 项⽬架构应该具有以上的11个包,这样显得层次分明,各个层之间的职责也很清晰明了,搭建JavaWeb 项⽬架构时,就按照上⾯的1~11的序号顺序创建包:domain →dao →dao.impl →service →service.impl →web.controller →web.UI →web.filter →web.listener →util →junit.test ,包的层次创建好了,项⽬的架构也就定下来了,当然,在实际的项⽬开发中,也不⼀定是完完全全按照上⾯说的来创建包的层次结构,⽽是根据项⽬的实际情况,可能还需要创建其他的包,这个得根据项⽬的需要来定了 在src ⽬录(类⽬录)下⾯,创建⽤于保存⽤户数据的xml ⽂件(DB.xml) 在WEB-INF ⽬录下创建⼀个pages ⽬录,pages ⽬录存放系统的⼀些受保护(不允许⽤户直接通过URL 地址访问)的jsp 页⾯,⽤户要想访问这些受保护的jsp 页⾯,那么只能通过这个包⾥⾯的Servlet 创建好的项⽬如下图(图-1)所⽰: 图-1 分层架构的代码也是按照【域模型层(domain)】→【数据访问层(dao 、dao.impl)】→【业务处理层(service 、service.impl)】→【表现层(web.controller 、web.UI 、web.filter 、web.listener)】→【⼯具类(util)】→【测试类(junit.test)】的顺序进⾏编写的。
web JSP 简单的登录+注册页面代码
简单做了界面,代码功能应该没有问题,简单做个文档分享一下。
登录界面denglu.jsp:<%@page contentType="text/html;charset=gb2312" %><html><head><title>登录界面</title><script>function check(){if(erN.value==""){alert("用户名不能为空");erN.focus();return false;}if(erP.value==""){alert("密码不能为空");erP.focus();return false;}document.dlForm.submit();return true;}</script></head><body><center><font size="6"> 欢迎进入登录界面</font><form action="dlhou.jsp" onsubmit="return check()" method="post" name="dlForm"><p>用户名:<input type="text" name="UserN" style="width: 148px; "/></p><p>密 码:<input type="password" name="UserP" style="width: 146px; "/></p><p><input type="submit" value=" 登 录 " style="height: 43px; "/> <input type="button" value="忘记密码" onclick="parent.location.href('wangji.jsp')" style="height: 43px; "/> <input type="button" value="返回主页" onclick="parent.location.href('welcome.jsp')" style="height: 43px; "/></p></FORM> </center></body></html>dlhou.jsp<%@page contentType="text/html;charset=gb2312" %><%@page language="java" import="java.sql.*" %><jsp:useBean id="SQLbean" scope="session" class="lian.Lian"/><html><head><title>登录状态</title></head><body><div align="center"><span class="style1">登录状态</span><br><hr><br></div><%String userN=request.getParameter("UserN");String userP=request.getParameter("UserP");// out.print(userN);String sql="select * from yxx where yname='"+userN+"'";SQLbean.OpenConn();ResultSet rs=SQLbean.executeQuery(sql);if(!rs.next()){%><script>alert("用户名不存在!");window.location.href="denglu.jsp";</script><%}// while(rs.next()){String p=rs.getString("ypassword").trim();if(p.equals(userP.trim()))// response.sendRedirect("zhu.jsp?param="+userN);{session.setAttribute("yhm",userN);// response.sendRedirect("zhu.jsp");%><script>alert("恭喜您,登录成功!");window.location.href="zhu.jsp";</script><%}else{%><script>alert("密码错误!");window.location.href="denglu.jsp";</script><%}}rs.close();SQLbean.closeSt();SQLbean.closeConn();%></body></html><%@page contentType="text/html;charset=gb2312" %><html><head><title>注册界面</title><script>function zcheck(){if(erN.value==""){alert("用户名不能为空");erN.focus();return false;}if(erP.value==""){alert("密码不能为空");erP.focus();return false;}if(document.zcForm.reUserP.value==""){alert("确认密码不能为空");document.zcForm.reUserP.focus();return false;}if(document.zcForm.reUserP.value!=erP.value){alert("确认密码和密码不符");document.zcForm.reUserP.focus();return false;}return true;}</script></head><body><center><font size="6"> 欢迎进入注册界面</font><br><br><font size="4"> 基本信息注册</font><form action="zchou.jsp" onsubmit="return zcheck()" method="post" name="zcForm"><p> 用户名: <input type="text" name="UserN" style="width: 155px; "/> <font color="red">*</font></p><p> 密 码:<input type="password" name="UserP" style="width: 155px; "/> <font color="red">*</font></p> <p> 确认密码:<input type="password" name="reUserP" style="width: 155px; "/> <font color="red">*</font></p><p> 性 别: <input type="radio" name="UserS" value="Mr." checked="checked"/>男 <input type="radio" name="UserS" value="Ms."/>女 <font color="red">*</font></p><p>年 龄:<input type="text" name="UserA" style="width: 155px; "/></p><br><font size="4"> 密码找回问题设置</font><p>问题1:你最尊敬的老师是?答案1:<input type="text" name="Q1" style="width: 155px; "/> <font color="red">*</font></p><p>问题2:你最喜欢的学科是?答案2:<input type="text" name="Q2" style="width: 155px; "/> <font color="red">*</font></p><p>问题3:你最喜欢的运动是?答案3:<input type="text" name="Q3" style="width: 155px; "/> <font color="red">*</font></p><p><input type="submit" name="确定" value=" 确 定 " style="height: 33px; "> <input type="button" value="返回主页" onclick="parent.location.href('welcome.jsp')" style="height: 33px; "/></p></form></center></body></html><%@page contentType="text/html;charset=gb2312" %><%@page language="java" import="java.sql.*" %><jsp:useBean id="SQLbean" scope="session" class="lian.Lian"/><html><head><title>注册状态</title></head><body><%String userN=request.getParameter("UserN");String userP=request.getParameter("UserP");String userS=request.getParameter("UserS");String userA=request.getParameter("UserA");String q1=request.getParameter("Q1");String q2=request.getParameter("Q2");String q3=request.getParameter("Q3");SQLbean.OpenConn();String sqly="select * from yxx where yname='"+userN+"'";ResultSet rsy=SQLbean.executeQuery(sqly);if(rsy.next()){%><script>alert("用户名已被注册,请更换用户名");window.location.href="zhuce.jsp";</script><%}else{String sql="insert into yxx values('"+userN+"','"+userP+"','"+userS+"','"+userA+"')";String sql2="insert into yyz values('"+userN+"','"+q1+"','"+q2+"','"+q3+"')";SQLbean.executeUpdate(sql);SQLbean.executeUpdate(sql2);SQLbean.closeSt();SQLbean.closeConn();%><script>alert("注册成功,将跳转登录界面");window.location.href="denglu.jsp";//wrq经试验表明sendRedirect()还没显示alert 提示就已经跳转</script><%}%></body></html>。
JavaWeb实现用户登录与注册功能
JavaWeb实现⽤户登录与注册功能本⽂实例为⼤家分享了JavaWeb实现⽤户登录与注册的具体代码,供⼤家参考,具体内容如下所⽤知识客户端:HTML CSS JS (JQuery)服务器:JAVA基础 JSP Servlet JDBC Tomcat数据库:MySQL⽤到的Jar包 druid数据库连接池 dbutils JDBC数据库操作⼯具 MySQL jar包实现效果基本为注册⽤户,注册成功将数据写⼊数据库,登录过程查看数据库中是的⽤户名,密码是否匹配,匹配跳转到登录成功页⾯,失败返回登录页⾯。
思路:1、先写前端登录注册界⾯,把前端的基本外观框架完成2、数据库创建⽤户信息表,储存注册⽤户的信息3、服务器部分采⽤JavaEE三层架构(1)、表现层:通俗讲就是展现给⽤户的界⾯,即⽤户在使⽤⼀个系统的时候他的所见所得。
(2)、业务逻辑层:针对具体问题的操作,也可以说是对数据层的操作,对数据业务逻辑处理。
(3)、数据访问层:该层所做事务直接操作数据库,针对数据的增添、删除、修改、查找等。
⼀、客户端部分⽂件存储形式实现代码:index.jsp主页<%@ page contentType="text/html;charset=UTF-8" language="java" %><!DOCTYPE html><html><head><meta charset="UTF-8"><title>⾸页</title><base href="http://localhost:8080/book_war_exploded/"><link type="text/css" rel="stylesheet" href="static/css/style.css" ></head><body><div id="header"><img class="logo_img" alt="" src="static/img/logo.gif" ><div><a href="pages/user/login.jsp" >登录</a> |<a href="pages/user/regist.jsp" >注册</a> </div></div><div id="bottom"><span>hunustNiu</span></div></body></html>login.jsp登录界⾯<%@ page contentType="text/html;charset=UTF-8" language="java" %><!DOCTYPE html><html><head><meta charset="UTF-8"><title>登录页⾯</title><base href="http://localhost:8080/book_war_exploded/"><link type="text/css" rel="stylesheet" href="${pageContext.request.contextPath}/static/css/style.css" ></head><body><div id="login_header"><img class="logo_img" alt="" src="static/img/logo.gif" ></div><div class="login_banner"><div id="l_content"><span class="login_word">欢迎登录</span></div><div id="content"><div class="login_form"><div class="login_box"><div class="tit"><h1>会员</h1><a href="pages/user/regist.jsp" >⽴即注册</a></div><div class="msg_cont"><b></b><span class="errorMsg">请输⼊⽤户名和密码</span></div><div class="form"><form action="${pageContext.request.contextPath}/loginServletl" method="post"><label>⽤户名称:</label><input class="itxt" type="text" placeholder="请输⼊⽤户名" autocomplete="off" tabindex="1" name="username" /> <br /><br /><label>⽤户密码:</label><input class="itxt" type="password" placeholder="请输⼊密码" autocomplete="off" tabindex="1" name="password" /> <br /><br /><input type="submit" value="登录" id="sub_btn" /></form></div></div></div></div></div><div id="bottom"><span>hunustNiu</span></div></body></html>regist.jsp 注册页⾯<%@ page contentType="text/html;charset=UTF-8" language="java" %><!DOCTYPE html><html><head><meta charset="UTF-8"><title>注册页⾯</title><base href="http://localhost:8080/book_war_exploded/"><link type="text/css" rel="stylesheet" href="static/css/style.css" rel="external nofollow" rel="external nofollow" ><script type="text/javascript" src="static/jquery-1.7.2.js"></script><script type="text/javascript">// 页⾯加载完成之后$(function (){$("#sub_btn").click(function (){//判断⽤户名称是否合法//获取⽤户昵称var username=$("#username").val();//获取⽤户昵称匹配的正则表达式var zzusername=/^\w{5,12}$/;//如果不符合正则if(!zzusername.test(username)){$("span.errorMsg").text("⽤户名不合法");return false;}//判断⽤户密码是否合法//获取⽤户密码var password=$("#password").val();//获取⽤户密码匹配的正则表达式var zzpassword=/^[a-z0-9_-]{6,18}$/;//如果不符合正则if(!zzusername.test(username)){$("span.errorMsg").text("⽤户密码不合法");return false;}//确认密码var repwd=$("#repwd").val();if(repwd!==password){$("span.errorMsg").text("两次密码不⼀致");return false;;}//电⼦邮件var email=$("#email").val();var zzemail=/[1-9]\d{7,10}@qq\.com/;if(!zzemail.test(email)){$("span.errorMsg").text("邮箱格式不符");return false;}//验证码//去掉验证码前后空格var code=$("#code").val();code=$.trim(code);if(code!=="6n6np"){$("span.errorMsg").text("验证码错误");return false;}});})</script><style type="text/css">.login_form{height:420px;margin-top: 25px;}</style></head><body><div id="login_header"><img class="logo_img" alt="" src="static/img/logo.gif" ></div><div class="login_banner"><div id="l_content"><span class="login_word">欢迎注册</span></div><div id="content"><div class="login_form"><div class="login_box"><div class="tit"><h1>注册</h1><span class="errorMsg"></span></div><div class="form"><form action="${pageContext.request.contextPath}/registServlet" method="post"> <label>⽤户名称:</label><input class="itxt" type="text" placeholder="请输⼊⽤户名"autocomplete="off" tabindex="1" name="username" id="username" /><br /><br /><label>⽤户密码:</label><input class="itxt" type="password" placeholder="请输⼊密码"autocomplete="off" tabindex="1" name="password" id="password" /><br /><br /><label>确认密码:</label><input class="itxt" type="password" placeholder="确认密码"autocomplete="off" tabindex="1" name="repwd" id="repwd" /><br /><br /><label>电⼦邮件:</label><input class="itxt" type="text" placeholder="请输⼊邮箱地址"autocomplete="off" tabindex="1" name="email" id="email" /><br /><br /><label>验证码:</label><input class="itxt" type="text" style="width: 150px;" id="code" name="code"/><img alt="" src="static/img/code.bmp" style="float: right; margin-right: 40px"><br /><br /><input type="submit" value="注册" id="sub_btn" /></form></div></div></div></div></div><div id="bottom"><span>hunustNiu</span></div></body></html>login_succe.jsp 和regist_success.jsp功能⽬前只是返回⾸页和退出登录<div id="header"><img class="logo_img" alt="" src="static/img/logo.gif" ><div><a href="index.jsp" >注销</a> <a href="index.jsp" >返回</a></div></div><div id="main"><h1>欢迎回来 <a href="index.jsp">转到主页</a></h1></div>⼆、数据库部分⽂件存储形式实现代码:CREATE DATABASE usersCREATE TABLE users(id INT PRIMARY KEY AUTO_INCREMENT,username VARCHAR(25) UNIQUE,PASSWORD VARCHAR(25),email VARCHAR(30) UNIQUE)SELECT *FROM `users`INSERT INTO `users`(`username`,`password`,`email`) VALUES('niu123','niu123','190177@')/*初始测试数据*/三、服务器部分点击查看:问题总结1、客户端部分遇到的bug⾸先就是在注册,登录,主页之间进⾏页⾯跳转的过程中由于没有加⼊<base>标签总是在⼀个⽹页可以显⽰跳到另⼀个页⾯就会产⽣404错误,通过将所有页⾯<base>标签固定为<basehref="http://localhost:8080/book_war_exploded/">统⼀跳转的基准以解决。
JavaWeb登录页面的实现代码实例
JavaWeb登录页⾯的实现代码实例代码如下~内有详细解释,最后有照⽚!<html><script type="text/javascript">function inUser(){username_mess.style.visibility="visible";}function outUser(){//获取name 为 usesrname 的⽂本u=ername.value;ername.style.border="1px solid AAAAAA";if(u==""){username_mess.style.visibility="hidden";return;}//正则表达式reg=/.{4,20}/;if(!reg.test(u)){username_mess.innerHTML="⽤户名长度只能在4-20位字符之间";username_mess.style.color="red";ername.style.color="red";ername.style.border="1px solid red";username_ok.style.visibility="hidden";return;}reg=/^[\u4e00-\u9fa5 \w-]{4,20}$/;if(reg.test(u)){username_ok.style.visibility="visible";username_mess.innerHTML="";ername.style.color="black";}else{username_mess.innerHTML="⽤户名只能由中⽂、英⽂、数字及'_'、'-'组成";username_mess.style.color="red";ername.style.color="red";ername.style.border="1px solid red";username_ok.style.visibility="hidden";}}function inMail(){mail_mess.style.visibility="visible";}function outMail(){v=f1.mail.value;f1.mail.style.border="1px solid AAAAAA";if(v==""){mail_mess.style.visibility="hidden";return;}reg=/\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/;if(reg.test(v)){mail_ok.style.visibility="visible";mail_mess.innerHTML="";f1.mail.style.color="black";}else{//更改id mail_mess 的⽂字mail_mess.innerHTML="请输⼊正确的邮箱地址,例如:X@X.X";//设置id mail_mess 字体的颜⾊mail_mess.style.color="red";//设置 id 为f1 ⾥的 name 为 mail ⽂本框内的⽂字颜⾊f1.mail.style.color="red";//设置⽂本框颜⾊以及框的⼤⼩f1.mail.style.border="1px solid red";mail_ok.style.visibility="hidden";}}</script><!--以下为 class 标签的应⽤函数 +++--><style type="text/css">.label{position:absolute ;right:70%;}.fi{position:relative ;left:30%;}.clr{height:20px ;color:AAAAAA;font-size:12px;visibility:hidden;}.s{font-weight:lighter ;color:red;}.text{font-family:宋体;width:200px;}.v{color:cccccc;font-size:12px ;}a{font-size:12px ;}.btn-img{position:relative ;left:30%;}.ok{background-image:url('ok.jpg');width:17px;height:16px;visibility:hidden;}</style><body><form id="f1"><div class="label"><b class="s">1*</b>⽤户名:</div><div class="fi"><input type="text" name="username" class="text" tabindex="1" onFocus="inUser()" onBlur="outUser()"/><label id="username_ok" class="ok"><img src="ok.jpg" width=17px height=16px/></label> <br/><div id="username_mess" class="clr">4-20位字符,可由中⽂、英⽂、数字及"_"、"-"组成</div></div><div class="label"><b class="s">*</b>设置密码:</div><div class="fi"><input type="password" name="pwd" class="text" tabindex="2"/> <input type="checkbox" name="visi" id="viewpwd"/><label class="v">显⽰密码字符</label><br/><div class="clr"></div></div><div class="label"><b class="s">*</b>确认密码:</div><div class="fi"><input type="password" name="pwd2" class="text" tabindex="3"/><br/><div class="clr"></div></div><div class="label"><b class="s">*</b>邮箱:</div><div class="fi"><input type="text" name="mail" class="text" tabindex="4" onFocus="inMail()" onBlur="outMail()"/><label id="mail_ok" class="ok"><img src="ok.jpg" width=17px height=16px/></label> <label class="v">免费邮箱:</label><a href="">搜狐</a><a href="">⽹易</a><br/><div id="mail_mess" class="clr">请输⼊正确的邮箱地址</div></div><div class="label">推荐⼈⽤户名:</div><div class="fi"><input type="text" name="referrer" class="text"value="可不填" tabindex="5"/><br/><div class="clr"></div></div><input type="button" class="btn-img" id="registsubmit"value="同意以下协议,提交" tabindex="8"/></form></body></html>以上所述是⼩编给⼤家介绍的Java Web 登录页⾯的实现详解整合,希望对⼤家有所帮助,如果⼤家有任何疑问请给我留⾔,⼩编会及时回复⼤家的。
JavaWeb用户登录实例代码
JavaWeb⽤户登录实例代码实现功能:1、⽤户登陆、注销2、利⽤session记录⽤户登陆信息3、在JSP中展⽰已登陆⽤户信息实现原理:登陆后通过判断⽤户名和密码是否和存储的⼀致,如果⼀致,就把⽤户信息放到session中储存;如果不⼀致就提⽰信息,并且返回登陆页⾯。
显⽰信息页⾯上固定从session中找⽤户登陆信息,找到就显⽰⽤户信息,没找到就显⽰登陆框。
注销很简单,就是清空session信息。
主要⽂件:1、LoginAction:struts2的Action类,⽤于处理JAVA端的主要登陆和登出逻辑。
2、login.jsp:⽤户登陆页⾯,⽤户输⼊⽤户名和密码,如果登陆失败显⽰失败信息。
3、page.jsp:登陆成功后显⽰⽤户信息。
4、struts.xml:struts的配置⽂件。
LoginAction:struts2的Action类,⽤于处理JAVA端的主要登陆和登出逻辑package luju.me.teach.struts2.login;import javax.servlet.http.Cookie;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.servlet.http.HttpSession;import ng.StringUtils;import org.apache.struts2.ServletActionContext;import com.opensymphony.xwork2.Action;/*** @author 鲁炬 http://luju.me**/public class LoginAction {private String loginname;private String password;private String msg;public String getMsg() {return msg;}public void setMsg(String msg) {this.msg = msg;}public String getLoginname() {return loginname;}public void setLoginname(String loginname) {this.loginname = loginname;}public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}/** ⽤户登陆 */public String login() {if(StringUtils.isBlank(this.loginname)) {return Action.INPUT;}/*这⾥写你⾃⼰通过⽤户名查找⽤户信息的业务逻辑⽐如:使⽤⼿机号登陆Citizen user = prmService.queryEGovCitizenByMobile(this.loginname);....*/if(user == null || user.getPwd() == null || !user.getPwd().getValue().equals(this.password)) {//登陆失败this.msg = "⽤户不存在或密码错误!";return Action.INPUT;} else {//登陆成功//设置sessionthis.getSession().setAttribute("_USER_INFO_LOGIN_NAME_", this.loginname);this.getSession().setAttribute("_USER_INFO_USER_ID_", user.getId().getValue());this.getSession().setAttribute("_USER_INFO_USER_INFO_", user);//设置cookiethis.getResponse().addCookie(new Cookie("_USER_INFO_LOGIN_NAME_", this.loginname));this.getResponse().addCookie(new Cookie("_USER_INFO_USER_ID_", user.getId().getValue()));return Action.SUCCESS;}}/*** 注销*/public String loginout() {//清空sessionthis.getSession().invalidate();return Action.SUCCESS;}public HttpSession getSession() {return ServletActionContext.getRequest().getSession();}public HttpServletRequest getRequest() {return ServletActionContext.getRequest();}public HttpServletResponse getResponse() {return ServletActionContext.getResponse();}}struts.xml:struts的配置⽂件<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "/dtds/struts-2.0.dtd"> <struts><package name="common" namespace="/common"><action name="login" class="mon.action.LoginAction"method="login"><result name="input">login.jsp</result><result name="success" type="redirect">/page.jsp</result></action><action name="loginout" class="mon.action.LoginAction"method="loginout"><result name="success" type="redirect">login.action</result></action></package></struts>login.jsp:⽤户登陆页⾯,⽤户输⼊⽤户名和密码,如果登陆失败显⽰失败信息。