Servlet, JSP, JDBC, MySQL-based login modules (with filter usage and configuration)

Source: Internet
Author: User
Tags stub

The registration module of the previous article, this is the login module. Mainly includes the login main interface, and login related written loginaction, Logindao and Loginservice. and the configured filter. The detailed procedures and code are documented in the following logical order:

First, after clicking the login button in the index directory above, the JavaScript jumps to loginaction.

<script type= "Text/javascript" > Function login () {   var th = Document.form1;   if (th.username.value== "") {      alert ("Username cannot be empty!! ");      Th.username.focus ();      return;   }   if (th.pswd.value== "") {      alert ("Password cannot be empty!! ");      Th.pswd.focus ();      return;   }   Th.action= "<%=path%>/servlet/loginaction"; Th.submit ();} </script>

Second, is about login this event, need to create three files are Logingaction, is a servlet. Loginservice is an interface, Logindao implement the above interface, query the database. The registration module in front of the same ha.

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 D Oget method of the servlet. <br> * This method was called when a form have 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 IOExceptionIf 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 was called when a form have 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 (HTT Pservletrequest 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 ("Login Failed"); }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 ();}}

Important: Create a session and save the username in the pass to main.jsp. In the main.jsp, I want to know who is currently logged in.

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;}}

Third, if the login is successful, then jump to the Main.jsp interface:


The main.jsp code is as follows:

<%@ 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 ">
You can see that main.jsp in writing using the <frameset> tag, nested inside <frame&gt, respectively top.jsp left.jsp postdata.jsp. Instructions for use see: Link 1 Link 2

Added the bottom JSP to the index.jsp, using an iframe:

<iframe name= "Top" align= "Default" src= "<%=path%>/bottom.jsp"
frameborder=0 width=100% Scrolling=no height=88>
</IFRAME>

Just can compare the difference, see link 1 link 2 link 3 iframe used often with target use, see link 1 link 2

top.jsp left.jsp postdata.jsp This three code is not affixed, in the source.

IV: Use of filter

The result is that the browser input http://localhost:8080/xianfengYan/main.jsp is not logged in at this time, no authentication, we do not want visitors to visit this interface, so we need to add a filter to filter, directly to the page to index.jsp .

New 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//Filter the user's request to determine whether to log in 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}}

Then configure it in the 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 in the filter page, we specify the filter/main.jsp this interface.

Code DOWNLOAD Link:


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.