Javaweb之简单例子(二)
一、简述
在Javaweb之简单例子(一)的基础上添加验证码、图片上传功能,并使用session保存登录状态。
文件打包:链接: https://pan.baidu.com/s/1psj69zjFclq3tvV-Y-UI2w 密码: dc5x
二、效果
在注册页面通过ajax异步检查用户名是否已存在,添加了验证码;登录成功之后服务器会将当前用户信息保存到session中,登录成功的页面会检查是否已经登录,已经登录会正常显示内容,未登录则跳转到登录成功页面。登录成功后可以修改简介以及头像。退出时移除保存在session的登录用户信息。
三、工程结构
四、源文件
hello.html文件
<!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=GBK">
<title>登录成功</title>
<style type="text/css">
.btn{height: 40px; border-left:0; width:90px; padding-left: 5px; font-size:15px; margin:10px; background: #4492dc; cursor:pointer; border-radius:5px; color:#fff;}
</style>
<script type='text/javascript' src='JS/jquery-1.8.1.min.js'></script>
<script type='text/javascript' >
window.onload=function(){
$.ajax({
type:"POST",
async: true,
dataType: "json",
url:"./servlet/IsUserLoginServlet",
success:function(data){
if(data.info=="true")
{
<!-- alert("已登录"); -->
document.getElementById("userName").innerHTML = data.userName;
document.getElementById("introduce").innerHTML = data.introduce;
document.getElementById("picSrc").src = data.picSrc;
document.getElementById("uid").value = data.uid;
document.getElementById("box").style.display = "block";
}
else
{
document.getElementById("box").style.display = "none";
alert("请先登录!!!");
window.location.href = "index.html";
}
},
error:function(data){
console.log(data);
}
});
};
function Logoff()
{
var userName = document.getElementById("userName").innerHTML;<!--获取用户输入的用户名-->
userName = userName.trim();
//alert(userName);
$.ajax({
type:"POST",
async: true,
dataType: "json",
url:"./servlet/UserLogoffServlet",
data: {"userName": userName},
success:function(data){
document.getElementById("box").style.display = 'none';
window.location.href = "index.html";
},
error:function(data){
console.log(data);
}
});
}
</script>
</head>
<body style="margin:0" >
<div id="box" style="display:none">
<div style="float:left; width: 100%; margin: 0;">
<span>头像:</span>
<img id="picSrc" src="./PIC/Upload/default.png" alt="头像" />
<div style="float:right">
<a href="" id="index" onclick="Logoff()" style="background-image: url('./PIC/BG/off.png');background-repeat: round;color:red;">______</a>
</div></br>
<span>用户名:</span><span id="userName">游客</span>
</br><span>简 介:</span><span id="introduce">积少成多,贵在坚持!</span>
</div>
<form action="./servlet/ChangePicServlet" method="post" enctype="multipart/form-data">
<span>修改简介为:</span><input name="introduce" type="text" id="introduce2" placeholder="积少成多,贵在坚持!"/>
<input type="hidden" name="uid" id="uid"/></br>
<span>修改头像为:</span><input type="file" name="picHead" value="上传图片"></br>
<input type="submit" class="btn"value="修改"/>
</form>
</div>
</body>
</html>
index.html文件
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>用户登录</title>
<link rel="stylesheet" href="CSS/index.css">
<style type="text/css">
</style>
<script type='text/javascript' src='JS/jquery-1.8.1.min.js'></script>
<script>
function ALogin()
{
var userName = $("#userName").val().trim();<!--获取用户输入的用户名-->
var pwd = $("#pwd").val().trim();<!--获取用户输入的密码-->
if(( userName!="" && pwd!=""))<!--如果用户名和密码不为空-->
{
$.ajax({
type:"POST", <!--以post方式请求-->
async: true, <!--异步请求-->
dataType: "json",<!--数据格式为json-->
url:"./servlet/LoginServlet",<!--请求LoginServlet-->
data: {"userName": userName, "pwd": pwd},<!--键值数据,前面的是键,后面的是值,后台在LoginServlet类可以根据这个键获取值-->
success:function(data){<!--这个data是后台LoginServlet返回的信息-->
if(data.info=="true")<!--如果返回的是"trueS"-->
{
window.location.href = "hello.html";<!--将本页面地址刷新为hello.html页面(相当于跳转页面并在本页面打开)-->
}
else <!--如果返回的是"false"-->
{
alert("用户名或密码错误!!!");
}
},
error:function(data){
console.log(data);<!--出错的话在控制台打印后台返回的信息-->
}
});
}
else
{
<!--alert("不能为空!");-->
}
}
window.onload=function()<!--页面刚加载时执行-->
{
$('#userName').focus();<!--用户名输入框获取焦点-->
ALogin();
}
<!--监听键盘按下事件,当按下回车的时候,开始请求登录(快捷键回车登录)-->
document.onkeydown=keyDownSearch;
function keyDownSearch(e)
{
<!--兼容FF和IE和Opera-->
var theEvent = e || window.event;
var code = theEvent.keyCode || theEvent.which || theEvent.charCode;
if (code == 13) {
ALogin();<!--具体处理函数-->
return false;
}
return true;
}
</script>
</head>
<body>
<div class="wp_res">
<div class="main_res png">
<div class="form" >
<ul class="shuru">
<li>
<div style="text-align:center;font-size:18px;">
<span >用户登录</span>
</div>
</li>
<li>
<div class="text" >
<span class="ico_f_cfm"></span>
<input id="userName" tabindex="3" id="psw1" name="psw1" class="ipt_nor" value="" placeholder="用户名" type="text" maxlength="16">
</div>
</li>
<li>
<div class="text">
<span class="ico_f_pwd"></span>
<input id="pwd" tabindex="3" id="psw1" name="psw1" class="ipt_nor" value="" placeholder="密码" type="password" maxlength="16">
</div>
</li>
<li>
<input type="button" class="btn_nor_2" onclick="ALogin()" id="login"title="登录" value="登录"/>
</li>
<a href="register.html" style="">未有账号?即刻注册!</a>
</ul>
<div class="footer">
<p>电信增值业务经营许可证粤B2-20171203号 粤ICP备10240715号</p>
<p>© 1927-2017 Genven_Liang</p>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
register.html文件
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>注册中心</title>
<meta name="keywords" content="帐号注册">
<meta name="description" content="账号注册">
<link rel="stylesheet" href="CSS/register.css">
<style type="text/css">.muHover {background:#efefef none repeat scroll 0 0;}</style>
<script type='text/javascript' src='./JS/jquery-1.8.1.min.js'></script>
<script type='text/javascript'>
window.onload=function()
{
console.log("已进入window.onload");
$("#userName").focus(function(){
document.getElementById("hasuser").innerHTML="";
});
$("#pwd2").focus(function(){
document.getElementById("pwdyizhi").innerHTML="";
});
$("#yzm").focus(function(){
document.getElementById("yzmYes").innerHTML="";
});
$("#pwd2").blur(function(){
var pwd1=$("#pwd").val().trim();
var pwd2=$("#pwd2").val().trim();
if(pwd1!=pwd2)
{
document.getElementById("pwdyizhi").innerHTML="两次密码不一致!";
}
});
$("#userName").blur(function(){
console.log("userName失去焦点");<!--失去焦点时,即填写用户名完毕,焦点离开用户名输入框,向后台验证用户名是否已存在-->
var name=$("#userName").val().trim();
if( name != "")
{
$.ajax({
type:"POST",
async: true,
dataType: "json",
url:"./servlet/CheckUserNameServlet",
data: {"userName": name},
success:function(data){
if(data.info==true)
{
document.getElementById("hasuser").innerHTML="恭喜您!用户名可用!!!";
}
else
{
document.getElementById("hasuser").innerHTML="Sorry!该用户名已存在!!!";
}
},
error:function(data){
console.log(data);
}
});
}
});
document.getElementById("register").onclick=function(){
var userName = $("#userName").val().trim();
var pwd = $("#pwd").val().trim();
var pwd2 = $("#pwd2").val().trim();
var yzm = $("#yzm").val().trim();
if(( userName!="" && pwd!="" && pwd2!=""))
{
if(pwd==pwd2 && pwd!="")
{
$.ajax({
type:"POST",
async: true,
dataType: "json",
url:"./servlet/RegisterServlet",
data: { "userName": userName, "pwd": pwd,"yzm":yzm},
success:function(data){
console.log(data);<!--data是后台返回的数据-->
if(data.info=="true")
{
alert("注册成功!");
window.location.href = "index.html";
}
else if(data.info=="false")
{
document.getElementById("hasuser").innerHTML="该用户名已存在!!!";
}
else
{
document.getElementById("yzmYes").innerHTML="验证码错误!!!";
refresh();
}
},
error:function(data){
console.log(data);
}
});
}
else
{
document.getElementById("pwdyizhi").innerHTML="两次输入的密码不一致!!!";
document.getElementById("pwd").value="";
document.getElementById("pwd2").value="";
return false;
}
}
else
{
alert("不能为空!!!");
return false;
}
}
}
</script>
</head>
<body>
<div class="wp_res">
<div class="header">
<a href="./index.html" class="login" title="首页">首页<span class="ico_log png"></span></a>
</div>
<div class="main_res png">
<div class="form">
<ul>
<li>
<div class="text">
<span class="ico_f_cfm"></span>
<input id="userName" tabindex="3" name="psw1" class="ipt_nor" value="" placeholder="用户名" type="text" maxlength="16"/>
</div>
<span id="hasuser"></span>
</li>
<li>
<div class="text">
<span class="ico_f_pwd"></span>
<input id="pwd" tabindex="3" name="psw1" class="ipt_nor" value="" placeholder="密码" type="password" maxlength="16">
</div>
</li>
<li>
<div class="text">
<span class="ico_f_cfm"></span>
<input id="pwd2" tabindex="4" class="ipt_nor" placeholder="确认密码" value="" type="password" maxlength="16">
</div>
<span id="pwdyizhi"></span>
</li>
<li>
<div>
<input id="yzm" placeholder="验证码" style="width:60px; height:30px;" type="text" maxlength="5" align="middle">
<img id="yzmsrc" src="./servlet/GetYZMServlet" align="middle">
<a href="#" onclick="refresh()"> 看不清,换一个</a>
</div>
<span id="yzmYes"></span>
</li>
<li>
<input type="button" class="btn_nor_2" id="register"title="立即注册" value="立即注册"/>
</li>
</ul>
<p class="txt_agree">注册即表示同意<a href="#">《XXX服务使用协议》</a></p>
</div>
</div>
</div>
<div class="footer">
<p>电信增值业务经营许可证粤B2-20171203号 粤ICP备10240715号</p>
<p>© 1927-2017 Genven_Liang</p>
</div>
</body>
<script>
function refresh() { <!--刷新验证码-->
document.getElementById("yzmsrc").src = document.getElementById("yzmsrc").src + "?nocache=" + new Date().getTime();
}
</script>
</html>
ChangePicServlet.java文件
import java.io.IOException;
import java.io.PrintWriter;
import javafx.scene.chart.PieChart.Data;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.jspsmart.upload.SmartUpload;
import com.jspsmart.upload.SmartUploadException;
public class ChangePicServlet extends HttpServlet {
/**
* Constructor of the object.
*/
public ChangePicServlet() {
super();
}
/**
* Destruction of the servlet. <br>
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
/**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
/**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to post.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
//response.setContentType("text/html;charset=UTF-8");
SmartUpload su = new SmartUpload();
su.initialize(this.getServletConfig(), request, response);
try {
su.upload();
su.save("PIC/Upload");//保存目录
} catch (SmartUploadException e) {
e.printStackTrace();
}
String fileName=su.getFiles().getFile(0).getFileName().trim();//获取文件名,并去掉两端空格
String suid = su.getRequest().getParameter("uid").trim();//获取用户id
if(!suid.isEmpty()&& !suid.isEmpty())
{
int uid = Integer.valueOf(suid);
String introduce = su.getRequest().getParameter("introduce").trim();//获取简介(收到的是ANSI编码)
System.out.println(introduce);
UserInfoSrvc srvc = new UserInfoSrvc();
if(uid>=0)
{
User user = srvc.searchById(uid);
if(user!=null)
{
if(introduce.isEmpty())
{
introduce = user.getIntroduce();
}
if(!fileName.isEmpty())
{
fileName = "./PIC/Upload/"+fileName;
}
else
{
fileName = user.getPicSrc();
}
srvc.updateById(uid, user.getUserName(), user.getPwd(),fileName , introduce);
}
}
}
response.sendRedirect("../hello.html");//重定向
}
/**
* Initialization of the servlet. <br>
*
* @throws ServletException if an error occurs
*/
public void init() throws ServletException {
// Put your code here
}
}
CheckUserNameServlet.java文件
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONObject;
public class CheckUserNameServlet extends HttpServlet {
/**
* Constructor of the object.
*/
public CheckUserNameServlet() {
super();
}
/**
* Destruction of the servlet. <br>
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
/**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("get");
String userName = request.getParameter("userName").trim();//获取前台传送过来要检测的用户名,并去掉两端空格
System.out.println("get"+userName);
boolean b=true;
if(!userName.isEmpty())
{
UserInfoSrvc infoservice = new UserInfoSrvc();
List<User> list=infoservice.search();
for(int i=0;i<list.size();i++)
{
if(list.get(i).getUserName().equals(userName))
{
b= false;
}
}
}
response.setContentType("application/json;charset=UTF-8");
PrintWriter out = response.getWriter();
JSONObject json = new JSONObject();
json.put("info", b);
out.write(json.toString());
out.flush();
out.close();
}
/**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to post.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("post");
String userName = request.getParameter("userName").trim();//获取前台传送过来要检测的用户名,并去掉两端空格
System.out.println("post"+userName);
boolean b=true;
if(!userName.isEmpty())
{
UserInfoSrvc infoservice = new UserInfoSrvc();
List<User> list=infoservice.search();
for(int i=0;i<list.size();i++)
{
if(list.get(i).getUserName().equals(userName))
{
b= false;
}
}
}
response.setContentType("application/json;charset=UTF-8");
PrintWriter out = response.getWriter();
JSONObject json = new JSONObject();
json.put("info", b);
out.write(json.toString());
out.flush();
out.close();
}
/**
* Initialization of the servlet. <br>
*
* @throws ServletException if an error occurs
*/
public void init() throws ServletException {
// Put your code here
}
}
CreateYZM文件
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.util.Random;
/**
* 验证码生成工具
* @author HXL
*
*/
public class CreateYZM {
private BufferedImage image;// 图像
private String str;// 验证码
private static char code[] = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray();
public static final String SESSION_CODE_NAME="code";
private CreateYZM() {
init();// 初始化属性
}
/*
* 取得RandomNumUtil实例
*/
public static CreateYZM Instance() {
return new CreateYZM();
}
/*
* 取得验证码图片
*/
public BufferedImage getImage() {
return this.image;
}
/*
* 取得图片的验证码
*/
public String getString() {
return this.str;
}
private void init() {
// 在内存中创建图象
int width = 85, height = 30;
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
// 获取图形上下文
Graphics g = image.getGraphics();
// 生成随机类
Random random = new Random();
// 设定背景色
g.setColor(getRandColor(200, 250));
g.fillRect(0, 0, width, height);
// 设定字体
g.setFont(new Font("Times New Roman", Font.PLAIN, 18));
// 随机产生100条干扰线,使图象中的认证码不易被其它程序探测到
g.setColor(getRandColor(160, 200));
for (int i = 0; i < 100; i++) {
int x = random.nextInt(width);
int y = random.nextInt(height);
int xl = random.nextInt(12);
int yl = random.nextInt(12);
g.drawLine(x, y, x + xl, y + yl);
}
// 取随机产生的认证码(5位)
String sRand = "";
for (int i = 0; i < 5; i++) {
String rand = String.valueOf(code[random.nextInt(code.length)]);
sRand += rand;
// 将认证码显示到图象中
g.setColor(new Color(20 + random.nextInt(110), 20 + random.nextInt(110), 20 + random.nextInt(110)));
// 调用函数出来的颜色相同,可能是因为种子太接近,所以只能直接生成
g.drawString(rand, 13 * i + 6, 22);
}
// 赋值验证码
this.str = sRand;
// 图象生效
g.dispose();
// ByteArrayInputStream input = null;
// ByteArrayOutputStream output = new ByteArrayOutputStream();
// try {
// ImageOutputStream imageOut = ImageIO.createImageOutputStream(output);
// ImageIO.write(image, "JPEG", imageOut);
// imageOut.close();
// input = new ByteArrayInputStream(output.toByteArray());
// } catch (Exception e) {
// System.out.println("验证码图片产生出现错误:" + e.toString());
// }
// this.image = input
this.image = image;/* 赋值图像 */
}
/*
* 给定范围获得随机颜色
*/
private Color getRandColor(int fc, int bc) {
Random random = new Random();
if (fc > 255)
fc = 255;
if (bc > 255)
bc = 255;
int r = fc + random.nextInt(bc - fc);
int g = fc + random.nextInt(bc - fc);
int b = fc + random.nextInt(bc - fc);
return new Color(r, g, b);
}
}
GetYZMServlet.java文件
import java.io.IOException;
import java.io.PrintWriter;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class GetYZMServlet extends HttpServlet {
/**
* Constructor of the object.
*/
public GetYZMServlet() {
super();
}
/**
* Destruction of the servlet. <br>
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
/**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 通知浏览器不要缓存
response.setHeader("Expires", "-1");
response.setHeader("Cache-Control", "no-cache");
response.setHeader("Pragma", "-1");
CreateYZM yzm = CreateYZM.Instance();
// 将验证码输入到session中,用来验证
String code = yzm.getString();
request.getSession().setAttribute("code", code);
//System.out.println("123");
// 输出打web页面
response.setContentType("image/jpg");
ImageIO.write(yzm.getImage(),"jpg",response.getOutputStream()); //输出图片
}
/**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to post.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out
.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
out.println("<HTML>");
out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>");
out.println(" <BODY>");
out.print(" This is ");
out.print(this.getClass());
out.println(", using the POST method");
out.println(" </BODY>");
out.println("</HTML>");
out.flush();
out.close();
}
/**
* Initialization of the servlet. <br>
*
* @throws ServletException if an error occurs
*/
public void init() throws ServletException {
// Put your code here
}
}
IsUserLoginServlet.java文件
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import net.sf.json.JSONObject;
public class IsUserLoginServlet extends HttpServlet {
/**
* Constructor of the object.
*/
public IsUserLoginServlet() {
super();
}
/**
* Destruction of the servlet. <br>
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
/**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out
.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
out.println("<HTML>");
out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>");
out.println(" <BODY>");
out.print(" This is ");
out.print(this.getClass());
out.println(", using the GET method");
out.println(" </BODY>");
out.println("</HTML>");
out.flush();
out.close();
}
/**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to post.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("application/json;charset=UTF-8");
PrintWriter out = response.getWriter();
JSONObject json = new JSONObject();
HttpSession hassession = request.getSession();
if(hassession !=null)
{
Object loginName = hassession.getAttribute("loginUser");
Object uid = hassession.getAttribute("uid");
int id = -1;
if(uid!=null)
id = Integer.valueOf(uid.toString());
// System.out.println("post");
if(loginName!=null &&loginName.toString()!= null && id>=0)
{
UserInfoSrvc srvc = new UserInfoSrvc();
User user = srvc.searchById(id);
json.put("info", "true");
json.put("userName", loginName.toString());
json.put("introduce",user.getIntroduce());
json.put("picSrc", user.getPicSrc());
json.put("uid",uid.toString());
}
}
else
{
json.put("info", "false");
}
out.write(json.toString());
out.flush();
out.close();
}
/**
* Initialization of the servlet. <br>
*
* @throws ServletException if an error occurs
*/
public void init() throws ServletException {
// Put your code here
}
}
LoginServlet.java文件
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONObject;
public class LoginServlet extends HttpServlet {
/**
* Constructor of the object.
*/
public LoginServlet() {
super();
}
/**
* Destruction of the servlet. <br>
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
/**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out
.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
out.println("<HTML>");
out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>");
out.println(" <BODY>");
out.print(" This is ");
out.print(this.getClass());
out.println(", using the GET method");
out.println(" </BODY>");
out.println("</HTML>");
out.flush();
out.close();
}
/**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to post.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String userName = request.getParameter("userName").trim();//根据前台设置的键获取值,获取用户名,并去掉两端的空格
String pwd = request.getParameter("pwd").trim();//获取密码
System.out.println(userName+"---"+pwd);
boolean b=false;//标识是否存在该用户
if(!userName.isEmpty() && !pwd.isEmpty())//如果用户名和密码不为空
{
UserInfoSrvc srvc=new UserInfoSrvc();
List<User> lst= srvc.search();//获取所有用户数据
if(!lst.isEmpty()&& lst.size()>0)//用户数据条数>0
{
for(int i=0;i<lst.size();i++)//遍历集合,匹配用户
{
//System.out.println(lst.get(i).getUserName()+"-["+lst.get(i).getPwd()+"]");
if( lst.get(i).getUserName().equals(userName) && lst.get(i).getPwd().equals(pwd) ) //存在此用户
{
b=true;
//request.getSession().setAttribute("introduce",lst.get(i).getIntroduce());
request.getSession().setAttribute("uid",lst.get(i).getUid());//将用户ID保存到session中
break;
}
}
}
}
JSONObject json = new JSONObject();
if(b)
{
request.getSession().setAttribute("loginUser",userName);//登录状态保存机制,用session保存当前登录用户名
json.put("info", "true");//可以看做键值对数据,前台可以根据键"info"获取数据"ture"
}
else
{
json.put("info", "false");
}
response.setContentType("application/json;charset=UTF-8"); //设置返回给前台的数据格式为json,字符集为UTF-8
PrintWriter out = response.getWriter();
out.write(json.toString());//返回数据给前台
out.flush();
out.close();
}
/**
* Initialization of the servlet. <br>
*
* @throws ServletException if an error occurs
*/
public void init() throws ServletException {
// Put your code here
}
}
RegiserServlet.java文件
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONObject;
public class RegisterServlet extends HttpServlet {
/**
* Constructor of the object.
*/
public RegisterServlet() {
super();
}
/**
* Destruction of the servlet. <br>
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
/**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out
.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
out.println("<HTML>");
out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>");
out.println(" <BODY>");
out.print(" This is ");
out.print(this.getClass());
out.println(", using the GET method");
out.println(" </BODY>");
out.println("</HTML>");
out.flush();
out.close();
}
/**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to post.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String userName = request.getParameter("userName").trim();//获取要注册的用户名,并去掉两端空格
String pwd = request.getParameter("pwd").trim();//获取密码
System.out.println("post--"+userName+"--"+pwd);
String b = "false";
String yzm = request.getParameter("yzm").trim();//获取用户输入的验证码
String codeSession = (String)request.getSession().getAttribute("code"); //这是后台生成的验证码
//System.out.println(codeSession);
if(codeSession.equalsIgnoreCase(yzm))//验证码匹配成功
{
if(!userName.isEmpty() && !pwd.isEmpty() )
{
UserInfoSrvc infoservice = new UserInfoSrvc();
if(infoservice.insert(userName, pwd))
{
b = "true";
}
}
}
else
{
b = "yzmerror";
}
response.setContentType("application/json;charset=UTF-8");
PrintWriter out = response.getWriter();
JSONObject json = new JSONObject();
json.put("info", b);
out.write(json.toString());
out.flush();
out.close();
}
/**
* Initialization of the servlet. <br>
*
* @throws ServletException if an error occurs
*/
public void init() throws ServletException {
// Put your code here
}
}
User.java文件
public class User {
private int uid;
private String userName;
private String pwd;
private String picSrc;
private String introduce;
public int getUid() {
return uid;
}
public void setUid(int uid) {
this.uid = uid;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
public String getPicSrc() {
return picSrc;
}
public void setPicSrc(String picSrc) {
this.picSrc = picSrc;
}
public String getIntroduce() {
return introduce;
}
public void setIntroduce(String introduce) {
this.introduce = introduce;
}
}
UserInfodao.java文件
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
public class UserInfoDao {
public void insert(String userName,String pwd)//添加用户
{
Connection conn = null;
Statement stmt = null;
try {
// 导入驱动
Class.forName("com.mysql.jdbc.Driver");
// 连接通道 3306:端口号 mytestdatabase:要连接的数据库名称 root:数据库用户名 123:密码
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mytestdatabase","root","123");
// 创建SQL语句,添加数据
String sql = "INSERT INTO usersinfo " +"(userName,pwd) VALUES ( '"+userName+"','"+pwd+"')";
//执行SQL语句
stmt = conn.createStatement();
stmt.executeUpdate(sql);
} catch (Exception e) {
e.printStackTrace();
}
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
public List<User> search() {//查询所有
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
List<User> list = new ArrayList<User>();
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mytestdatabase", "root", "123");
String sql = "SELECT * FROM usersinfo";
stmt = conn.createStatement();
rs = stmt.executeQuery(sql);
//一行一条数据
while(rs.next()){
User user = new User();
user.setUid(rs.getInt(1));
user.setUserName(rs.getString(2));
user.setPwd(rs.getString(3));
user.setPicSrc(rs.getString(4));
user.setIntroduce((rs.getString(5)));
list.add(user);
}
} catch (Exception e) {
e.printStackTrace();
}
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
return list;
}
public void updateById(int uid,String name,String pwd,String picSrc,String introduce) //修改用户信息
{
Connection conn = null;
Statement stmt = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mytestdatabase", "root", "123");
String sql1 = "UPDATE usersinfo SET userName = '"+name+"' WHERE id = '"+uid+"'";
String sql2 = "UPDATE usersinfo SET pwd = '"+pwd+"' WHERE id = '"+uid+"'";
String sql3 = "UPDATE usersinfo SET picSrc = '"+picSrc+"' WHERE id = '"+uid+"'";
String sql4 = "UPDATE usersinfo SET introduce = '"+introduce+"' WHERE id = '"+uid+"'";
stmt = conn.createStatement();
stmt.executeUpdate(sql1);
stmt.executeUpdate(sql2);
stmt.executeUpdate(sql3);
stmt.executeUpdate(sql4);
} catch (Exception e) {
e.printStackTrace();
}
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
public void deleteById(int uid) //根据ID删除用户
{
Connection conn = null;
Statement stmt = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mytestdatabase", "root", "123");
String sql = "DELETE FROM usersinfo WHERE id = '"+uid+"'";
stmt = conn.createStatement();
stmt.executeUpdate(sql);
} catch (Exception e) {
e.printStackTrace();
}
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
userInfoSrvc.java文件
import java.util.List;
public class UserInfoSrvc {
public List<User> search() //从数据库中获取所有用户数据,并放到list集合
{
UserInfoDao udao=new UserInfoDao();
return udao.search();
}
public boolean insert(String userName,String pwd)//添加用户
{
if(userName.isEmpty() || pwd.isEmpty())//如果用户名或密码为空,不进行添加
{
return false;
}
UserInfoDao udao=new UserInfoDao();//创建一个数据库操作类
List<User> list = udao.search();//读取数据库所有的用户数据,并放到list集合
for(int i=0;i<list.size();i++)//检测用户名是否已存在
{
if( list.get(i).getUserName().equals(userName)) //如果用户名已存在,不添加
{
return false;
}
}
udao.insert(userName, pwd);//添加用户
return true;
}
public boolean updateById(int uid,String name,String pwd,String picSrc,String introduce) //更新用户信息
{
if(!name.isEmpty() && !pwd.isEmpty())//如果姓名以及密码不为空
{
UserInfoDao dao=new UserInfoDao();
List<User> list= dao.search();
for(int i=0;i<list.size();i++)//查找到要更新的用户
{
if(list.get(i).getUid()==uid)
{
dao.updateById(uid, name, pwd,picSrc,introduce);
return true;
}
}
}
//System.out.println("end");
return false;
}
public User searchById(int uid) //根据ID查找用户
{
UserInfoDao dao=new UserInfoDao();
List<User> list = dao.search();
if(uid>0)
{
for(int i=0;i<list.size();i++)
{
if(list.get(i).getUid()==uid)
{
return list.get(i);
}
}
}
return null;
}
public boolean deleteById(int uid) //根据用户删除用户
{
UserInfoDao dao=new UserInfoDao();
List<User> list=dao.search();
for(int i=0;i<list.size();i++)
{
if(list.get(i).getUid()==uid)
{
dao.deleteById(uid);
return true;
}
}
return false;
}
}
UserLogoffServlet.java文件
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import net.sf.json.JSONObject;
public class UserLogoffServlet extends HttpServlet {
/**
* Constructor of the object.
*/
public UserLogoffServlet() {
super();
}
/**
* Destruction of the servlet. <br>
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
/**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("get");
}
/**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to post.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("application/json;charset=UTF-8");
PrintWriter out = response.getWriter();
String userName = request.getParameter("userName").trim();
//System.out.println("off"+userName);
JSONObject json = new JSONObject();
if(!userName.isEmpty() && userName!="游客")
{
HttpSession sessionoff = request.getSession();
sessionoff.removeAttribute("loginUser");//移除对应session
//request.getSession().setAttribute("loginUser",null);
json.put("info", "true");
}
else
{
json.put("info", "false");
}
out.write(json.toString());
out.flush();
out.close();
}
/**
* Initialization of the servlet. <br>
*
* @throws ServletException if an error occurs
*/
public void init() throws ServletException {
// Put your code here
}
}
五、总结
1、有待完善
a)session问题
登录状态理论上需要客户端方面配合保存相关信息
每一个用户登录之后应该有一个session值对应。
在多个用户时需要依赖客户端(cookie机制)来分清"你"到底是谁
本例子中只使用session保存一个用户信息,没有使用cookie没有考虑并发等问题
b)传输编码问题
并没有完全统一使用UTF-8,在图片上传页面的编码是GBK,因为设置为UTF-8格式中文会乱码。
2、生成验证码工具类问题(原因:jdk1.8不兼容;解决方法:使用jdk1.6版本)
添加使用jdk1.6版本
3、图片上传,需要导入jspsmartuoload.jar包