Spring MVC用户注册和登录示例

原文地址: https://dzone.com/articles/spring-mvc-example-for-user-registration-and-login-1?edition=274902&utm_source=Daily%20Digest&utm_medium=email&utm_campaign=dd%202017-03-04

本文是使用几种Web开发语言和数据库设置用户注册和登录的分步指南。

   · Web Dev Zone

本文是使用以下工具和技术的用户注册和登录的分步指南。

Spring框架(Core,MVC和JBDC)

2. Java 1.8

3.Maven 3.3.9

4. Eclipse IDE(Mars2)

5. MySQL 5.1

步骤1:创建Maven项目

使用Eclipse IDE,通过选择Web Archetype创建Maven项目。

步骤2:更新Pom.xml

更新你的maven依赖。



    4.0.0

    jbr

    SpringMvcUser

    war

    0.1

    SpringMvcUser Maven Webapp

    http://maven.apache.org

    

        UTF-8

        4.3.2.RELEASE

        4.12

        3.1.0

        3.0.1

        5.1.9

    

    

        

        

            junit

            junit

            ${junit.version}

            test

        

        

        

            javax.servlet

            javax.servlet-api

            ${servlet.version}

        

        

        

            org.springframework

            spring-core

            ${spring.version}

        

        

            org.springframework

            spring-beans

            ${spring.version}

        

        

            org.springframework

            spring-context

            ${spring.version}

        

        

            org.springframework

            spring-jdbc

            ${spring.version}

        

        

            org.springframework

            spring-test

            ${spring.version}

            test

        

        

            org.springframework

            spring-webmvc

            ${spring.version}

        

        

        

            javax.servlet

            javax.servlet-api

            ${servlet.version}

        

        

        

            mysql

            mysql-connector-java

            ${mysql.connector.version}

        

    

    

        SpringMvcUser

    


步骤3:更新web.xml

更新src / main / webapp / WEB-INF下的web.xml,如下所示:





    Archetype Created Web Application

    

        home.jsp

    

    

        spring-mvc

        org.springframework.web.servlet.DispatcherServlet

        1

    

    

        spring-mvc

        /

    


  1. DispatcherServlet   是您的应用程序中定义的任何Servlet的根Servlet。 它将根据URL将对应用程序发出的请求重定向到相应的控制器。

  2. spring-mvc   是根servlet的名称,Spring容器将查找具有此名称的配置。 所以下一步是使用spring-mvc-servlet.xml创建一个spring配置。

步骤4:创建spring-mvc-servlet.xml

创建spring-mvc-servlet.xml   在src / main / webapp / WEB-INF文件夹下,并定义bean。





    

    

    

    

        

        

    


步骤5:创建控制器

为用户注册和登录创建单独的控制器,如下所示。

创建一个包jbr.springmvc.controller  

RegistrationController.java

package jbr.springmvc.controller;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.ModelAttribute;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestMethod;

import org.springframework.web.servlet.ModelAndView;

import jbr.springmvc.model.User;

import jbr.springmvc.service.UserService;

@Controller

public class RegistrationController {

  @Autowired

  public UserService userService;

  @RequestMapping(value = "/register", method = RequestMethod.GET)

  public ModelAndView showRegister(HttpServletRequest request, HttpServletResponse response) {

    ModelAndView mav = new ModelAndView("register");

    mav.addObject("user", new User());

    return mav;

  }

  @RequestMapping(value = "/registerProcess", method = RequestMethod.POST)

  public ModelAndView addUser(HttpServletRequest request, HttpServletResponse response,

  @ModelAttribute("user") User user) {

  userService.register(user);

  return new ModelAndView("welcome", "firstname", user.getFirstname());

  }

}

LoginController.java

package jbr.springmvc.controller;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.ModelAttribute;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestMethod;

import org.springframework.web.servlet.ModelAndView;

import jbr.springmvc.model.Login;

import jbr.springmvc.model.User;

import jbr.springmvc.service.UserService;

@Controller

public class LoginController {

  @Autowired

  UserService userService;

  @RequestMapping(value = "/login", method = RequestMethod.GET)

  public ModelAndView showLogin(HttpServletRequest request, HttpServletResponse response) {

    ModelAndView mav = new ModelAndView("login");

    mav.addObject("login", new Login());

    return mav;

  }

  @RequestMapping(value = "/loginProcess", method = RequestMethod.POST)

  public ModelAndView loginProcess(HttpServletRequest request, HttpServletResponse response,

  @ModelAttribute("login") Login login) {

    ModelAndView mav = null;

    User user = userService.validateUser(login);

    if (null != user) {

    mav = new ModelAndView("welcome");

    mav.addObject("firstname", user.getFirstname());

    } else {

    mav = new ModelAndView("login");

    mav.addObject("message", "Username or Password is wrong!!");

    }

    return mav;

  }

}

步骤5:创建POJO类

创建一个包: jbr.springmvc.model  

Login.java

package jbr.springmvc.model;

public class Login {

  private String username;

  private String password;

  public String getUsername() {

  return username;

  }

  public void setUsername(String username) {

  this.username = username;

  }

  public String getPassword() {

  return password;

  }

  public void setPassword(String password) {

  this.password = password;

  }

}

User.java

package jbr.springmvc.model;

public class User {

  private String username;

  private String password;

  private String firstname;

  private String lastname;

  private String email;

  private String address;

  private int phone;

  public String getUsername() {

  return username;

  }

  public void setUsername(String username) {

  this.username = username;

  }

  public String getPassword() {

  return password;

  }

  public void setPassword(String password) {

  this.password = password;

  }

  public String getFirstname() {

  return firstname;

  }

  public void setFirstname(String firstname) {

  this.firstname = firstname;

  }

  public String getLastname() {

  return lastname;

  }

  public void setLastname(String lastname) {

  this.lastname = lastname;

  }

  public String getEmail() {

  return email;

  }

  public void setEmail(String email) {

  this.email = email;

  }

  public String getAddress() {

  return address;

  }

  public void setAddress(String address) {

  this.address = address;

  }

  public int getPhone() {

  return phone;

  }

  public void setPhone(int phone) {

  this.phone = phone;

  }

}

注意:如果您想添加任何新的逻辑,您可以添加另一个称为服务的层并访问DAO层。

步骤6:创建DAO类

创建用于访问MySQL数据库的接口/类。

创建一个包: jbr.springmvc.dao  

UserDao.java

package jbr.springmvc.dao;

import jbr.springmvc.model.Login;

import jbr.springmvc.model.User;

public interface UserDao {

  void register(User user);

  User validateUser(Login login);

}

UserDaoImpl.java

package jbr.springmvc.dao;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.util.List;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.jdbc.core.JdbcTemplate;

import org.springframework.jdbc.core.RowMapper;

import jbr.springmvc.model.Login;

import jbr.springmvc.model.User;

public class UserDaoImpl implements UserDao {

  @Autowired

  DataSource datasource;

  @Autowired

  JdbcTemplate jdbcTemplate;

  public void register(User user) {

    String sql = "insert into users values(?,?,?,?,?,?,?)";

    jdbcTemplate.update(sql, new Object[] { user.getUsername(), user.getPassword(), user.getFirstname(),

    user.getLastname(), user.getEmail(), user.getAddress(), user.getPhone() });

    }

    public User validateUser(Login login) {

    String sql = "select * from users where username='" + login.getUsername() + "' and password='" + login.getPassword()

    + "'";

    List users = jdbcTemplate.query(sql, new UserMapper());

    return users.size() > 0 ? users.get(0) : null;

    }

  }

  class UserMapper implements RowMapper {

  public User mapRow(ResultSet rs, int arg1) throws SQLException {

    User user = new User();

    user.setUsername(rs.getString("username"));

    user.setPassword(rs.getString("password"));

    user.setFirstname(rs.getString("firstname"));

    user.setLastname(rs.getString("lastname"));

    user.setEmail(rs.getString("email"));

    user.setAddress(rs.getString("address"));

    user.setPhone(rs.getInt("phone"));

    return user;

  }

}

步骤7:创建Spring Bean配置

resources 创建一个新的xml bean配置user-beans.xml 来定义我们创建的bean。





    

    

    

    

    

        

    

    

        

        

        

        

    


步骤8:在MySQL中创建表

CREATE DATABASE 

  IF NOT EXISTS myusers;USE 

    DROP TABLE 

    DROP TABLE IF EXISTS `myusers`.`users`;CREATE TABLE `myusers`.`users` 

                 ( 

                              `username`  VARCHAR(45) NOT NULL, 

                              `password`  VARCHAR(45) NULL, 

                              `firstname` VARCHAR(45) NOT NULL, 

                              `lastname`  VARCHAR(45) NULL, 

                              `email`     VARCHAR(45) NULL, 

                              `address`   VARCHAR(45) NULL, 

                              `phone`     INT NULL, 

                              PRIMARY KEY (`username`) 

                 )

步骤9:创建视图

在/ src / main / webapp文件夹下,创建一个home.jsp,我们在web.xml中定义为“welcome-file”。

home.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1" %>

    

    

    

        

        Welcome

    

    

        
Login Register

在/ src / main / webapp / jsp下创建:

register.jsp

<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>

    <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1" %>

        

        

            

            Registration

        

        

            

                
Username
Password
FirstName
LastName
Email
Address
Phone
Register
Home

login.jsp

<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>

    <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1" %>

        

        

        

            

            Login

        

        

            

                
Username:
Password:
Login
Home
${message}

welcome.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1" %>

    

    

    

        

        Welcome

    

    

        
Welcome ${firstname}
Home

步骤10:运行应用程序

  1. 右键单击应用程序,然后Maven-> clean。

  2. 右键单击应用程序,然后单击Maven-> install。

  3. 右键单击应用程序并运行As->在服务器上运行 - >使用Tomcat运行。

您将看到以下输出。

主页:

图片标题


用户注册:

Spring MVC用户注册和登录示例_第1张图片

用户注册成功:

Spring MVC用户注册和登录示例_第2张图片

登录:

Spring MVC用户注册和登录示例_第3张图片

登录成功:

Spring MVC用户注册和登录示例_第4张图片

概要

本教程有助于为Spring MVC创建一个Maven项目,并为用户注册和登录开发一个小应用程序。







你可能感兴趣的:(Spring)