JavaWeb_(Spring框架)用户登陆Spring整合到Servlet中

 

 

一、使用servlet技术开发用户登陆功能

  在MySQL中准备一个user表,表中增加一条假数据

  

   

  使用Servlet实现用户登陆的功能

  

 

  用户登陆的<from>表单

  <form id="loginFrom" action="${pageContext.request.contextPath }/userLogin" method="post">
                    <div class="input-group input-group-lg sepH_a">
                        <span class="input-group-addon"><span class="icon_profile"></span></span>
                        <input type="text" class="form-control" placeholder="Username" name="username">
                    </div>
                    <div class="input-group input-group-lg">
                        <span class="input-group-addon"><span class="icon_key_alt"></span></span>
                        <input type="password" class="form-control" placeholder="Password" name="password">
                    </div>
                    
                    <div>
                        <a id="errorMsg" href="javascript:void(0)" style="color: red">${errorMsg}</a>
                    </div>
                    
                    <div class="sepH_c text-right">
                        <a href="javascript:void(0)" class="small">Forgot password?</a>
                    </div>
                    <div class="form-group sepH_c">
                        <a href="javascript:doucment:loginFrom.submit()" class="btn btn-lg btn-primary btn-block">Log in</a>
                    </div>
  </form>

 

 

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <head>
        <meta charset="UTF-8">
        <title>登录/注册</title>
        <meta name="viewport" content="initial-scale=1.0,maximum-scale=1.0,user-scalable=no">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">

        <!-- bootstrap framework -->
        <link href="${pageContext.request.contextPath }/css/bootstrap.min.css" rel="stylesheet" media="screen">
        <!-- elegant icons -->
        <link href="${pageContext.request.contextPath }/css/style.css" rel="stylesheet" media="screen">
        <!-- main stylesheet -->
        <link href="${pageContext.request.contextPath }/css/main.min.css" rel="stylesheet" media="screen">

        <!-- jQuery -->
        <script src="${pageContext.request.contextPath }/js/jquery.min.js"></script>

    </head>
    <body class="login_page">
        <div class="login_header">
        </div>
        <div class="login_register_form">
            <div class="form_wrapper animated-short" id="login_form">
                <h3 class="sepH_c"><span>Login</span> \ <a href="javascript:void(0)" class="form-switch" data-switch-form="register_form">Register</a></h3>
                <form id="loginFrom" action="${pageContext.request.contextPath }/userLogin" method="post">
                    <div class="input-group input-group-lg sepH_a">
                        <span class="input-group-addon"><span class="icon_profile"></span></span>
                        <input type="text" class="form-control" placeholder="Username" name="username">
                    </div>
                    <div class="input-group input-group-lg">
                        <span class="input-group-addon"><span class="icon_key_alt"></span></span>
                        <input type="password" class="form-control" placeholder="Password" name="password">
                    </div>
                    
                    <div>
                        <a id="errorMsg" href="javascript:void(0)" style="color: red">${errorMsg}</a>
                    </div>
                    
                    <div class="sepH_c text-right">
                        <a href="javascript:void(0)" class="small">Forgot password?</a>
                    </div>
                    <div class="form-group sepH_c">
                        <a href="javascript:doucment:loginFrom.submit()" class="btn btn-lg btn-primary btn-block">Log in</a>
                    </div>
                </form>
            </div>
            <div class="form_wrapper animated-short" id="register_form" style="display:none">
                <h3 class="sepH_c"><span>Register</span> \ <a href="javascript:void(0)" class="form-switch" data-switch-form="login_form">Login</a></h3>
                <form name = "registerForm" action="${pageContext.request.contextPath}/userRegister" method="post">
                    <div class="input-group input-group-lg sepH_a">
                        <span class="input-group-addon"><span class="icon_profile"></span></span>
                        <input type="text" class="form-control" placeholder="Username" name="username">
                    </div>
                    <div class="input-group input-group-lg sepH_a">
                        <span class="input-group-addon"><span class="icon_key_alt"></span></span>
                        <input type="password" class="form-control" placeholder="Password" name="password">
                    </div>
                    <div class="input-group input-group-lg sepH_c">
                        <span class="input-group-addon"><span class="icon_mail_alt"></span></span>
                        <input type="email" class="form-control" placeholder="Email" name="email">
                    </div>
                    <div class="form-group sepH_c">
                        <a href="javascript:doucment:registerForm.submit()" class="btn btn-lg btn-success btn-block">Register</a>
                    </div>
                </form>
            </div>
        </div>

        <script>
            $(function () {
                $('.form-switch').on('click', function (e) {
                    e.preventDefault();

                    var $switchTo = $(this).data('switchForm'),
                        $thisForm = $(this).closest('.form_wrapper');

                    $('.form_wrapper').removeClass('fadeInUpBig');
                    $thisForm.addClass('fadeOutDownBig');

                    setTimeout(function () {
                        $thisForm.removeClass('fadeOutDownBig').hide();
                        $('#' + $switchTo).show().addClass('fadeInUpBig');
                    }, 300);

                });
            });
        </script>
    </body>
</html>
login_page.jsp

 

package com.Gary.bean;

public class User {

    private Integer u_id;
    private String u_username;
    private String u_password;
    
    
    public Integer getU_id() {
        return u_id;
    }
    public void setU_id(Integer u_id) {
        this.u_id = u_id;
    }
    public String getU_username() {
        return u_username;
    }
    public void setU_username(String u_username) {
        this.u_username = u_username;
    }
    public String getU_password() {
        return u_password;
    }
    public void setU_password(String u_password) {
        this.u_password = u_password;
    }
    
    
    
}
User.java

 

package com.Gary.dao;

import java.beans.PropertyVetoException;
import java.sql.SQLException;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;

import com.Gary.bean.User;
import com.mchange.v2.c3p0.ComboPooledDataSource;

public class UserDao {

    private static ComboPooledDataSource dataSource;
    
    static {
        //配置c3p0
        try {
            //使用c3p0链接数据库
            dataSource = new ComboPooledDataSource();
            dataSource.setDriverClass("com.mysql.jdbc.Driver");
            dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/ssm_spring");
            dataSource.setUser("root");
            dataSource.setPassword("123456");
        } catch (PropertyVetoException e) {
        
            e.printStackTrace();
        }
    }
    
    //通过数据库获取用户
    public User getUserByInfo(User u) throws SQLException {
        
        //使用dbutils操作数据库 查询并返回用户对象
        QueryRunner qr = new QueryRunner(dataSource);
        
        String sql ="select * from user where u_username = ? and u_password = ?";
        
        return    qr.query(sql, new BeanHandler<User>(User.class),u.getU_username(),u.getU_password());

    }

}
UserDao.java

 

package com.Gary.service;

import java.sql.SQLException;

import com.Gary.bean.User;
import com.Gary.dao.UserDao;

public class UserService{

    private UserDao ud= new UserDao();
    
    public User getUserByInfo(User u) throws SQLException {
        
        return ud.getUserByInfo(u);
    }

}
UserService.java

 

package com.Gary.web;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.Gary.bean.User;
import com.Gary.service.UserService;


@WebServlet("/userLogin")
public class UserLoginServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        
        //接收表单数据
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        
        //封装成User对象
        User u = new User();
        u.setU_username(username);
        u.setU_password(password);
        
        //调用service方法验证
        UserService us = new UserService();
        User loginUser = null;
        try {
            loginUser = us.getUserByInfo(u);
        } catch (SQLException e) {

            e.printStackTrace();
        }
        
        //根据用户验证结果进行操作
        if(loginUser == null)
        {
            //验证成功登陆,并重定向到index.jsp
            request.setAttribute("errorMsg", "用户名或密码错误");
            request.getRequestDispatcher("/login_page.jsp").forward(request, response);
        }else {
            //验证失败,重定向到login_page.jsp
            HttpSession session = request.getSession();
            session.setAttribute("user", loginUser);
            response.sendRedirect(request.getContextPath()+"/index.jsp");
        }
        
        
    }

    public UserLoginServlet() {
        super();
      
    }


    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
        
    }

}
UserLoginServlet.java

 

  修改项目

  利用Spring改造项目

  导入Spring的核心包,并配置Spring随项目启动

  

 

package com.Gary.bean;

public class User {

    private Integer u_id;
    private String u_username;
    private String u_password;
    
    
    public Integer getU_id() {
        return u_id;
    }
    public void setU_id(Integer u_id) {
        this.u_id = u_id;
    }
    public String getU_username() {
        return u_username;
    }
    public void setU_username(String u_username) {
        this.u_username = u_username;
    }
    public String getU_password() {
        return u_password;
    }
    public void setU_password(String u_password) {
        this.u_password = u_password;
    }
    
    
    
}
User.java

 

package com.Gary.dao;

import java.beans.PropertyVetoException;
import java.sql.SQLException;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;

import com.Gary.bean.User;
import com.mchange.v2.c3p0.ComboPooledDataSource;

public class UserDao {

    /*
    private static ComboPooledDataSource dataSource;
    
    static {
        //配置c3p0
        try {
            //使用c3p0链接数据库
            dataSource = new ComboPooledDataSource();
            dataSource.setDriverClass("com.mysql.jdbc.Driver");
            dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/ssm_spring");
            dataSource.setUser("root");
            dataSource.setPassword("123456");
        } catch (PropertyVetoException e) {
        
            e.printStackTrace();
        }
    }
    */
    
    private ComboPooledDataSource dataSource;
    

    public void setDataSource(ComboPooledDataSource dataSource) {
        this.dataSource = dataSource;
    }
    
    //通过数据库获取用户
    public User getUserByInfo(User u) throws SQLException {
        
        //使用dbutils操作数据库 查询并返回用户对象
        QueryRunner qr = new QueryRunner(dataSource);
        
        String sql ="select * from user where u_username = ? and u_password = ?";
        
        return    qr.query(sql, new BeanHandler<User>(User.class),u.getU_username(),u.getU_password());

    }


    
    

}
UserDao.java

 

package com.Gary.service;

import java.sql.SQLException;

import com.Gary.bean.User;
import com.Gary.dao.UserDao;

public class UserService{

    private UserDao ud= new UserDao();
    
    public User getUserByInfo(User u) throws SQLException {
        
        return ud.getUserByInfo(u);
    }

    public void setUd(UserDao ud) {
        this.ud = ud;
    }

}
UserService.java

 

package com.Gary.web;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.Gary.bean.User;
import com.Gary.service.UserService;


@WebServlet("/userLogin")
public class UserLoginServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    
    private UserService us;
    
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        
        //接收表单数据
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        
        //封装成User对象
        User u = new User();
        u.setU_username(username);
        u.setU_password(password);
        
        //通过容器获取userService
        /*ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
        us = (UserService) ac.getBean("userService");*/
        
        //在web项目中我们只需要一个spring容器
        
        //application域
        
        //ServletContext() 生命周期 随着web项目启动而创建  随着web项目关闭而销毁
        
        //ServletContextListener 可以通过配置监听器来达到我们的需求,在web项目创建时候创建容器,销毁时候关闭spring容器
        WebApplicationContext wac = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
        us = (UserService)wac.getBean("userService");
        
        //调用service方法验证
        User loginUser = null;
        try {
            loginUser = us.getUserByInfo(u);
        } catch (SQLException e) {

            e.printStackTrace();
        }
        
        //根据用户验证结果进行操作
        if(loginUser == null)
        {
            //验证成功登陆,并重定向到index.jsp
            request.setAttribute("errorMsg", "用户名或密码错误");
            request.getRequestDispatcher("/login_page.jsp").forward(request, response);
        }else {
            //验证失败,重定向到login_page.jsp
            HttpSession session = request.getSession();
            session.setAttribute("user", loginUser);
            response.sendRedirect(request.getContextPath()+"/index.jsp");
        }
        
        
    }

    public UserLoginServlet() {
        super();
      
    }


    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
        
    }

}
UserLoginServlet.java

 

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
            xmlns="http://www.springframework.org/schema/beans" 
            xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd ">

    <!-- 配置 dataSource -->
    <bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="com.mysql.jdbc.Driver"/>
        <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/ssm_spring"/>
        <property name="user" value="root"/>
        <property name="password" value="123456"/>
    </bean>
    

    <!-- 配置 dao -->
    <bean name="userDao" class="com.Gary.dao.UserDao">
        <property name="dataSource" ref="dataSource"/>
    </bean>
    
    <!-- 配置 service -->
    <bean name="userService" class="com.Gary.service.UserService">
        <property name="ud" ref="userDao"/>
    </bean>


</beans>        
applicationContext.xml

 

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
  <display-name>ssm_spring_servlet</display-name>
  
  <!-- 配置监听器,在web项目启动后让spring启动 -->
  <listener>
      <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <!-- 读取spring的配置文件 -->
  <context-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:applicationContext.xml</param-value>
  </context-param>
  
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
</web-app>
web.xml

 

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <head>
        <meta charset="UTF-8">
        <title>登录/注册</title>
        <meta name="viewport" content="initial-scale=1.0,maximum-scale=1.0,user-scalable=no">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">

        <!-- bootstrap framework -->
        <link href="${pageContext.request.contextPath }/css/bootstrap.min.css" rel="stylesheet" media="screen">
        <!-- elegant icons -->
        <link href="${pageContext.request.contextPath }/css/style.css" rel="stylesheet" media="screen">
        <!-- main stylesheet -->
        <link href="${pageContext.request.contextPath }/css/main.min.css" rel="stylesheet" media="screen">

        <!-- jQuery -->
        <script src="${pageContext.request.contextPath }/js/jquery.min.js"></script>

    </head>
    <body class="login_page">
        <div class="login_header">
        </div>
        <div class="login_register_form">
            <div class="form_wrapper animated-short" id="login_form">
                <h3 class="sepH_c"><span>Login</span> \ <a href="javascript:void(0)" class="form-switch" data-switch-form="register_form">Register</a></h3>
                <form id="loginFrom" action="${pageContext.request.contextPath }/userLogin" method="post">
                    <div class="input-group input-group-lg sepH_a">
                        <span class="input-group-addon"><span class="icon_profile"></span></span>
                        <input type="text" class="form-control" placeholder="Username" name="username">
                    </div>
                    <div class="input-group input-group-lg">
                        <span class="input-group-addon"><span class="icon_key_alt"></span></span>
                        <input type="password" class="form-control" placeholder="Password" name="password">
                    </div>
                    
                    <div>
                        <a id="errorMsg" href="javascript:void(0)" style="color: red">${errorMsg}</a>
                    </div>
                    
                    <div class="sepH_c text-right">
                        <a href="javascript:void(0)" class="small">Forgot password?</a>
                    </div>
                    <div class="form-group sepH_c">
                        <a href="javascript:doucment:loginFrom.submit()" class="btn btn-lg btn-primary btn-block">Log in</a>
                    </div>
                </form>
            </div>
            <div class="form_wrapper animated-short" id="register_form" style="display:none">
                <h3 class="sepH_c"><span>Register</span> \ <a href="javascript:void(0)" class="form-switch" data-switch-form="login_form">Login</a></h3>
                <form name = "registerForm" action="${pageContext.request.contextPath}/userRegister" method="post">
                    <div class="input-group input-group-lg sepH_a">
                        <span class="input-group-addon"><span class="icon_profile"></span></span>
                        <input type="text" class="form-control" placeholder="Username" name="username">
                    </div>
                    <div class="input-group input-group-lg sepH_a">
                        <span class="input-group-addon"><span class="icon_key_alt"></span></span>
                        <input type="password" class="form-control" placeholder="Password" name="password">
                    </div>
                    <div class="input-group input-group-lg sepH_c">
                        <span class="input-group-addon"><span class="icon_mail_alt"></span></span>
                        <input type="email" class="form-control" placeholder="Email" name="email">
                    </div>
                    <div class="form-group sepH_c">
                        <a href="javascript:doucment:registerForm.submit()" class="btn btn-lg btn-success btn-block">Register</a>
                    </div>
                </form>
            </div>
        </div>

        <script>
            $(function () {
                $('.form-switch').on('click', function (e) {
                    e.preventDefault();

                    var $switchTo = $(this).data('switchForm'),
                        $thisForm = $(this).closest('.form_wrapper');

                    $('.form_wrapper').removeClass('fadeInUpBig');
                    $thisForm.addClass('fadeOutDownBig');

                    setTimeout(function () {
                        $thisForm.removeClass('fadeOutDownBig').hide();
                        $('#' + $switchTo).show().addClass('fadeInUpBig');
                    }, 300);

                });
            });
        </script>
    </body>
</html>
login_page.jsp

 

 

 

 

 

 

 

posted @ 2019-12-08 14:03  Cynical丶Gary  阅读(224)  评论(0编辑  收藏  举报