天天看点

韩顺平细说jsp购物车项目--用户登录及验证

index.jsp

<body>
   <jsp:forward page="/WEB-INF/login.jsp"></jsp:forward>
  </body>
           

为了安全,一般把jsp页面设置在web-inf 目录下面。然后留一个入口,往web-inf 跳转。

login.jsp

<body style="text-align:center; margin:0 auto; ">
    <h1>登陆界面</h1>
    <form action="/shopping/GoHallUI" method="post"><!-- 注意ACTION的值 -->
    <div class="login">
    <table  align="center">
    <tr><td>用户ID:</td><td><input type="text" name="id"/></td></tr>
    <tr><td>密 码:</td><td><input type="password" name="password"/></td></tr>
    <tr><td><input type="submit" value="登陆"/></td><td><input type="reset" value="清空"/></td></tr>
    </table>
    </div>
    </form>   
</body>
           

一个简单的登录页面,输入用户名和密码,提交给GoHallUI这个servlet处理

GoHallUI

public class GoHallUI extends HttpServlet {
	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out=response.getWriter();
		
		//得到从登陆页面传递的用户ID和密码
		String id=request.getParameter("id");
		String p=request.getParameter("password");	
				
		//先判断该用户是否登录或此用户曾登录的session是否已经过期
		if(request.getSession().getAttribute("loginUser")!=null){
			//给下一个页面准备要显示的数据
			BookService bookservice=new BookService();
			ArrayList al=bookservice.getAllBook();
			
			//把要显示的数据放在request,原因是request的生命周期最短
			request.setAttribute("books", al);
			request.getRequestDispatcher("/WEB-INF/hall.jsp").forward(request, response);
			return;//不要往下走了!
		}		
		
		//创建一个Users对象()//String->int
		Users loginUser=new Users(Integer.parseInt(id),p);		
		//使用业务逻辑类,完成验证。
		UsersService usersService=new UsersService();
		if(usersService.checkUser(loginUser)){
			//说明是合法用户,跳转到购物大厅.
			
			//把用户信息放到session中
			request.getSession().setAttribute("loginUser",loginUser);
			
			//创建一个购物车
			MyCart myCart=new MyCart();
			request.getSession().setAttribute("myCart", myCart);
			
			
			
			//给下一个页面hall.jsp准备要显示的数据
			BookService bookService=new BookService();
			ArrayList al=bookService.getAllBook();			
			//把要显示的数据放入request,原因是request对象的生命周期最短
			request.setAttribute("books", al);
			
			request.getRequestDispatcher("/WEB-INF/hall.jsp").forward(request, response);
		}else{
			//不合法
			request.getRequestDispatcher("/WEB-INF/login.jsp").forward(request, response);
		}
	
	}	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		this.doGet(request, response);
	}
}
           

这个servlet干了很多事,暂时先看用户登录与验证那一块儿。

1.创建了users对象

users.java

package com.wxh.domain;
//这是一个javabean,和数据库中的users表对应。
public class Users {
	private int id;	
	private String name;
	private String pwd;
	private String email;
	private String tel;
	private int grade;	
	
	public Users(int id, String pwd) {
		super();
		this.id = id;
		this.pwd = pwd;
	}
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getPwd() {
		return pwd;
	}
	public void setPwd(String pwd) {
		this.pwd = pwd;
	}
	public String getEmail() {
		return email;
	}
	public void setEmail(String email) {
		this.email = email;
	}
	public String getTel() {
		return tel;
	}
	public void setTel(String tel) {
		this.tel = tel;
	}
	public int getGrade() {
		return grade;
	}
	public void setGrade(int grade) {
		this.grade = grade;
	}
}
           

2.使用了UsersService类

UsersService.java

package com.wxh.service;

import java.util.ArrayList; 
import com.wxh.utils.*;
import com.wxh.domain.Users;

//这是专门处理业务逻辑的类
//处理和users表相关的业务逻辑
public class UsersService {
	//验证用户是否合法的方法,合法则返回该用户的其他信息
	//不仅判断用户合不合法,还要把用户本身作为一个数据拿来用
	public boolean checkUser(Users user){
		//到数据库去验证
		String sql="select * from users where id=? and pwd=?";
		String paras[]={user.getId()+"",user.getPwd()};
		ArrayList al=new SqlHelper().executeQuery(sql, paras);
		if(al.size()==0){
			return false;
		}else{
			Object[] objects=(Object[])al.get(0);
			//把对象数组封装到Users对象			
			user.setName((String)objects[1]);
			user.setEmail((String)objects[3]);
			user.setGrade(Integer.parseInt(objects[5].toString()));
			//在用户登陆后同时还需要取出该用户的其他信息,故封装到一个对象
			return true;
		}	
	}
}
           

在这里UsersService又调用了SqlHelper类来完成一些对数据库的操作。

SqlHelper.java

//这是工具类,主要用于完成对数据库的crud操作
public class SqlHelper 
{	
	private static Connection ct=null;//连接
	private static ResultSet rs=null;//结果
	private static PreparedStatement ps=null;

	public ArrayList executeQuery(String sql,String []paras)
	{
		ArrayList al=new ArrayList();
		try {
			ct=DBUtil.getCon();
			ps=ct.prepareStatement(sql);
			//给sql问号赋值
			for (int i = 0; i < paras.length; i++) 
			{
				ps.setString(i+1, paras[i]);
			}
			rs=ps.executeQuery();
			//非常有用
			ResultSetMetaData rsmd=rs.getMetaData();
			//用法rs可以的到有多少列
			int columnNum=rsmd.getColumnCount();
			//循环从a1中取出数据封装到ArrayList
			while(rs.next())
			{
				Object []objects=new Object[columnNum];
				for(int i=0;i<objects.length;i++)
				{
					objects[i]=rs.getObject(i+1); //返回对象数组
				}
				al.add(objects);
			}
			return al;
			} catch (Exception e) 
			{
				e.printStackTrace();
				throw new RuntimeException(e.getMessage());
		}finally
		{
			DBUtil.close(rs,ps,ct);
		}
		
	}
	public ResultSet executeQuery(String sqlstr) 
	{
		Statement stmt = null;
		try
		{
			//得到连接
			ct=DBUtil.getCon();
			//ps=ct.prepareStatement(sqlstr);
			stmt = ct.createStatement();
			//创建结果集
			 rs = stmt.executeQuery(sqlstr); 
			//将结果集返回
			return rs;
		}
		catch(SQLException e)
		{
			System.out.print("错误");
		}
		return null;
	}
}
           

这里又用到了DBUtil 类

DBUtil.java

这是数据库工具类,用于得到连接和关闭连接
public class DBUtil 
{
	private static Connection ct=null;//连接
	private static ResultSet rs=null;//结果
	private static PreparedStatement ps=null;
	//连接数据库参数
	private static String url = "";	
	private static String drivername = "";
	private static String username = "";
	private static String password = "" ;
	//加载驱动
static{
		try 
			{				
				Properties properties=new Properties();
				InputStream is=DBUtil.class.getClassLoader().getResourceAsStream("com/wxh/utils/dbinfo.properties");
				properties.load(is);
				//属性文件读取信息
				drivername=properties.getProperty("driver");
				username=properties.getProperty("username");
				password=properties.getProperty("password");
				url=properties.getProperty("url");
			} catch (Exception e) {
				e.printStackTrace();
				System.exit(-1);
			}
		}

//得到连接
public static  Connection getCon()
{
	try {
		Class.forName(drivername);
		ct= DriverManager.getConnection(url,username,password);//注意配置文件
	} catch (Exception e) {
		e.printStackTrace();
	}
	return ct;//谁调用谁拿到Connection
}
public static void main(String args [])
{
	
	System.out.println(drivername);
	System.out.println(username);
	System.out.println(password);
	System.out.println(url);
}
//关闭资源函数
public static void close(ResultSet rs,Statement ps,Connection ct)
{
	if(rs!=null)
	{	
			try
		{
				rs.close();
		}catch(Exception e)
		{
			
		}
		rs=null;//使用垃圾回收
	}
	if(ps!=null)
	{
		try
		{
				ps.close();
		}catch(SQLException e)
		{
			e.printStackTrace();
		}
		ps=null;
	}
	
	if(ct!=null)
	{
		try
		{
				ct.close();
		}catch(SQLException e)
		{
			e.printStackTrace();
		}
		ct=null;
	}
		
}

}	
           

存放数据库连接参数的属性文件

dbinfo.properties

url=jdbc:oracle:thin:@127.0.0.1:1521:test
driver=oracle.jdbc.driver.OracleDriver
 username=hr
 password=hr
           

———摘自《韩顺平细说jsp》