Session和Jdbc编程
1、实验内容:
编写一个login.html:用户可以输入用户名,角色和密码登陆(需要用post方法提交)编写一个名为loginservlet的servlet:要能够接收login.html的表单数据,通过查询用户表的用户名和密码,判断用户登录凭证是否正确。
用户登录后, loginservlet同时为该用户对应的session添加用户名和用户登录时间等两个属性
登录成功后,将流程跳转到url pattern: /shop
注意:servlet流程跳转:
response.sendRedirect(url)
getRequestDispatcher是服务器内部跳转,地址栏信息不变,只能跳转到web应用内的网页。
sendRedirect是页面重定向,地址栏信息改变,可以跳转到任意网页。
编写一个名为shopservlet的servlet,它对应的url pattern为 前述 /shop
在shopservlet里,获取用户的session,通过判断能否取出session的名字分析用户是否已登录:若已经登陆,则通过response发回一个简单的商品描述页面,并在页面上方显示当前登录的用户名,以及cookie里面的登录次数;若未登陆,则通过request.getRequestDispatcher跳转到login.html
2、实验步骤:
(1)编写名为login.html的文件,用于提交表单数据。注意表单的提交地址应该为loginservlet,提交方式为“post”
(2)编写名为loginservlet的servlet,用于将表单提交的用户名和密码与数据库中的用户表信息比对,如果完全一致则登陆成功,将用户的登陆信息等记录到session之中,将页面重定向至shop的servlet。否则将页面重定向至shopservlet。
(3)编写名为shopservlet的servlet,通过注释的方法将它对应的url pattern设置为“/shop”,通过获取session中的name是否为空来判断用户是否已经登陆,如果未登陆则通过request.getRequestDispatcher("login.html").forward(request, response);
来将页面转回登陆页面方便用户登陆。如果session中已经含有用户名那么说明该用户已经登陆则显示商品信息、登陆时间等。
3、主要代码:
Login.html文件:
<!DOCTYPE html>
<html>
<head>
<meta charset="gb2312">
<title>登陆页面</title>
</head>
<body>
<div>
<table>
<form action="loginservlet" method="post">
<td><label for="name1">用户名字:</label>
<td><input type="text" name="name1" id="name1">
<tr></tr>
<br>
<td><label for="name2">密码: </label>
<td><input type="password" name="name2" id="name2">
<tr></tr>
<br>
<td><input type="submit" value="登陆">
<td><input type="reset" value="重置">
</form>
</table>
</div>
</body>
</html>
loginservlet文件:
package servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.mysql.jdbc.PingTarget;
import java.awt.List;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.sql.*;
/**
* Servlet implementation class loginservlet
*/
@WebServlet("/loginservlet")
public class loginservlet extends HttpServlet {
public void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException{
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("gb2312");
PrintWriter out=response.getWriter();
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn=null;
conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/webdb", "root","*****");
PreparedStatement pstmt=conn.prepareStatement(""
+ "SELECT* FROM webdb WHERE web_name=?");
pstmt.setString(1, request.getParameter("name1"));
ResultSet rs=pstmt.executeQuery();
if(rs.next())
{
String pw=rs.getString("pass_word");
String repw=request.getParameter("name2");
//注意字符串的比较不能直接用==
if(pw.equals(repw))
{
out.println(""+request.getParameter("name1")+"你已经登陆成功");
HttpSession session=request.getSession();
session.setAttribute("name", request.getParameter("name1"));//用户名
session.setAttribute("logintime", new Date(session.getCreationTime()));//用户登陆时间
//用户登陆次数统计
//*****************************修改成记录当前用户的登陆次数***********************************************
String accessCountName="accessCount"+request.getParameter("name1");
Integer accessCount=(Integer)session.getAttribute(""+accessCountName);
if(accessCount==null)
{
accessCount=new Integer(1);
}else {
accessCount=accessCount+1;
}
//session.setAttribute("accessCount", accessCount);
session.setAttribute(""+accessCountName, accessCount);//用于将指定用户的登陆次数传给服务器
session.setAttribute("accessCountNameStr", accessCountName);//用于将唯一用户名通过session传给服务器
//设置重定向的路径
response.sendRedirect("shop");
out.println("用户名"+session.getAttribute("name"));
out.println("用户登陆时间"+session.getAttribute("logintime"));
}else {
out.println("密码错误请重新输入");
HttpSession session=request.getSession();
session.setAttribute("name",null);
//response.setContentType("text/html;charset=utf-8");
response.sendRedirect("shop");
}
}else {
out.println("你还不是本网站的注册用户");
HttpSession session=request.getSession();
session.setAttribute("name",null);
response.sendRedirect("shop");
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//request.getParameter("name1")+"您好!您的信息我已经收到"
/*out.println("<!DOCTYPE html>"+
"<html>"+
"<head><meta charset='gb2312'><title>myfristwebproject</title></head>"+
"<body>"+
""+request.getParameter("name1")+"您好!您的信息我已经收到"+
"</body>"+
"</html>");
*/
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
processRequest(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
processRequest(request, response);
}
}
Shopservlet文件:
package servlet;
import java.io.IOException;
import java.io.PrintWriter;
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;
/**
* Servlet implementation class shopservlet
*/
@WebServlet("/shop")
public class shopservlet extends HttpServlet {
public void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException{
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("gb2312");
PrintWriter out=response.getWriter();
HttpSession session=request.getSession();
String name=(String)session.getAttribute("name");
//out.print("用户名字"+name);
if(name==null||"".equals(name))
{
out.println("用户未登陆");
request.getRequestDispatcher("login.html").forward(request, response);
//response.sendRedirect("file:///C:/java%20workspace/loginproject/WebContent/login.html");
}else {
out.println("<!DOCTYPE html>"+
"<html>"+
"<head><meta charset='gb2312'><title>欢迎</title></head>"+
"<body>"+
"<lable>用户名:</lable>"+session.getAttribute("name")+
"<lable>用户登陆次数:</lable>"+/*session.getAttribute("accessCount")*/session.getAttribute(""+session.getAttribute("accessCountNameStr"))+
"<lable>用户登陆时间:</lable>"+session.getAttribute("logintime")+
"<div>"+
"<img src='file:///C:/java%20workspace/loginproject/phone.jpg' alt='图片下载失败' title='2500RNB'/>"+
"<br>"+
"<lable>荣耀10 全面屏AI摄影手机 6GB+64GB 游戏手机 幻影蓝全网通 移动联通电信4G 双卡双待 2500RNB</lable>"+
"</div>"+
"</body>"+
"</html>");
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
processRequest(request,response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
processRequest(request,response);
}
}
注意:
- html、servlet、图片都放在了同一个文件夹
- 本人数据库用的是mysql,使用数据库别忘了导入需要使用的包
- 此处html文件用的编码格式是gb2312,用utf-8会导致重定向回登陆页面出现乱码的情况