STS用Maven写一个登录页面 - 用MySQL验证登录用户

上一章我们已经将MySQL和STS的连接进行了测试,下面我们就用MySQL验证登录用户是否正确。

可参考:https://www.cnblogs.com/smart-zihan/p/15041013.html

第一步:建立数据库接口

1. 右键LoginPage项目,【New】-->【Package】,Name就填com.free.entity。在com.free.entity下新建一个User.java,右键com.free.entity,【New】--> 【Class】,Name就填User。当然java的名称自己可以取的。这个文件对应前面数据库中的数据(id, name, password)。

User.java

package com.free.entity;

public class User {
    private Integer id;
    private String name;
    private String password;
    
    public Integer getuser_id() {
        return id;
    }
    public void setuser_id(Integer User_id) {
        id = User_id;
    }
    public String getuser_name() {
        return name;
    }
    public void setuser_name(String User_name) {
        name = User_name;
    }

    public String getpassword() {
        return password;
    }
    public void setpassword(String Password) {
        password = Password;
    }

    
    public User(Integer User_id, String User_name,  String Password) {
        super();
        id = User_id;
        name = User_name;
        password = Password;
    }
    
}
View Code

 

2.  新建一个com.free.dao包,在其下新建一个UserDao.java,用来写操作数据库的方法接口。

UserDao.java

package com.free.dao;

import java.util.List;

import org.apache.ibatis.annotations.Param;

import com.free.entity.User;

public interface UserDao {

    User login(@Param("name") String name,@Param("password") String password); //这个地方的name和Usermapper里面login中select语句#{name}对应
}
View Code

 

3. 新建一个com.free.mapper,实现UserDao里面的方法,这里用到了mybatis。在com.free.mapper下新建一个Usermapper.xml文件,【New】--> 【Other】--> 【XML File】,取名为Usermapper。

Usermapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" 
"http://mybatis.org/dtd/mybatis-3-mapper.dtd" >

<mapper namespace="com.free.dao.UserDao">
    <resultMap id="user" type="com.free.entity.User">
        <id column="id" property="id" jdbcType="INTEGER" />
        <result column="name" property="name" jdbcType="VARCHAR" />
        <result column="password" property="password" jdbcType="VARCHAR" />
    </resultMap>

    <select id="login" resultMap="user">
        SELECT * FROM user 
        WHERE name=#{name} 
            AND password=#{password};
    </select>

</mapper>
View Code

 

4. 新建一个com.free.service包,在com.free.service包下建一个UserService.java,作为一个用户登陆接口。右键com.free.service,【New】--> 【Class】,Name就填UserService。当然java的名称自己可以取的。在com.free.service包下建一个UserServiceImpl.java,实现UserService的函数。

UserService.java

package com.free.service;

import java.util.List;

import org.apache.ibatis.annotations.Param;

import com.free.entity.User;

public interface UserService {

    User login(String name,String password);
}
View Code

 

UserServiceImpl.java

package com.free.service;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.free.dao.UserDao;
import com.free.entity.User;

@Service
public class UserServiceImpl implements UserService {
    
    @Resource
    public UserDao userDao;
    
    @Override
    public User login(String name,String password) {
        
        return userDao.login(name,password);
    }

}
View Code

 

 

第二步:配置mybatis和mysql

1. 在src/main/resources下建立一个mybatis的文件夹,右键src/main/resources,【New】--> 【Folder】,Name就填mybatis。在mybatis文件夹下新建mybatis的配置文件,右键mybatis,【New】-->【Other】--> 【XML File】,取名为mybatis-config。

mybatis-config.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"  
"http://mybatis.org/dtd/mybatis-3-config.dtd"> 
<configuration>    
</configuration>
View Code

 

2. 在src/main/resources下面新建一个properties文件夹,在此文件夹下建立一个jdbc.properties文件,【New】--> 【File】,取名为jdbc.properties。

jdbc_driverClassName=com.mysql.cj.jdbc.Driver
jdbc_url=jdbc:mysql://localhost:3306/LoginTestUser?useSSL=false&serverTimezone=GMT%2B8&allowPublicKeyRetrieval=true
jdbc_username=root
jdbc_password=123456
View Code

 

3. 修改以下配置文件

pom.xml

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.test.demo</groupId>
  <artifactId>Demo</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>

  <name>Demo Maven Webapp</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
    <org.springframework-version>4.3.8.RELEASE</org.springframework-version>
    <org.slf4j-version>1.7.5</org.slf4j-version>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
    
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>4.3.8.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-web</artifactId>
        <version>4.3.8.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>4.3.8.RELEASE</version>
    </dependency>
    
    <!-- Logging -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>${org.slf4j-version}</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>jcl-over-slf4j</artifactId>
            <version>${org.slf4j-version}</version>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>${org.slf4j-version}</version>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.15</version>
            <exclusions>
                <exclusion>
                    <groupId>javax.mail</groupId>
                    <artifactId>mail</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>javax.jms</groupId>
                    <artifactId>jms</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>com.sun.jdmk</groupId>
                    <artifactId>jmxtools</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>com.sun.jmx</groupId>
                    <artifactId>jmxri</artifactId>
                </exclusion>
            </exclusions>
            <scope>runtime</scope>
        </dependency>
        
        <!-- Servlet -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.1</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
        
        <!-- mysql连接 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.30</version>
        </dependency>
        
        <dependency>  
           <groupId>com.itextpdf</groupId>  
           <artifactId>itextpdf</artifactId>  
           <version>5.5.0</version>  
         </dependency>  
         <dependency>  
           <groupId>com.itextpdf</groupId>  
           <artifactId>itext-pdfa</artifactId>  
           <version>5.5.0</version>  
         </dependency>  
         <dependency>  
           <groupId>com.itextpdf</groupId>  
           <artifactId>itext-asian</artifactId>  
           <version>5.2.0</version>  
         </dependency>   
         <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.10-FINAL</version>
        </dependency>
        
        <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</artifactId>
        <version>4.2.6.RELEASE</version>
        </dependency>
        
        <!-- mybatis 包 -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.0</version>
        </dependency>

        <!--mybatis spring 插件 -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.3.0</version>
        </dependency>
  </dependencies>

  <build>
    <finalName>Demo</finalName>
    <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
      <plugins>
        <plugin>
          <artifactId>maven-clean-plugin</artifactId>
          <version>3.1.0</version>
        </plugin>
        <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
        <plugin>
          <artifactId>maven-resources-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>3.8.0</version>
        </plugin>
        <plugin>
          <artifactId>maven-surefire-plugin</artifactId>
          <version>2.22.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-war-plugin</artifactId>
          <version>3.2.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-install-plugin</artifactId>
          <version>2.5.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-deploy-plugin</artifactId>
          <version>2.8.2</version>
        </plugin>
      </plugins>
    </pluginManagement>
  </build>
</project>
View Code

 

web.xml

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app> 
  <display-name>Archetype Created Web Application</display-name>
  
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/root-context.xml</param-value>
  </context-param>
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <servlet>
    <servlet-name>my</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>my</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
  <welcome-file-list>
    <welcome-file>/homepage</welcome-file>
  </welcome-file-list>
</web-app>
View Code

 

root-content.xml

<?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:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context 
    http://www.springframework.org/schema/context/spring-context.xsd
    http://www.springframework.org/schema/aop 
    http://www.springframework.org/schema/aop/spring-aop.xsd">
    
    <!-- Root Context: defines shared resources visible to all other web components -->
    <!-- 引入jdbc配置文件 -->  
     <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations">
            <list>
               <value>classpath:properties/*.properties</value>
            </list>
        </property>
    </bean>
    
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.free.dao" />
    </bean>
    
    <!-- 配置数据源 -->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        
        <property name="driverClassName">
            <value>${jdbc_driverClassName}</value>
        </property>
        <property name="url">
            <value>${jdbc_url}</value>
        </property>
        <property name="username">
            <value>${jdbc_username}</value>
        </property>
        <property name="password">
            <value>${jdbc_password}</value>
        </property>
    </bean>
    
    <!--      配置Mybatis文件 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="mapperLocations" value="classpath*:com/free/mapper/**/*.xml"/>  
        <property name="configLocation" value="classpath:mybatis/mybatis-config.xml" />
    </bean>
    
</beans>
View Code

 

my-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
    
    <!-- Enables the Spring MVC @Controller programming model -->
    <annotation-driven />

    <!-- Handles HTTP GET requests for /resources/** by efficiently serving 
        up static resources in the ${webappRoot}/resources directory -->
    <resources mapping="/resources/**" location="/resources/" />
    
    <beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <beans:property name="prefix">
            <beans:value>/pages/</beans:value>
        </beans:property>
        <beans:property name="suffix">
            <beans:value>.jsp</beans:value>
        </beans:property>
        
    </beans:bean>
    
    <!-- 自动扫描controller -->
    <context:component-scan base-package="com.test.demo"/>
    
    <!-- 自动扫描的service -->
    <context:component-scan base-package="com.free.service" />
</beans:beans>
View Code

 

 

第三步:实现用MySQL验证登录

修改以下login.jsp,添加一个报错语句

login.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ page isELIgnored="false" %><!-- 让${Error}当做一个变量,而不是以字符串的形式打印${Error} -->
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Login</title>
</head>
<body>
    <form role="form" action="loginOn" method = "post">
        <table align = "center" border = "1" width = "500">
            <tr>
                <td>username: </td>
                <td>
                    <input type = "text" name = "username"/>
                </td>
            </tr>
            <tr>
                <td>password:</td>
                    <td>
                        <input type = "password" name = "password"/>
                    </td>
            </tr>
            <tr align = "center">
                    <td colspan = "2">
                            <input type = "submit" value = "login"/>
                            <input type = "reset" value = "reset"/>
                    </td>
            </tr>
            
        </table>
        <p style="font-size: 14px; line-height: 150%; font-family: consolas;">
                <font color="red">${Error}</font>
        </p>
    </form>
</body>
</html>
View Code

 

修改Demo.java,添加验证语句

Demo.java

package com.test.demo;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import org.springframework.web.bind.annotation.SessionAttributes;  
import org.springframework.web.servlet.mvc.support.RedirectAttributes;  
import org.springframework.ui.Model;
import javax.annotation.Resource;
import java.util.Enumeration;

import com.free.entity.User;
import com.free.service.UserService;

@Controller
@SessionAttributes("User")
public class Demo {
    
    private static final Logger logger = LoggerFactory.getLogger(Demo.class);
    
    @Resource
    public UserService userService;
    
    @RequestMapping(value = "/")
    public String ShowLogin(){
//        Driver driver =new com.mysql.cj.jdbc.Driver();
//        String url="jdbc:mysql://localhost:3306/LoginTestUser?useSSL=false&serverTimezone=GMT%2B8&allowPublicKeyRetrieval=true";
//        Properties info =new Properties();
//        info.put("user", "root");
//        info.put("password", "123456");
//        Connection conn = (Connection) driver.connect(url, info);
//        System.out.println(conn);
//        System.out.println("成功连接Mysql服务器!");
//        Statement stmt = conn.createStatement();
//        ResultSet rs = (ResultSet) stmt.executeQuery("select * from user");
//        while(rs.next()){
//            System.out.println(rs.getString("ID"));        //取MySQL数据库中user表中的ID
//            System.out.println(rs.getString("name"));   //取MySQL数据库中user表中的name
//            System.out.println(rs.getString("password"));   //取MySQL数据库中user表中的password
//        }
        return "login";
    }
    
    // 点击login时触发
    @RequestMapping(value="/loginOn", method=RequestMethod.POST)
    public ModelAndView Login(HttpServletRequest request, Model model, ModelAndView view, RedirectAttributes redirectAttributes)
    {
        logger.info("======================================");
        System.out.print("Start");
        String name = request.getParameter("username");
        String password = request.getParameter("password");
        User user = userService.login(name, password); 
        if(user != null)
        {
            model.addAttribute("User", user);

            view.setViewName("redirect:/loginOn");
        }
        else
        {
            redirectAttributes.addFlashAttribute("Error", " * Wrong name or password.");
            view.setViewName("redirect:/");
        }
        
        return view;
    }

    
    @RequestMapping(value="/loginOn") 
    public ModelAndView ShowLoginOn(ModelAndView view) 
    { 
        logger.info("====================Move to login on==================");
        System.out.print("123");
        view.setViewName("loginOn"); 
        return view; 
    }
     

}
View Code

 

看一下当前目录结构

 

 

第四步:运行程序,看看是否达到效果。

Update Project,Maven Install,Run on Server。

 

可以看到,可以成功验证。

posted @ 2022-09-26 13:44  o云淡风轻o  阅读(94)  评论(0编辑  收藏  举报