Spring MVC demo small example to achieve simple login and registration

Posted by LuiePL on Tue, 04 Jun 2019 03:27:14 +0200

1. Create a dynamic web project

2. Importing the jar packages needed by Spring Mvc (you can find them online, there are many resources)

The first two parts are not described in detail, but the second part is the formal code.~

First of all, there is a web.xml file, which belongs to the large configuration file. As long as you write login, you can simply configure the basic environment inside.

 

<servlet>
    <servlet-name>springmvc</servlet-name>
    <servlet-class>
        org.springframework.web.servlet.DispatcherServlet
    </servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
     <servlet-name>springmvc</servlet-name>
     <url-pattern>/</url-pattern>
  </servlet-mapping>

This is called Dispatcher Servlet. You can find the corresponding small configuration file according to the servlet-name, which is the file that configures spring MVC.

Create a new spring mvc-servlet.xml file in the same directory of the web.xml file. The following is the content of the spring mvc-servlet.xml file

 

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="
    http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.0.xsd
    http://www.springframework.org/schema/mvc 
    http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
    <!--Default annotation mapping support -->
    <mvc:annotation-driven/>
    <!--Enable automatic scanning -->
    <context:component-scan base-package="controller"/>
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
</beans>

Note that by starting automatic scanning, spring will automatically scan the classes labeled @Controller under the specified package (for example, I'm the controller package here).

prefix means that the returned value is prefixed automatically. Similarly, suffix means suffix.

 

 

It's hard enough to see here. Here's the complete catalog. Here's how to write the logic code. Start with loginController.

@Controller
public class LoginController {
    @RequestMapping(value="/",method=RequestMethod.GET)
    public String sayHello(){
        //model.addAttribute("msg", "Hello,World!");
        return "login";
    }

Explain the above code, @Controller, annotate this class is Controller class, spring will automatically scan, @Request Mapping in the value refers to the address suffix in the url, set to/for convenience of course,

For example, when starting a project, the url just needs to enter what localhost: 8080 / project name, it will automatically jump to the login page; method refers to whether the url is a post request or a get request

The return is a login string, you remember the prefix above, it will automatically splice your url, the complete path is the following one

/WEB-INF/jsp/login.jsp

Next, look at login.jsp

<%@ 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 http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>login</title>
</head>
<body>
    <form action="login" method="post">
        User name:<input type="text" name="username"/><br/>
        dense&nbsp;&nbsp;Code:<input type="password" name="password"/>
        <input type="submit" value="Land"/>
        <a href="regist">register</a>
    </form>
</body>
</html>

Here action returns login, and Controller automatically captures the request, so there's a way to capture the request in login Controller

@RequestMapping(value="login",method=RequestMethod.POST)
    public String login(Model model, // Put the value passed to the front page model in
            HttpServletRequest request){ // The value obtained from the front page
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String user_name = LoginCheck.check(username, password);
        if(user_name != null && user_name != ""){
            model.addAttribute("msg", user_name);
            return "success";
        }else{
            return "login2";
        }
    }

Login, of course, has to be validated, so there is LoginCheck, not to mention the code.

package logic;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import dao.Dao;

public class LoginCheck {
    
    public static String check(String username,String password){
        try {
            Connection conn = Dao.getConnection();
            PreparedStatement p = conn.prepareStatement("select * from user_t where user_name=? and password=?");
            p.setString(1, username);
            p.setString(2, password);
            ResultSet rs = p.executeQuery();
            if(rs.next()){
                String user_name = rs.getString("user_name");
                Dao.close(rs, p, conn);
                return user_name;
            }
            Dao.close(rs, p, conn);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }
}

To query the database, there will be DAO. Dao has it on the internet. My idea is to find a change on the Internet and use it.~

package dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class Dao {
    // Get the database connection
    public static Connection getConnection(){
        
        Connection conn = null;
        String url = "jdbc:mysql://127.0.0.1:3306/test?characterEncoding=utf8&useSSL=false&serverTimezone=Hongkong";
        try
        {
            Class.forName("com.mysql.cj.jdbc.Driver");
            conn = DriverManager.getConnection(url,"root","Database password");//Don't expose your database password when you share your code. It's very insecure.
        }
        catch(ClassNotFoundException e)
        {
            e.printStackTrace();
            System.out.println("Database Driver Loading Error");
        }
        catch(SQLException e)
        {
            e.printStackTrace();
            System.out.println("Database error");
        }
        return conn;
    }
     //Close related channels
    public static void close(ResultSet rs,PreparedStatement p,Connection conn)
    {
        try
        {
            if(!rs.isClosed()){
                rs.close();
            }
            if(!p.isClosed()){
                p.close();
            }
            if(!conn.isClosed()){
                conn.close();
            }
        }
        catch(SQLException e)
        {
            e.printStackTrace();
            System.out.println("Data Closing Error");
        }
    }
    //Close related channels
    public static void close(PreparedStatement p,Connection conn)
    {
        try
        {
            if(!p.isClosed()){
                p.close();
            }
            if(!conn.isClosed()){
                conn.close();
            }
        }
        catch(SQLException e)
        {
            e.printStackTrace();
            System.out.println("Data Closing Error");
        }
    }
}

Well, if the query results match the values queried in the database, then you can jump to the success page, success.jsp

<%@ 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 http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Landing successfully</title>
</head>
<body>
    //Landing success!
    //Welcome~${msg};
</body>
</html>

login is successful, the next registration page is similar to this principle, I don't talk much nonsense, attach the code for your reference.

First, register. JSP

<%@ 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 http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Registration page</title>
</head>
<body>
    <form action="registSuccess" method="Post">
        //User name:<input type="text" name="username"/>
        //dense&nbsp;&nbsp;code<input type="text" name="password"/>
        //year&nbsp;&nbsp;age<input type="number" name="age"/>
        <input type="submit" value="Submission"/>
    </form>
</body>
</html>

Next comes RegistController

package controller;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import logic.RegistCheck;

@Controller
public class RegistController {
    @RequestMapping(value="regist",method=RequestMethod.GET)
    public String regist(){
        return "regist";
    }
    
    @RequestMapping(value="registSuccess",method=RequestMethod.POST)
    public String registSuccess(HttpServletRequest request,Model model){
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String age = request.getParameter("age");
        
        if(RegistCheck.registCheck(username, password,age)){
            model.addAttribute("username", username);
            return "login";
        }else{
            return "regist2";
        }
    }
}

Next comes RegistCheck

 

package logic;

import java.sql.Connection;
import java.sql.PreparedStatement;

import dao.Dao;

public class RegistCheck {
    
    public static boolean registCheck(String username,String password,String age){
        String user_name = LoginCheck.check(username, password);
        if(user_name == null || user_name == ""){
            try {
                Connection conn = Dao.getConnection();
                PreparedStatement p = conn.prepareStatement("insert user_t(user_name,password,age) VALUES (?,?,?);");
                p.setString(1, username);
                p.setString(2, password);
                p.setString(3, age);
                p.executeUpdate();
                System.out.println("login was successful");
                Dao.close(p, conn);
                return true;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return false;
    }
}

There's also registSuccess.jsp, which returns successfully. I just put an empty page with no content.

<%@ 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 http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>login was successful</title>
</head>
<body>
    //Successful registration!
</body>
</html>

Okay, so far login and registration pages have been written. It's very easy for new people to encounter such small exercises when they first arrive at the company. Haha said a lot, just like it.

Welcome to reprint, reprint please indicate the source~

Java from learning to giving up, MySQL from deleting libraries to running, haha ha

Topics: Java SQL Spring JSP