Servlet Learning Notes 3 - Logon Exercise

1. Ideas:

1. Create a login page

Create a servlet to process login page requests

2. Click Login to complete the login operation

) Browser sends request to server (user information + other data)

The server calls the corresponding servlet for processing

3. Complete user login verification in the servlet

* Need to connect to the database (create user tables in mySql)

2. Code Procedure

1. New servlet

(1) Directory structure

(2) Code

PageServlet

package com.bjsxt.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class PageServlet extends HttpServlet {
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		//Format Response Encoding
			resp.setContentType("text/html;charset=utf-8");
		//Get Request Information
		//Processing Request
		//Response processing results
			//Get request scope data
				String str=(String) req.getAttribute("str")==null?"":(String) req.getAttribute("str");
				resp.getWriter().write("<html>");
				resp.getWriter().write("<head>");
				resp.getWriter().write("</head>");
				resp.getWriter().write("<body>");
				resp.getWriter().write("<font color='red' size='20px'>"+str+"</font>");
				resp.getWriter().write("<form action='login' method='get'>");
				resp.getWriter().write("User name:<input type='text' name='uname' value=''/><br/>");
				resp.getWriter().write("Password:<input type='password' name='pwd' value=''/><br/>");
				resp.getWriter().write("<input type='submit'  value='Sign in'/><br/>");
				resp.getWriter().write("</form>");
				resp.getWriter().write("</body>");
				resp.getWriter().write("</html>");

			}
			
	}

 LoginServlet

package com.bjsxt.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.bjsxt.pojo.User;
import com.bjsxt.service.LoginService;
import com.bjsxt.service.impl.LoginServiceImpl;

public class LoginServlet extends HttpServlet {
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		//Set request encoding format:
			req.setCharacterEncoding("utf-8");
		//Format Response Encoding
			resp.setContentType("text/html;charset=utf-8");
		//Get Request Information
			String uname=req.getParameter("uname");
			//uname=new String(uname.getBytes("iso8859-1"),"utf-8"); //Use String for data re-encoding
			String pwd=req.getParameter("pwd");
			System.out.println(uname+":"+pwd);


		//Processing Request Information
			//Get Business Tier Objects
			LoginService ls=new LoginServiceImpl();
			User u=ls.checkLoginService(uname, pwd);
			System.out.println(u);


		//Response processing results
			if(u!=null){
				//Create Cookie info to exempt login for three days.
					Cookie c=new Cookie("uid", u.getUid()+"");
					//Set Cookie Validity Period
					c.setMaxAge(3*24*3600);
					c.setPath("/login/ck");
					//Add Cookie Information
					resp.addCookie(c);
				//Request Forwarding
					//req.getRequestDispatcher("main").forward(req, resp);
				//redirect
				resp.sendRedirect("/login/main");
				return;
			}else{
				//Using request object to flow data between different Servlet s
				req.setAttribute("str", "ERROR Incorrect username or password");
				//Use Request Forwarding
				req.getRequestDispatcher("page").forward(req, resp);
				return;
			}
	}
}

2. Entity Classes

3.service

impl

package com.bjsxt.service.impl;

import com.bjsxt.dao.LoginDao;
import com.bjsxt.dao.impl.LoginDaoImpl;
import com.bjsxt.pojo.User;
import com.bjsxt.service.LoginService;

public class LoginServiceImpl implements LoginService{
	//Create Dao Layer Over
	LoginDao ld=new LoginDaoImpl();
	//Verify user login information
	@Override
	public User checkLoginService(String uname, String pwd) {
		
		return ld.checkLoginDao(uname, pwd);
	}


	//Check Cookie Information
	@Override
	public User checkUidService(String uid) {
		return ld.checkUidDao(uid);
	}
	
}

 

4.Dao

package com.bjsxt.dao;

import com.bjsxt.pojo.User;

public interface LoginDao {
	//Get user information based on user name and password
	User checkLoginDao(String uname,String pwd);
	//Get user information from uid
	User checkUidDao(String uid);
}

DaoImpl

package com.bjsxt.dao.impl;

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

import com.bjsxt.dao.LoginDao;
import com.bjsxt.pojo.User;

public class LoginDaoImpl implements LoginDao{

	@Override
	public User checkLoginDao(String uname, String pwd) {
		//Declare Jdbc objects
		Connection conn=null;
		PreparedStatement ps=null;
		ResultSet rs=null;
		//Declare Data Store Objects
		User u=null;
		try {
			//Load Driver
			Class.forName("com.mysql.jdbc.Driver");
			//Get Connection Object
			conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/407","root","root");
			//Create Sql Command
			String sql="select * from t_user where uname=? and pwd=?";
			//Create Sql Command Object
			ps=conn.prepareStatement(sql);
			//Assigning values to placeholders
			ps.setString(1, uname);
			ps.setString(2, pwd);
			//implement
			rs=ps.executeQuery();
			//Traverse execution results
			while(rs.next()){
				u=new User();
				u.setUid(rs.getInt("uid"));
				u.setUname(rs.getString("uname"));
				u.setPwd(rs.getString("pwd"));
			}
			//close resource
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			try {
				rs.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			try {
				ps.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			try {
				conn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		//Return
		return u;
	}
	//Get user information from UID
	@Override
	public User checkUidDao(String uid) {
			//Declare Jdbc objects
				Connection conn=null;
				PreparedStatement ps=null;
				ResultSet rs=null;
				//Declare Data Store Objects
				User u=null;
				try {
					//Load Driver
					Class.forName("com.mysql.jdbc.Driver");
					//Get Connection Object
					conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/407","root","1234");
					//Create Sql Command
					String sql="select * from t_user where uid=?";
					//Create Sql Command Object
					ps=conn.prepareStatement(sql);
					//Assigning values to placeholders
					ps.setString(1, uid);
					//implement
					rs=ps.executeQuery();
					//Traverse execution results
					while(rs.next()){
						u=new User();
						u.setUid(rs.getInt("uid"));
						u.setUname(rs.getString("uname"));
						u.setPwd(rs.getString("pwd"));
					}
					//close resource
				} catch (Exception e) {
					e.printStackTrace();
				}finally{
					try {
						rs.close();
					} catch (SQLException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					try {
						ps.close();
					} catch (SQLException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					try {
						conn.close();
					} catch (SQLException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				//Return
				return u;
	}
		
}

 

Tags: SQL Java JDBC MySQL

Posted on Thu, 07 Nov 2019 08:52:36 -0800 by skippy111