基于Servlet、JSP、JDBC、MySQL的登录模块(含过滤器的使用和配置)

来源:互联网 发布:火炬之光2mac汉化补丁 编辑:程序博客网 时间:2024/04/27 21:57

接前文的注册模块,本篇是登录模块。主要包括登录主界面,和登录相关编写的LoginAction、LoginDao和LoginService。以及配置的Filter。下面按逻辑顺序记录详细过程和代码:

一、在前文的index目录点击登录按钮后,通过javascript跳转至LoginAction。

<script type="text/javascript"> function login(){   var th = document.form1;   if(th.username.value==""){      alert("用户名不能为空!!");      th.username.focus();      return ;   }   if(th.pswd.value==""){      alert("密码不能为空!!");      th.pswd.focus();      return ;   }   th.action="<%=path%>/servlet/LoginAction";th.submit();}</script>

二、就是关于登录这个事件,需要创建三个文件分别是LogingAction,是个Servlet。LoginService是个接口,LoginDao实现上面的接口,查询数据库。跟前文的注册模块一样的哈。

LogingAction.java

package com.product.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.login.dao.LoginDao;import com.product.login.service.LoginService;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 {request.setCharacterEncoding("utf-8");response.setContentType("text/html; charset=utf-8");String path = request.getContextPath();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);        boolean flag = service.login(params);        out.println("username = " + username);        out.println("pswd = " + pswd);                if(flag){        request.getSession().setAttribute("username", username);        response.sendRedirect(path + "/main.jsp");        }else{        out.println("登录失败 ");        }out.flush();out.close();}/** * Initialization of the servlet. <br> * * @throws ServletException if an error occurs */public void init() throws ServletException {// Put your code hereservice = new LoginDao();}}

要点:创建一个Session,将username存进去传递给main.jsp。也即在main.jsp的时候我要知道当前是谁在登录。

        if(flag){
        request.getSession().setAttribute("username", username);
        response.sendRedirect(path + "/main.jsp");
        }

LoginService.java

package com.product.login.service;import java.util.List;public interface LoginService {public boolean login(List<Object> params);}

LoginDao.java

package com.product.login.dao;import java.util.List;import java.util.Map;import com.product.jdbc.dbutil.JdbcUtils;import com.product.login.service.LoginService;public class LoginDao implements LoginService {private JdbcUtils jdbcUtils;public LoginDao(){jdbcUtils = new JdbcUtils();}@Overridepublic boolean login(List<Object> params) {// TODO Auto-generated method stubboolean 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){e.printStackTrace();}finally{jdbcUtils.releaseConn();}return flag;}}

三、这样如果登录成功的话就跳转到了main.jsp界面:


main.jsp代码如下:

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%><%String path = request.getContextPath();%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3c.org/TR/1999/REC-html401-19991224/frameset.dtd"><HTML xmlns="http://www.w3.org/1999/xhtml"><HEAD><TITLE>后台管理系统</TITLE><META http-equiv=content-type content="text/html; charset=utf-8"></HEAD><FRAMESET rows=105,* cols="*" bordercolor="04376E"><FRAME name=ads marginWidth=0 marginHeight=0 src="<%=path%>/top.jsp"frameBorder=0 noResize scrolling=no longDesc=""><FRAMESET rows=675 cols=198,* frameborder="yes"><FRAME name=list marginWidth=0 marginHeight=0 src="<%=path%>/left.jsp"frameBorder=0 noResize scrolling=yes longDesc=""><FRAME name=main marginWidth=0 marginHeight=0src="<%=path%>/postdata.jsp" frameBorder=0 scrolling=yes longDesc=""></FRAMESET><NOFRAMES></NOFRAMES></FRAMESET><body></body></HTML>

可以看到main.jsp在书写上利用了<frameset>标签,在里面嵌套<frame>,分别是top.jsp left.jsp postdata.jsp.使用说明参见:链接1 链接2

在index.jsp里增加了底部的jsp,使用的是iframe:

<IFRAME name="top" align="default" src="<%=path %>/bottom.jsp"
frameBorder=0 width=100% scrolling=no height=88>
<h1>&nbsp;</h1>
</IFRAME>

正好可以对比其区别,详见链接1 链接2 链接3  iframe使用时常常要和target配合使用,参见  链接1 链接2

top.jsp left.jsp postdata.jsp这三个的代码就不贴了,在源码里。

四:filter的使用

起因是浏览器直接输入http://localhost:8080/xianfengYan/main.jsp 这时还没有登录,没有验证,我们不希望游客访问这个界面,因此需要加个过滤器进行过滤,直接将页面跳转至index.jsp.

新建包package com.product.filter;

MyFilter.java

package com.product.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;public class MyFilter implements Filter {@Overridepublic void destroy() {// TODO Auto-generated method stub}@Overridepublic void doFilter(ServletRequest request, ServletResponse response,FilterChain chain) throws IOException, ServletException {// TODO Auto-generated method stub//过滤用户的请求,判断是否登录HttpServletRequest httpServletRequest = (HttpServletRequest)request;HttpServletResponse httpServletResponse = (HttpServletResponse)response;httpServletRequest.setCharacterEncoding("utf-8");httpServletResponse.setCharacterEncoding("utf-8");String path = httpServletRequest.getContextPath();String username = (String)httpServletRequest.getSession().getAttribute("username");if(username == null){httpServletResponse.sendRedirect(path + "/index.jsp");}chain.doFilter(httpServletRequest, httpServletResponse);}@Overridepublic void init(FilterConfig arg0) throws ServletException {// TODO Auto-generated method stub}}

然后再web.xml里进行配置:

<filter><filter-name>MyFilter</filter-name><filter-class>com.product.filter.MyFilter</filter-class></filter><filter-mapping><filter-name>MyFilter</filter-name><url-pattern>/main.jsp</url-pattern></filter-mapping>

url-pattern里表示过滤的页面,我们指定过滤/main.jsp这个界面。

代码下载链接:http://download.csdn.net/detail/yanzi1225627/7448175


7 0
原创粉丝点击