JSP连接数据库实现注册登录(附带上传头像)

完成登录程序,可进行注册,需进行头像的上传,登录成功之后,可进行注销和进行个人信息修改,并且可以修改头像。

公共方法:
文件自动取名FileNameAuto

package cn.lizhi.pub;


import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

public class FileNameAuto {
    private String ip;

    public String getIp() {
        return ip;
    }

    public void setIp(String ip) {
        this.ip = ip;
    }

    public FileNameAuto(String ip) {
        super();
        this.ip = ip;
    }

    public FileNameAuto() {
        super();
    }
    public String getFileName(){
        Date date = new Date();
        DateFormat df = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        String fileName = df.format(date);
        return fileName;

    }

}



获取表ID GetTableID

package cn.lizhi.pub;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;

public class GetTableID {
    public static final String DRIVER = "oracle.jdbc.driver.OracleDriver";
    public static final String URL = "jdbc:oracle:thin:@10.211.55.3:1521:orcl";
    public static final String USERNAME = "lizhi";
    public static final String PASSWORD = "lizhi";
    public static int getIdk() {
        Connection conn = null;
        CallableStatement cstate = null;//专门用于调用存储过程和函数的操作接口
        int result_ = 0;
        try {
            Class.forName(DRIVER);
            conn = DriverManager.getConnection(URL,USERNAME,PASSWORD);
            //调用存储过程
            String sql = "{? = call getidk}";
            cstate = conn.prepareCall(sql);
            cstate.registerOutParameter(1, java.sql.Types.INTEGER);//定义返回值的类型
            cstate.execute();//执行
            result_ = cstate.getInt(1);//取得返回值
        } catch (Exception e) {
            e.printStackTrace();
        } finally{
            try {
                cstate.close();
                conn.close();
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result_;
    }
}



注册账号检查 RegisterCheck

package cn.lizhi.pub;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;


public class RegisterCheck {
    public static final String DRIVER = "oracle.jdbc.driver.OracleDriver";
    public static final String URL = "jdbc:oracle:thin:@10.211.55.3:1521:orcl";
    public static final String USERNAME = "lizhi";
    public static final String PASSWORD = "lizhi";
    Connection conn = null;
    PreparedStatement pstate = null;
    ResultSet res = null;
    public boolean checkUserName(String userName) {
        boolean flag = true;
        try {
            String sql = "select count(user_id) from dh12_user where user_account= ?";
            pstate = conn.prepareStatement(sql);
            pstate.setString(1, userName);
            res = pstate.executeQuery();
            while(res.next()){
                int count = res.getInt(1);
                if(count > 0){
                    flag = false;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally{
            try{
                res.close();
                pstate.close();
            }catch(Exception e2){
                e2.printStackTrace();
            }
        }
        return flag;
    }
}



用户保存进数据库 SaveUser

package cn.lizhi.pub;


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

public class SaveUser {
    public static final String DRIVER = "oracle.jdbc.driver.OracleDriver";
    public static final String URL = "jdbc:oracle:thin:@10.211.55.3:1521:orcl";
    public static final String USERNAME = "lizhi";
    public static final String PASSWORD = "lizhi";
    public static int saveuser(String userName,String password,String userImg) {
        Connection conn = null;
        PreparedStatement pstate = null;
        int flag = -1;
        try {
            Class.forName(DRIVER);
            conn = DriverManager.getConnection(URL,USERNAME,PASSWORD);
            String sql = "insert into dh12_user(USER_ID,USER_ACCOUNT,USER_PASSWORD,USER_IMG) values(?,?,?,?)";
            pstate = conn.prepareStatement(sql);
            pstate.setInt(1,GetTableID.getIdk());
            pstate.setString(2,userName);
            pstate.setString(3,password);
            pstate.setString(4,userImg);
            pstate.execute();
            flag = 1;
        } catch (Exception e) {
            e.printStackTrace();
        } finally{
            try {
                pstate.close();
                conn.close();
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return flag;
    }
}



用户类 UserBean

package cn.lizhi.pub;

public class UserBean {  
       private String userAccount;  
       private String password;  
       private String Img;
       private String name;
       public String getUserAccount() {
        return userAccount;
    }
       public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public void setUserAccount(String userAccount) {
        this.userAccount = userAccount;
    }
       public String getPassword() {
        return password;
    }
       public void setPassword(String password) {
        this.password = password;
    }
       public String getImg() {
        return Img;
    }
       public void setImg(String img) {
        Img = img;
    }
    public UserBean(String userAccount, String password, String img) {
        super();
        this.userAccount = userAccount;
        this.password = password;
        this.name = name;
        Img = img;
    }
    public UserBean() {
        super();
        // TODO Auto-generated constructor stub
    }


}  




登陆:Login.jsp

<%@page import="java.text.Normalizer.Form"%>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ page import="java.sql.*"%>
<% String account = ""; String password = ""; %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<style type="text/css"> a { text-decoration: NONE } a:HOVER { color : red } </style>

</style>
</head>
<body>
    <% Cookie c[] = request.getCookies();//取得浏览器中所有的Cookie if( c!=null && c.length >1){ for(int i = 0;i<c.length;i++){ Cookie cook = c[i]; if(c[i].getName().equals("account")){ account = c[i].getValue(); } if(c[i].getName().equals("password")){ password= c[i].getValue(); } } %>
            <jsp:forward page="LoginCheck.jsp">
              <jsp:param name="account" value="<%= account%>"/>
              <jsp:param name="password" value="<%= password%>"/>
            </jsp:forward>  
            <% }else if (c == null || c.length == 1) { %>
    <form action="LoginCheck.jsp" method="post" name="f" onsubmit="return validate(this)" >
    <center>
    <fieldset style="width:300px">
    <legend>登陆</legend>
    <table> 
        <tr><td width="20%" align="right"><labelfor"i1">账号</label></td>     
        <td><input type="text" id="i1" name="account" ></td></tr>       
        <tr><td width="20%" align="right"><labelfor"i2">密码</label></td> 
        <td><input type="password" id="i2"name="password"></td></tr>
        <tr><td width=20% align="right"></td>
        <td align="center" ><input type="submit" value="提 交" /><input type="reset" value="重 置" /></td></tr>
        <tr><td colspan = "3" align="center"><a href="../Register/Register.jsp">点击这里进行注册!</a></td></tr>

    </table>
    </fieldset>
    </center>
    </form>

    <% }else{ %><jsp:forward page = "LoginCheck.jsp" /><% } %>

</body>
<script type="text/javascript"> function validate(f) { var account = f.account.value; var password = f.password.value; var flag = false; if (account == null || account == "") { alert("请输入账号"); f.account.focus();//取得焦点 return false; } if (password == null || password == "") { alert("请输入密码"); f.password.focus();//取得焦点 return false; } return true; } </script>
</html>




登陆验证:LoginCheck.jsp

<%@page import="javax.servlet.jsp.tagext.TryCatchFinally"%>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ page import = "java.sql.*" %>
<%@ page import = "java.util.*"%>
<%@ page import = "cn.lizhi.pub.*"%>
<% //取得设置的属性 String account = request.getParameter("account"); String password = request.getParameter("password"); boolean flag = false; String name = null; UserBean user = null; String img = null; %>
<%! public static final String DRIVER = "oracle.jdbc.driver.OracleDriver"; public static final String URL = "jdbc:oracle:thin:@10.211.55.3:1521:orcl"; public static final String USERNAME = "lizhi"; public static final String PASSWORD = "lizhi"; %>

<% Connection conn = null; PreparedStatement pstate = null; ResultSet res = null; try { Class.forName(DRIVER); conn = DriverManager.getConnection(URL,USERNAME,PASSWORD); String sql = "select user_img from dh12_user where user_account = ? and user_password = ?"; pstate = conn.prepareStatement(sql); pstate.setString(1, account); pstate.setString(2, password); res = pstate.executeQuery(); while(res.next()){ img = res.getString(1); user = new UserBean(account,password,img); flag = true; } } catch (Exception e) { e.getStackTrace(); } finally { try { } catch (Exception e2) { e2.getStackTrace(); } } %>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
    <% if (flag) { %>
            <% session.setAttribute("user",user); response.sendRedirect("../Main/Main.jsp"); Cookie cook1 = new Cookie("account", account); Cookie cook2 = new Cookie("password", password); cook1.setMaxAge(60); cook2.setMaxAge(60); response.addCookie(cook1);//向客户端添加Cookie response.addCookie(cook2);//向客户端添加Cookie %>


    <% } else { %>
    <h1>
        登录失败,请重新<a href="Login.jsp">登录</a>
    </h1>
    <% } %>
</body>
</html>




注册:Register.jsp

<%@page import="cn.lizhi.pub.RegisterCheck"%>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ page import="java.sql.*" %>
<%@page import="cn.lizhi.pub.UserBean"%>
<% RegisterCheck rCheck = new RegisterCheck(); %>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>用户注册</title>
</head>
<body>
    <form action="SmartUpLoad.jsp" method="post" onsubmit="return validate(this)" enctype="multipart/form-data">
    <center>
        <fieldset style="width:400px">
            <legend>用户注册</legend>
            <table>
                    <tr>
                        <td class=“left” width=40% align="right"><label for="t1">账&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;号:</label></td>
                        <td class="right"><input type="text" id="t1" name="account"></td>
                    </tr> 
                    <tr>
                        <td class=“left” width=40% align="right"><label for="Password1">密&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;码:</label></td>
                        <td class="right"><input id="Password1" type="password" name="password" /></td>
                    </tr>
                    <tr>
                        <td class=“left” width=40% align="right"><label for="Password1">重复密码:</label></td>
                        <td class="right"><input id="Password1" type="password" name="password2" /></td>
                    </tr>
                    <tr>
                        <td class=“left” width=40% align="right"><label for="e1">邮&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;箱:</label></td>
                        <td class="right"><input type="email" id="e1" name="email"></td>
                    </tr>
                    <tr>
                        <td class=“left” width=40% align="right"><label for="s1">性&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;别:</label></td>
                        <td class="right"><input type="radio" id="s1" name="sex" value="nan" /><input type="radio" id="2" name="sex" value="nv" /></td>
                    </tr>
                    <tr>
                        <td class=“left” width=40% align="right">地&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;区:</td>
                        <td><select id="selc" name="place">
                                <option value="nanchang">南昌</option>
                                <option value="xiamen">厦门</option>
                                <option value="guangzhou">广州</option>
                        </select></td>
                    </tr>
                    <tr>
                        <td class=“left” width=40% align="right"><label for="txtarea">头&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;像:</label></td>
                        <td><input type="file" value="上传" name="img"/></td>
                    </tr>
                    <tr>
                        <td class=“left” width=40% align="right" rowspan=2><input type="submit" id="Submit1" value="提 交" /></td>
                        <td align="center"><input type="reset" id="Reset1" name="chongzhi" value="重 置" /></td>
                    </tr>
            </table>
        </fieldset>
        </center>
    </form>
</body>
<script type="text/javascript"> function validate(f) { var account = f.account.value; var password = f.password.value; var password2 = f.password2.value; var img = f.img.value; var flag = false; if (account == null || account == "") { alert("请输入账号"); f.account.focus();//取得焦点 return false; } if (password == null || password == "") { alert("请输入密码"); f.password.focus();//取得焦点 return false; } if (password2 != password) { alert("两次输入密码不相同,请重新输入"); f.password2.focus();//取得焦点 return false; } if (img == null) { alert("请选择头像"); f.img.focus();//取得焦点 return false; } if(!rCheck){ alert("账号不能重复"); f.account.focus(); return false; } return true; } </script>
</html>




上传注册信息:SmartUpLoad.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@page import="com.jspsmart.*"%>
<%@page import="com.jspsmart.upload.SmartUpload"%>
<%@page import="com.jspsmart.upload.Request"%>
<%@page import="cn.lizhi.pub.*"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
    <% SmartUpload smart = new SmartUpload();//主要操作类 smart.initialize(pageContext);//初始化上传文件 smart.setCharset("utf-8");//设置上传编码 smart.upload();//准备上传 Request smrequest = smart.getRequest(); String userName = smrequest.getParameter("account"); String password = smrequest.getParameter("password"); String endName = smart.getFiles().getFile(0).getFileExt();//取得文件后缀 FileNameAuto auto = new FileNameAuto(); String name = auto.getFileName(); String fileName = getServletContext().getRealPath("/")+"file/"+name + "."+endName; String saveFile = name + "."+endName; smart.getFiles().getFile(0).saveAs(fileName);//保存文件 SaveUser.saveuser(userName,password,saveFile); response.sendRedirect("../Login/Login.jsp"); %>

</body>
</html>




修改个人信息:ChangeInfo.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ page import="java.sql.*" %>
<%@ page import = "java.util.*"%>
<%@ page import = "cn.lizhi.pub.*"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
    <form action="InfoSubmit.jsp" onsubmit="return validate(this)">
    <h1>修改昵称:<input type="text" name="nickname"></h1>
    </form>
</body>
<script type="text/javascript"> </script>
</html>




提交信息给数据库:InfoSumbit.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ page import="java.sql.*" %>
<%@ page import = "java.util.*"%>
<%@ page import = "cn.lizhi.pub.*"%>
    <% //取得设置的属性 String account = request.getParameter("account"); String password = request.getParameter("password"); String nickname = request.getParameter("nickname"); boolean flag = false; String name = null; UserBean user = null; String img = null; %>
<%! public static final String DRIVER = "oracle.jdbc.driver.OracleDriver"; public static final String URL = "jdbc:oracle:thin:@10.211.55.3:1521:orcl"; public static final String USERNAME = "lizhi"; public static final String PASSWORD = "lizhi"; %>
<% Connection conn = null; PreparedStatement pstate = null; ResultSet res = null; try { Class.forName(DRIVER); conn = DriverManager.getConnection(URL,USERNAME,PASSWORD); String sql = "insert into dh12_user(user_nickname) values(?) where user_account = ?"; pstate = conn.prepareStatement(sql); pstate.setString(1, nickname); pstate.setString(2, account); res = pstate.executeQuery(); flag = true; } catch (Exception e) { e.getStackTrace(); } finally { try { } catch (Exception e2) { e2.getStackTrace(); } } %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
      <% if(flag){ %><h1>修改成功</h1>
        <% } %>>
</body>
</html>




用户信息:UserInfo.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ page import="java.sql.*" %>
<%@ page import = "java.util.*"%>
<%@ page import = "cn.lizhi.pub.*"%>
<% //取得设置的属性 String account = request.getParameter("account"); String password = request.getParameter("password"); boolean flag = false; String name = null; UserBean user = null; String img = null; %>
<%! public static final String DRIVER = "oracle.jdbc.driver.OracleDriver"; public static final String URL = "jdbc:oracle:thin:@10.211.55.3:1521:orcl"; public static final String USERNAME = "lizhi"; public static final String PASSWORD = "lizhi"; %>
<% Connection conn = null; PreparedStatement pstate = null; ResultSet res = null; try { Class.forName(DRIVER); conn = DriverManager.getConnection(URL,USERNAME,PASSWORD); String sql = "select user_img from dh12_user where user_account = ?"; pstate = conn.prepareStatement(sql); pstate.setString(1, account); res = pstate.executeQuery(); while(res.next()){ img = res.getString(1); user = new UserBean(account,password,img); flag = true; } } catch (Exception e) { e.getStackTrace(); } finally { try { } catch (Exception e2) { e2.getStackTrace(); } } %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
    <h1>账号:<%= account %></h1>
    <h1>头像地址:<%= img %></h1>

</body>
</html>




主界面:Main.jsp

<%@page import="cn.lizhi.pub.UserBean"%>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<% UserBean user = (UserBean)session.getAttribute("user"); %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<style type="text/css"> .nav{width: 50%;height: 50px;background:url("../../img/bg.jpg");} .nav ul{width: 980px;margin:0px auto;} .nav ul li{list-style: none;width:136px;height: 50px;float: left;/*横排排列*/color: #FFFFFF;line-height: 50px;font-family: "微软雅黑"; text-align: center;} .nav ul li a{color: #FFFFFF;text-decoration: none;width:136px;height: 50px;display: block;} .nav ul li a:hover{background:url("../../img/hover.jpg");} </style>
</head>
<body>
   <h1>
        欢迎光临:<%=user.getUserAccount() %>    

    </h1>
    <div class = "head"> <img src="../../file/<%= user.getImg()%>"/> </div>
    <div class="nav">
      <ul>
        <li><a href="../UserInfo/UserInfo.jsp?account=<%=user.getUserAccount()%> ">查看个人信息</a></li>

        <li><a href="../UserInfo/ChangeInfo.jsp?account=<%=user.getUserAccount()%>">修改个人信息</a></li>
        <li><a href="../UserInfo/ChangeInfo.jsp?account=<%=user.getUserAccount()%>">修改头像</a></li>
        <li><a href="../Login/Login.jsp">注销</a></li>
      </ul> 
    </div>


</body>
</html> 

主界面代码很简单,个人信息那些的也很简单,字段很少,不过实现了功能就行了,想丰富自己加就行了,23333 就这样吧。

你可能感兴趣的:(数据库,jsp)