servlet实现登录过滤

控制层:

package com.product.dbutil.login.action;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

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

import com.product.dbutil.login.dao.LoginDao;
import com.product.dbutil.login.service.LoginService;
/**
 * MVC模式 一个控制层action 一个数据访问层dao,一个接口service
 * 接口定义一个登录功能规范, dao层实现对数据库的访问
 * action层获得客户端提交的表单信息,调用dao层访问数据库,若有返回真在做界面跳转。
 * @author yqq
 *
 */
public class LoginAction extends HttpServlet {

	private LoginService service;//接口

	/**
	 * Constructor of the object.
	 */
	public LoginAction() {
		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 {

		this.doPost(request, response);
	}

	/**
	 * 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 path = request.getContextPath();
		//设置编码方式和客户端表单的编码方式相同
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();
		//获取表单的值
		String username = request.getParameter("username");
		String pswd = request.getParameter("pswd");
		List<Object> params = new ArrayList<Object>();
		params.add(username);
		params.add(pswd);
		//查询数据库的内容若有则返回true
		boolean flag = service.login(params);
		////////////////
		if (flag) {
			//登录界面(获得Session并设置属性在登录成功后才可以)
			request.getSession().setAttribute("username", username);
			response.sendRedirect(path + "/main.jsp");
		}
		out.flush();
		out.close();
	}

	/**
	 * Initialization of the servlet. <br>
	 *
	 * @throws ServletException
	 *             if an error occurs
	 */
	public void init() throws ServletException {
		// Put your code here
		service = new LoginDao();
	}

}

服务层:

接口定义中,方法默认是公有抽象的,不指明也可以。

package com.product.dbutil.login.service;

import java.util.List;

public interface LoginService {

	public boolean login(List<Object> params);
}

dao层:

package com.product.dbutil.login.dao;

import java.util.List;
import java.util.Map;

import com.product.dbutil.jdbc.JdbcUtils;
import com.product.dbutil.login.service.LoginService;

public class LoginDao implements LoginService {

	private JdbcUtils jdbcUtils = null;

	public LoginDao() {
		// TODO Auto-generated constructor stub
		jdbcUtils = new JdbcUtils();
	}

	public boolean login(List<Object> params) {
		// TODO Auto-generated method stub
		boolean flag = false;
		String sql = "select * from userinfo where username=? and pswd=?";
		try {
			jdbcUtils.getConnection();
			Map<String, Object> map = jdbcUtils.findSimpleResult(sql, params);
			flag = !map.isEmpty() ? true : false;
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		} finally {
			jdbcUtils.releaseConn();
		}
		return flag;
	}

}

过滤器:

package com.product.dbutil.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
 * web.xml配置中url-pattern配置为/*全过滤,配置为谁过滤谁
 * @author yqq_coder
 *
 */
public class MyFilter implements Filter {

	public MyFilter() {
		// TODO Auto-generated constructor stub
	}

	public void destroy() {
		// TODO Auto-generated method stub

	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		// TODO Auto-generated method stub
		// 过滤用户的请求,判断是否登录
		//先做类型转换
		HttpServletRequest httpServletRequest = (HttpServletRequest) request;
		HttpServletResponse httpServletResponse = (HttpServletResponse) response;
		//获得从定向路径
		String path = httpServletRequest.getContextPath();
		//设置请求和响应的编码
		httpServletRequest.setCharacterEncoding("utf-8");
		httpServletResponse.setCharacterEncoding("utf-8");
		//从请求中获得Session值,为空跳转
		String username = (String)httpServletRequest.getSession().getAttribute("username");

		if (username==null) {
			httpServletResponse.sendRedirect(path + "/index.jsp");
		}
		///////
		chain.doFilter(httpServletRequest, httpServletResponse);
	}

	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub

	}

}

web.xml配置

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
	xmlns="http://java.sun.com/xml/ns/javaee"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
	http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  <servlet>
    <description>This is the description of my J2EE component</description>
    <display-name>This is the display name of my J2EE component</display-name>
    <servlet-name>RegisterAction</servlet-name>
    <servlet-class>com.product.dbutil.register.action.RegisterAction</servlet-class>
  </servlet>
  <servlet>
    <description>This is the description of my J2EE component</description>
    <display-name>This is the display name of my J2EE component</display-name>
    <servlet-name>LoginAction</servlet-name>
    <servlet-class>com.product.dbutil.login.action.LoginAction</servlet-class>
  </servlet>
  <servlet>
    <description>This is the description of my J2EE component</description>
    <display-name>This is the display name of my J2EE component</display-name>
    <servlet-name>ProductAction</servlet-name>
    <servlet-class>com.product.dbutil.product.action.ProductAction</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>RegisterAction</servlet-name>
    <url-pattern>/servlet/RegisterAction</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>LoginAction</servlet-name>
    <url-pattern>/servlet/LoginAction</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>ProductAction</servlet-name>
    <url-pattern>/servlet/ProductAction</url-pattern>
  </servlet-mapping>

  <filter>
  <filter-name>MyFilter</filter-name>
  <filter-class>com.product.dbutil.filter.MyFilter</filter-class>
  </filter>

  <filter-mapping>
  <filter-name>MyFilter</filter-name>
  <url-pattern>/main.jsp</url-pattern>
  </filter-mapping>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>
时间: 2024-10-26 07:34:42

servlet实现登录过滤的相关文章

Spring MVC过滤器-登录过滤

以下代码是继承OncePerRequestFilter实现登录过滤的代码: /**  *  * @author geloin  * @date 2012-4-10 下午2:37:38  */ package com.test.spring.filter; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.FilterChain; import javax.servlet.ServletExce

JSP+servlet简单登录实例

一个简单的jsp+servlet实例,实现简单的登录 转载▼ http://blog.sina.com.cn/s/blog_5c5bc9070100z7wb.html     开发环境myeclipse+tomcat6 1.先创建web project,项目名为RegisterSystem, 2.在WebRoot 目录下创建login.jsp文件,只需修改body中的内容,如下所示: <body>     <form action="login">     us

JavaWeb过滤器——登录过滤

一般来说简单且常用的过滤器使用方法,我觉得除了配置字符编码的过滤之外就是登录器的过滤了 登录过滤器的主要过程可以 一句话来概括:首先在登录的时候把指定好的标志放在session中,操作过滤的时候根据session中的标志判断是否需要过滤.(好像是废话--) 过滤器代码: package com.ahoo.filter; import javax.servlet.*; import javax.servlet.http.HttpServletRequest; import javax.servle

使用servlet实现登录

简单的登录页面: <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>login</title> </head> <body> <!-- web3:项目名,在LoginServlet前必须加项目名,如果不加则默认视为工作空间地址 --> <form action="/web3/LoginServl

jsp+mysql+servlet的登录

登录代码 entity类 package com.wy.entity; public class User { private int id; private String username; private String password; private String email; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUsername()

java -------简单的基于jsp+servlet+jdbc登录

1 2 项目结构以及数据库表图片 3 4 5 package com.jmi.booklibmanage.service; 6 7 import java.sql.Connection; 8 import java.sql.DriverManager; 9 import java.sql.ResultSet; 10 import java.sql.SQLException; 11 import java.sql.Statement; 12 13 14 15 public class Studen

Servlet页面登录的数据库验证程序(一)

一.基本思想是MVC模式,一个登录页面login.jsp,一个服务器处理程序Servlet.java,一个MySql数据库userinfo. 另外还有相关的数据封装类User和数据库连接类GetData,如果要加入密码验证,可能还要一个错误处理页面error.jsp.在这个小实例中,为了思路简单一点,暂时没有密码验证. 使用的工具是MyEclipse2015. 由于设计jdbc数据库的应用,需要准备mysql-connector-java-5.1.26-bin.jar开发包,拷贝到 WEB_IN

jsp和servlet 简单登录界面(不连接数据库)

1.首先说明一点,虽然很简单但是对于初学者 这个jsp和servlet的链接 我捣鼓了半天才算弄明白 jsp将请求提交到一个url,然后servlet获取也从这个url中获取请求的数据,两者的链接就在那个url jsp中的代码 文件名:login.jsp <%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%> <

使用Servlet技术~登录-02

为了更简洁的讲解,我只书写关键代码,只写思路. 场景:对一个人的信息进行录入,然后展示出来. 思路: 1.登录信息录入<录入页面>   username,      [text] gender,          [radio]    (female/male男女,必须保证name一致,默认选中请设置:checked="checked") isAccept,        [checkbox] (保证name属性值一致) date birthday; [text]