meet above Registration module for , This is the login module . It mainly includes the login main interface , And login related to the preparation of LoginAction、LoginDao and LoginService. And configuration Filter. The following records the specific process and code in logical order :

One 、 In the previous article index Folder click login button after . adopt javascript Jump to LoginAction.

<script type="text/javascript">
function login(){
var th = document.form1;
if(th.username.value==""){
alert(" The username cannot be empty ! .");
th.username.focus();
return ;
}
if(th.pswd.value==""){
alert("password Can't be empty ! ! ");
th.pswd.focus();
return ;
}
th.action="<%=path%>/servlet/LoginAction";
th.submit();
}
</script>

Two 、 It's about logging in , You need to create three files, each of which is LogingAction, It's a Servlet.LoginService It's an interface ,LoginDao Implement the above interface , Query the database .

The registration module is the same as above .

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(" 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 here
service = new LoginDao();
} }

The main points of : Create a Session, take username Put it in and pass it on to main.jsp.

Also in main.jsp I need to know who is currently logging 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();
}
@Override
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){
e.printStackTrace();
}finally{
jdbcUtils.releaseConn();
}
return flag;
} }

3、 ... and 、 If the login is successful, you will jump to main.jsp Interface :

watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQveWFuemkxMjI1NjI3/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="" />

main.jsp The 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">
<HTML xmlns="http://www.w3.org/1999/xhtml">
<HEAD>
<TITLE> Background management system </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=0
src="<%=path%>/postdata.jsp" frameBorder=0 scrolling=yes longDesc="">
</FRAMESET>
<NOFRAMES>
</NOFRAMES>
</FRAMESET>
<body>
</body>
</HTML>

Be able to see main.jsp Make use of in writing <frameset> label . Nested inside <frame>, They are top.jsp left.jsp postdata.jsp. For instructions, please refer to : link 1 link 2

stay index.jsp Added the bottom jsp, It uses iframe:

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

It's just the difference , See link 1 link 2 link 3  iframe When using it, always use it with target In combination with . See also   link 1 link 2

top.jsp left.jsp postdata.jsp These three codes will not be pasted . In the source code .

Four :filter Use

The reason is that the browser inputs directly http://localhost:8080/xianfengYan/main.jsp I haven't logged in yet , No verification . We don't want visitors to visit this interface , So you need to add a filter to filter , Jump directly to index.jsp.

New package 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 { @Override
public void destroy() {
// TODO Auto-generated method stub } @Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
// TODO Auto-generated method stub
// Filtering user requests , Infer 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);
} @Override
public void init(FilterConfig arg0) throws ServletException {
// TODO Auto-generated method stub } }

And then again web.xml Configuration in :

 <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 It's a filtered page , We specify filtering /main.jsp This interface .

Code download link :http://download.csdn.net/detail/yanzi1225627/7448175

Copyright notice : This article is an original blog article . Blog , Without consent , Shall not be reproduced .

be based on Servlet、JSP、JDBC、MySQL Login module ( Including the filters and configurations used ) More articles about

  1. be based on Servlet+jsp Of web Calculator

    be based on Servlet+jsp Of web Calculator In order to let us review by ourselves web In the page Jump to the assigned task A big copy of the world code , The key is how you copy First of all, the algorithm I came up with was not a stack , It's simple. ( It's complicated , But I just need to ...

  2. establish jsp+Servlet+JavaBean+JDBC+MySQL The process of the project

    1 Build on demand Mysql data , Establish the fields of the table in the database . attribute . Primary key , Foreign keys, etc . The database name I use below dev , Table name user, Field   name, Set the primary key . The username cannot be empty , Field password, password 2 stay E ...

  3. javaweb Learning summary ( Twenty-two )—— be based on Servlet+JSP+JavaBean Development mode user login registration

    One .Servlet+JSP+JavaBean Development mode (MVC) Introduce Servlet+JSP+JavaBean Pattern (MVC) Suitable for developing complex web application , In this mode ,servlet Responsible for processing user requests ,jsp ...

  4. JavaWeb Study ( The 21st )———— be based on Servlet+JSP+JavaBean Development mode user login registration

    One .Servlet+JSP+JavaBean Development mode (MVC) Introduce Servlet+JSP+JavaBean Pattern (MVC) Suitable for developing complex web application , In this mode ,servlet Responsible for processing user requests ,jsp ...

  5. be based on Servlet+JSP+JavaBean Development mode user login registration

    http://www.cnblogs.com/xdp-gacl/p/3902537.html One .Servlet+JSP+JavaBean Development mode (MVC) Introduce Servlet+JSP+JavaBea ...

  6. javaweb( Twenty-two )—— be based on Servlet+JSP+JavaBean Development mode user login registration

    One .Servlet+JSP+JavaBean Development mode (MVC) Introduce Servlet+JSP+JavaBean Pattern (MVC) Suitable for developing complex web application , In this mode ,servlet Responsible for processing user requests ,jsp ...

  7. JavaWeb Implementation of user login registration function instance code ( be based on Servlet+JSP+JavaBean Pattern )

    One .Servlet+JSP+JavaBean Development mode (MVC) Introduce Servlet+JSP+JavaBean Pattern (MVC) Suitable for developing complex web application , In this mode ,servlet Responsible for processing user requests ,jsp ...

  8. servlet+jsp+jdbc Realize the query of user information from database to page

    Project creation is no longer mentioned here , Directly from the display User Information list starts . remarks : I use it servlet3 The annotation function of , So there's no need to configure web.xml This is my project catalog : First, we create the entity class : public cla ...

  9. Servlet+JSP+JDBC Comprehensive case

    Hierarchy : One .Util package There's one in the bag JDBCTools.java file function : Realize the database connection and return a Connection object , And it can close the corresponding resources of the database ! matters needing attention : 1. Define member variables 1 p ...

Random recommendation

  1. Mysql Simple use of triggers

    trigger :trigger The syntax for creating triggers mysql> delimiter $mysql> create trigger Trigger Name after/before( Trigger time ) insert/upd ...

  2. No.007 Reverse Integer

    7. Reverse Integer Total Accepted: 153147 Total Submissions: 644103 Difficulty: Easy Reverse digits ...

  3. QWidget You can set QStyle, It can draw a lot of things ( The specific content has not been studied , To be continued )

    QStyle * QWidget::style() const See also QWidget::setStyle(), QApplication::setStyle(), and QApplica ...

  4. Kali Linux After installing the system, install the frequently used software

    1. Configure software source   leafpad /etc/apt/source.list or(recommand): # Official source deb http://http.kali.org/kali kali main no ...

  5. JDBC Second articles --【PreparedStatment、 The batch 、 Processing binary 、 Automatic primary key 、 Calling stored procedure 、 function 】

    This is me JDBC The first chapter of http://blog.csdn.net/hon_3y/article/details/53535798 1.PreparedStatement object PreparedState ...

  6. MySql Transaction control for (TCL Language )

    ⒈ Business One or a group of sql Statements form an execution unit , This execution unit is either all executed , Or none at all . ⒉ The nature of transactions (ACID) 1. Atomicity (Atomicity): A transaction is indivisible , Either all or none . 2. ...

  7. c Language Pinball games

    #include <stdio.h>#include <stdlib.h>#include <windows.h>#include <time.h>#i ...

  8. html Translate characters Character entities

    http://www.w3school.com.cn/html/html_entities.asp http://www.w3school.com.cn/tags/html_ref_entities. ...

  9. University of China MOOC- Chen Yue 、 He Qinming - data structure - note

    University of China MOOC- Chen Yue . He Qinming - data structure -2017 In the spring follow < University of China MOOC- Chen Yue . He Qinming - data structure -2017 In the spring > Study , Usually practice pat Out of the homework on : Record it here : The harvest of learning video at ordinary times . ...

  10. CentOS7 System installation Maria Db(MYSQL) course

    One . background Maria Db It's a popular cross platform MySQL The branch of database management system , Is considered to be MySQL Complete substitution .Maria Db By Sun stay Sun Micro systems During the merger period, it was Oracle After the acquisition , On 2 ...