编写一个简单的Spring MVC登录应用程序,帮助大家深入了解Spring MVC。
Spring MVC登录程序前期准备
打开数据库,建库、建表并设置字段信息。
create table x_user(
id int auto_increment primary key,
username varchar(50),
password varchar(32),
phone varchar(20),
email varchar(30)
)
insert into x_user values (null,'admin','123456','130','xx@xx.com');
insert into x_user values (null,'admin2','123456','130','xx@xx.com');
insert into x_user values (null,'admin3','123456','130','xx@xx.com');
insert into x_user values (null,'admin4','123456','130','xx@xx.com');
创建Maven项目,项目情况截图
Maven项目创建完成后,在pom文件中添加依赖的jar包,代码如下:
总的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.shrimpking</groupId>
<artifactId>springtest09</artifactId>
<packaging>pom</packaging>
<version>1.0-SNAPSHOT</version>
<modules>
<module>spring-01</module>
<module>spring-02</module>
<module>spring-03-bankapp</module>
<module>spring-04</module>
<module>spring-05-annotaion</module>
<module>spring-06-mvc</module>
<module>spring-07-b</module>
<module>startmvc</module>
<module>springmvc-01</module>
<module>spingmvc-02-test</module>
<module>springmvc-02-test</module>
<module>springmvc-03-test</module>
<module>springmvc-04-mysql</module>
</modules>
<!--
spring 4.0.0
servlet 3.0.1
jsp-api 2.2
jstl 1.2
standard 1.1.2
junit 3.8.1
commons-logging 1.1.3
-->
<properties>
<spring.version>4.0.0.RELEASE</spring.version>
<servlet.version>3.0.1</servlet.version>
<jsp-api.version>2.2</jsp-api.version>
<jstl.version>1.2</jstl.version>
<standard.version>1.1.2</standard.version>
<junit.version>3.8.1</junit.version>
<commons-logging.version>1.1.3</commons-logging.version>
<jdk.version>1.8</jdk.version>
<maven.complier.plugin.version>2.3.2</maven.complier.plugin.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.version}</version>
</dependency>
<!--servelt-->
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>${jsp-api.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>${servlet.version}</version>
<scope>provided</scope>
</dependency>
<!-- test -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
</dependency>
<!-- jstl -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>${jstl.version}</version>
</dependency>
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>${standard.version}</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven.complier.plugin.version}</version>
<configuration>
<source>${jdk.version}</source>
<target>${jdk.version}</target>
</configuration>
</plugin>
</plugins>
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
</build>
</project>
moudle的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">
<parent>
<artifactId>springtest09</artifactId>
<groupId>com.shrimpking</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>springmvc-04-mysql</artifactId>
<dependencies>
<!-- spring依赖 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.3.9.RELEASE</version>
</dependency>
<!--junit测试依赖-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<!-- 数据库库连接池 -->
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.4</version>
</dependency>
<!--mysql驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<!-- lombok依赖包 -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.10</version>
</dependency>
</dependencies>
</project>
Spring MVC的jar包添加完成后,需要在src/main/resources文件夹中添加配置文件,配置文件名分别为spring-mvc.xml、spring-dao.xml、spring-service.xml。
spring-mvc.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"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
https://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/tx
https://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd">
<!-- 自动包扫描 -->
<context:component-scan base-package="com.shrimpking.controller"/>
<!-- 视图解析器 -->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
<property name="prefix" value="/WEB-INF/view/"/>
<property name="suffix" value=".jsp"/>
</bean>
<mvc:annotation-driven/>
</beans>
spring-dao.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"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:p="http://www.springframework.org/schema/p" xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
https://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/tx
https://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">
<!-- 自动包扫描 -->
<context:component-scan base-package="com.shrimpking.dao"/>
<util:properties id="dbConfig" location="classpath:db.properties"/>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="#{dbConfig.driverClassName}"/>
<property name="url" value="#{dbConfig.url}"/>
<property name="username" value="#{dbConfig.username}"/>
<property name="password" value="#{dbConfig.password}"/>
</bean>
</beans>
spring-service.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"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:p="http://www.springframework.org/schema/p" xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
https://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/tx
https://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">
<!-- 自动包扫描 -->
<context:component-scan base-package="com.shrimpking.service"/>
</beans>
文件配置完成后,由于使用到了数据库,所以要进行数据库连接的配置,文件名为db.properties,配置代码如下:
db.properties
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimeZone=UTC
username=root
password=mysql123
ApplicationContext.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<import resource="spring-mvc.xml"/>
<import resource="spring-dao.xml"/>
<import resource="spring-service.xml"/>
</beans>
数据库文件配置完成后,需要在WEB-INF中配置web.xml文件,具体配置代码如下:
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<!-- web应用上下文参数 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:ApplicationContext.xml</param-value>
</context-param>
<!-- 监听 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 过滤器,中文乱码 -->
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>utf-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- 分发控制器 -->
<servlet>
<servlet-name>DispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-mvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>DispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
Spring MVC登录程序代码实现
-----------------------------------------------------------------------------------------------------------
使用Spring MVC来完成登录应用程序的代码。在框架中,通常将代码分为四层:页面、控制层、业务层、持久层(数据库)。编写代码时,先写持久层、业务层、控制层,再写页面,具体步骤如下。
配置完成后,可以进行业务逻辑的实现。在src/main/java文件夹中新建实体类User.java,包名为com.shrimpking.pojo,具体配置代码如下
User.java
package com.shrimpking.pojo;
import java.util.Objects;
/**
* @author user1
*/
public class User
{
private int id;
private String username;
private String password;
private String phone;
private String email;
public User()
{
}
public User(int id, String username, String password, String phone, String email)
{
this.id = id;
this.username = username;
this.password = password;
this.phone = phone;
this.email = email;
}
public int getId()
{
return id;
}
public void setId(int id)
{
this.id = id;
}
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 getPhone()
{
return phone;
}
public void setPhone(String phone)
{
this.phone = phone;
}
public String getEmail()
{
return email;
}
public void setEmail(String email)
{
this.email = email;
}
@Override
public String toString()
{
return "User{" + "id=" + id + ", username='" + username + '\'' + ", password='" + password + '\'' + ", phone='" + phone + '\'' + ", email='" + email + '\'' + '}';
}
@Override
public boolean equals(Object obj)
{
if (this == obj)
{
return true;
}
if (obj == null || getClass() != obj.getClass())
{
return false;
}
User user = (User) obj;
return id == user.id && username.equals(user.username) && password.equals(user.password) && phone.equals(user.phone) && email.equals(user.email);
}
@Override
public int hashCode()
{
return Objects.hash(id, username, password, phone, email);
}
}
在Spring MVC框架中,Bean的实体类User创建完成后,需要写数据库的Dao层代码,新建包com.shrimpking.dao,在包下新建一个UserDao接口,并使UserDaoImpl.java实现接口UserDao。
UserDao.java
package com.shrimpking.dao;
import com.shrimpking.pojo.User;
/**
* @author user1
*/
public interface UserDao
{
User selectByUserName(String username);
}
UserDaoImpl.java
package com.shrimpking.dao;
import com.shrimpking.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import javax.annotation.Resource;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
* @author user1
*/
@Repository
public class UserDaoImpl implements UserDao
{
@Resource
//@Autowired
private DataSource dataSource;
@Override
public User selectByUserName(String username)
{
User user = null;
try
{
//获取数据库连接对象
Connection conn = dataSource.getConnection();
//获取预编译对象
String sql = "select * from x_user where username=?";
PreparedStatement pstmt = conn.prepareStatement(sql);
//赋值
pstmt.setString(1,username);
//执行查询
ResultSet rs = pstmt.executeQuery();
//处理结果集
if(rs.next())
{
user = new User();
user.setId(rs.getInt("id"));
user.setUsername(rs.getString("username"));
user.setPassword(rs.getString("password"));
user.setPhone(rs.getString("phone"));
user.setEmail(rs.getString("email"));
}
//关闭资源
rs.close();
pstmt.close();
conn.close();
}
catch (SQLException e)
{
e.printStackTrace();
}
return user;
}
}
下面介绍业务层(Service)的代码实现。
在src/main/java文件夹中新建包com.shrimpking.service,在包下新建一个UserService接口和实现接口的UserServiceImpl.java类,并在UserServiceImpl.java类中对用户和密码进行判断。
UserService.java
package com.shrimpking.service;
import com.shrimpking.pojo.User;
public interface UserService
{
User login(String username,String pwd);
}
UserServiceImpl.java
package com.shrimpking.service;
import com.shrimpking.dao.UserDao;
import com.shrimpking.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
/**
* @author user1
*/
@Service
public class UserServiceImpl implements UserService
{
@Resource
//@Autowired
private UserDao userDao;
@Override
public User login(String username, String pwd)
{
//1调用持久层的方法,返回user对象
User user = userDao.selectByUserName(username);
//2判断user用户是否存在
if(user == null)
{
throw new RuntimeException("用户名错误");
}
else
{
//3判断,密码是否正确
if(user.getPassword().equals(pwd))
{
return user;
}
else
{
throw new RuntimeException("密码错误");
}
}
}
}
UserServiceImpl配置完成后,使用JUnit来进行测试。在src/test/java文件夹中新建类UserTest,包名为com.shrimpking.test,代码如下:
UserTest.java
package com.shrimpking.test;
import com.shrimpking.dao.UserDaoImpl;
import com.shrimpking.service.UserService;
import com.shrimpking.service.UserServiceImpl;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class UserTest
{
/**
* 测试查询用户是否正确
*/
@Test
public void testSelectByUserName()
{
//1获取容器对象
ApplicationContext context = new ClassPathXmlApplicationContext("spring-dao.xml");
//2获取bean对象
UserDaoImpl userDaoImpl = context.getBean("userDaoImpl", UserDaoImpl.class);
//3调用方法
System.out.println(userDaoImpl.selectByUserName("admin"));
}
/**
* 测试登录是否正确
*/
@Test
public void testLogin()
{
ApplicationContext context = new ClassPathXmlApplicationContext("ApplicationContext.xml");
UserService userService = context.getBean("userServiceImpl", UserService.class);
System.out.println(userService.login("admin", "123456"));
}
}
提示:JUnit是一个Java语言的单元测试框架,多数Java开发环境都已经集成了JUnit作为单元测试的工具。JUnit是由Erich Gamma和Kent Beck编写的一个回归测试框架。Junit测试是程序开发人员测试,即白盒测试,因为程序开发人员知道被测试的软件如何完成功能和完成什么样的功能。JUnit是一套框架,继承TestCase类,就可以用JUnit进行自动测试了。
测试结果截图
业务层配置完成后,要进行控制层的代码实现。在src/main/java文件夹中新建类LoginController,包名为com.shrimpking.controller,具体代码如下:
LoginController.java
package com.shrimpking.controller;
import com.shrimpking.pojo.User;
import com.shrimpking.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import javax.servlet.http.HttpSession;
/**
* @author user1
*/
@Controller
@RequestMapping("/user")
public class LoginController
{
@Autowired
private UserService userService;
/**
* 显示登录页面
* @return
*/
@RequestMapping("/toLogin")
public String toLogin()
{
return "login";
}
/**
* 判断登录,
* @param username
* @param pwd
* @param map
* @param session
* @return
*/
@RequestMapping("/login")
public String login(
@RequestParam("name") String username,
@RequestParam("pwd") String pwd,
ModelMap map,
HttpSession session)
{
System.out.println("name:" + username);
try
{
User user = userService.login(username,pwd);
session.setAttribute("user",user);
return "index";
}
catch (RuntimeException e)
{
if( "用户名错误".equals(e.getMessage())
|| "密码错误".equals(e.getMessage()))
{
map.addAttribute("error",e.getMessage());
return "login";
}
throw new RuntimeException(e.getMessage());
}
}
/**
* 显示个人信息
* @return
*/
@RequestMapping("/userInfo")
public String showInfo()
{
return "userInfo";
}
/**
* 退出
* @param session
* @return
*/
@RequestMapping("/exit")
public String exit(HttpSession session)
{
//会话层立即失效
session.invalidate();
return "login";
}
}
控制层配置完成后,下面需要实现简单的页面。在WEB-INF文件夹中新建文件夹view,在view文件夹中新建login.jsp、index.jsp、error.jsp、userInfo.jsp页面。
login.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>login</title>
</head>
<body>
${error}<br>
<form action="${pageContext.request.contextPath}/user/login" method="get">
账号:<input type="text" name="name" id="name"><br>
密码:<input type="password" name="pwd" id="pwd"><br>
<input type="submit" value="登录">
</form>
</body>
</html>
index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>index</title>
</head>
<body>
<h3>${sessionScope.user.username},登录成功!</h3>
<div align="left" style="color: red">
<a href="${pageContext.request.contextPath}/user/exit">退出</a>
<br>
<a href="${pageContext.request.contextPath}/user/userInfo">显示个人信息</a>
</div>
</body>
</html>
error.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>error</title>
</head>
<body>
<h1>应用程序出现错误,请联系服务商!</h1>
<p>错误提示:</p>
${error}
</body>
</html>
userInfo.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>userInfo</title>
</head>
<body>
<h3>${user.username}的个人信息如下:</h3>
编号:${user.id}<br>
账号:${user.username}<br>
密码:${user.password}<br>
电话:${user.phone}<br>
邮箱:${user.email}<br>
</body>
</html>
页面创建完成后,运行程序进行检验,在页面上进行登录验证。
运行情况截图