SpringMVC學習(二)--實現簡單使用者登入
阿新 • • 發佈:2019-02-08
1.搭建框架
建立Maven專案並配置pom.xml:
<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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId >com.lq</groupId>
<artifactId>Springmvc01</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<!-- 設定UTF-8編碼格式 -->
<properties>
<!-- 檔案拷貝時的編碼 -->
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding >
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<!-- 編譯時的編碼 -->
<maven.compiler.encoding>UTF-8</maven.compiler.encoding>
<!-- 自定義常量,在依賴中可以通過${名字}的方式進行引用 -->
<spring.version>4.3.14.RELEASE</spring.version >
</properties>
<dependencies>
<!-- springmvc配置 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- servlet配置 -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<!-- 流程處理標籤配置 -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- spring相關配置 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- hibernate配置 -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.1.12.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>6.0.2.Final</version>
</dependency>
<!-- 連線池配置 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.6</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.41</version>
</dependency>
<!-- 單元測試配置 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
<!-- jdk版本配置 -->
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
2.配置web.xml前端控制器[有兩種常見配置,*.do或者/
<?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>Springmvc01</display-name>
<context-param>
<param-name>appName</param-name>
<param-value>Springmvc01-Hibernate-使用者登入</param-value>
</context-param>
<!-- 整合Spring和 web應用,這裡負責載入父容器,父容器對應的配置檔案是classpath:applicationContext.xml -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:app*.xml</param-value>
</context-param>
<!-- 過濾器處理中文亂碼 -->
<!--提交資料時如果需要傳送中文,請使用post提交-->
<filter>
<filter-name>encoder</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>encoder</filter-name>
<servlet-name>lq</servlet-name>
</filter-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 配置前端控制器,它負責載入子容器,子容器配置檔案是/WEB-INF/lq-servlet.xml -->
<servlet>
<servlet-name>lq</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- 隨系統啟動 -->
<load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>lq</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
3.SpringMVC應用中的父子容器的概念
在Spring整體框架的核心概念中,容器是核心思想,就是用來管理Bean的整個生命週期的,而在一個專案中,容器不一定只有一個,Spring中可以包括多個容器,而且容器有上下層關係,目前最常見的一種場景就是在一個專案中引入Spring和SpringMVC這兩個框架,那麼它其實就是兩個容器,Spring是父容器,SpringMVC是其子容器,並且在Spring父容器中註冊的Bean對於SpringMVC容器中是可見的,而在SpringMVC容器中註冊的Bean對於Spring父容器中是不可見的,也就是子容器可以看見父容器中的註冊的Bean,反之就不行。
子容器中一般配置和web應用相關的元件,例如ViewResolver檢視解析器、控制器等。父容器中配置和web應用不直接相關的元件,例如連線池、SessionFactory、業務Bean等.
4.新增Servlet相關的核心配置
慣例:位於WEB-INF目錄下,名稱為<servlet的名稱>-servlet.xml
例如/WEB-INF/lq-servlet.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:mvc="http://www.springframework.org/schema/mvc"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.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-4.3.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">
<!-- 開啟mvc應用中的註解支援 -->
<mvc:annotation-driven validator="valid1"/>
<!-- 配置檢視解析器,將邏輯地址名轉換為實體地址,其中prefix用於設定字首,suffix用於設定字尾,viewClass用於設定檢視型別。例如
返回檢視名稱為abc,則對應的實體地址為“字首”+邏輯地址名+"字尾"構成.ViewClass允許使用者定義各種檢視型別,例如返回pdf、Excel等 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/WEB-INF/content/" p:suffix=".jsp"
p:viewClass="org.springframework.web.servlet.view.JstlView"/>
<!-- 啟用Hinbernate提供的校驗器 -->
<bean id="valid1"
class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
<property name="providerClass" value="org.hibernate.validator.HibernateValidator"></property>
</bean>
<!-- 定義控制器 -->
<context:component-scan base-package="com.lq.action">
<context:include-filter type="annotation"
expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
</beans>
5.定義控制器
package com.lq.action;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.Errors;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.lq.action.group.UserGroup;
import com.lq.entity.UserBean;
@Controller//用於標識是處理器類
@RequestMapping("/")// 定義在類上則類似於Struts2中的名空間,給類中的所有方法添加了一個名空間
public class UserController {
/*
@RequestMapping(value = "login", method = RequestMethod.GET)
public ModelAndView login()throws Exception{
ModelAndView mv = new ModelAndView();
UserBean user = new UserBean();
mv.addObject("user", user);
mv.setViewName("user/login");
return mv;
ModelAndView:
簡單理解它是將後臺返回的資料傳遞給View層,同時包含一個要訪問的View層的URL地址,當控制器處理完請求後,通常控制器會將包含檢視名稱以及一些模型屬性的ModelAndView物件返回給DispatcherServlet。因此,在控制器中會構造一個ModelAndView物件
ModelAndView作用
1)設定轉向地址
2)將底層獲取的資料進行儲存(或者封裝)
3)最後將資料傳遞給View
ModelAndView的用法:
先建立ModelAndView物件,再通過它的方法去設定資料與轉發的檢視名
ModelAndView modelAndView = new ModelAndView();構建物件
modelAndView.setViewName("m06"); 設定邏輯檢視名
modelAndView.addObject("message", "Hello World, Hello Kitty");新增需要顯示的資料
*/
//對映login()方法到get請求的login.do上
@RequestMapping(value = "login", method = RequestMethod.GET)
public String login(Model model) throws Exception {
UserBean user = new UserBean();
model.addAttribute("user", user);
return "user/login";
}
/*
* 在Controller方法上添加註解@Validated,啟動伺服器端資料校驗
* 通過分組區分不同方法的資料校驗和定義校驗執行順序(前面的校驗沒有通過則後續校驗不執行)
* 實現方法:採用旗標介面實現,定義如下介面和類
@GroupSequence({UserFirstGroup.class,UserSecondGroup.class})設定順序
public interface UserGroup { }
public Class UserFirstGroup { }
public Class UserSecondGroup{ }
@NotEmpty(message="使用者名稱稱不能為空!",groups=UserFirstGroup.class)
@Length(min=6,max=20,message="使用者名稱稱只能在6到20個字元之間!",groups=UserSecondGroup.class)
private String username;
*/
@RequestMapping(value="login" ,method=RequestMethod.POST)
public String login(@Validated(UserGroup.class)@ModelAttribute("user") UserBean user, Errors errors) {
System.out.println(user);
if (errors.hasErrors())
return "user/login";
return "show";
}
}
旗標介面實現類和介面:
package com.lq.action.group;
import javax.validation.GroupSequence;
@GroupSequence({UserFirstGroup.class,UserSecondGroup.class})//設定順序
public interface UserGroup {}
package com.lq.action.group;
public class UserFirstGroup {}
package com.lq.action.group;
public class UserSecondGroup {}
實體類:
package com.lq.entity;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import static javax.persistence.GenerationType.IDENTITY;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Transient;
import javax.validation.constraints.NotEmpty;
import org.hibernate.validator.constraints.Length;
import com.lq.action.group.UserFirstGroup;
import com.lq.action.group.UserSecondGroup;
@Entity(name = "t_users")
public class UserBean implements java.io.Serializable {
private static final long serialVersionUID = 5385542861402736914L;
@Id
@GeneratedValue(strategy = IDENTITY)
@Column(name = "id", unique = true, nullable = false)
private Long id;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "role_id", nullable = false)
private RoleBean role=new RoleBean();
@NotEmpty(message="使用者名稱稱不能為空!",groups=UserFirstGroup.class)
@Length(min=6,max=10,message="使用者名稱稱只能在6到10個字元之間",groups=UserSecondGroup.class)
@Column(name = "username", unique = true, nullable = false)
private String username;
@NotEmpty(message="使用者口令不能為空!",groups=UserFirstGroup.class)
@Column(name = "password", nullable = false, length = 20)
private String password;
@Transient
private String repassword;
@Column(columnDefinition="timestamp default current_timestamp")
private Date birth;
@Column(columnDefinition="boolean default 1")
private Boolean sex;
public UserBean() {
}
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
public RoleBean getRoleBean() {
return this.role;
}
public void setRoleBean(RoleBean role) {
this.role = role;
}
public String getUsername() {
return this.username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return this.password;
}
public void setPassword(String password) {
this.password = password;
}
public Date getBirth() {
return birth;
}
public void setBirth(Date birth) {
this.birth = birth;
}
public Boolean getSex() {
return this.sex;
}
public void setSex(Boolean sex) {
this.sex = sex;
}
public String getRepassword() {
return repassword;
}
public void setRepassword(String repassword) {
this.repassword = repassword;
}
@Override
public String toString() {
return "UserBean [username=" + username + ", password=" + password + "]";
}
}
前臺頁面:
index.jsp:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>${initParam.appName }</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
</head>
<body>
<a href="login.do">登入系統</a>
</body>
</html>
login.jsp:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>${initParam.appName }</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
</head>
<body>
<form:form modelAttribute="user" >
<table>
<tr>
<td><form:label path="username">使用者名稱稱:</form:label></td>
<td><form:input path="username" cssStyle="width=200px"/><form:errors path="username"/></td>
</tr>
<tr>
<td><form:label path="password">使用者口令:</form:label></td>
<td><form:password path="password" cssStyle="width=200px"/><form:errors path="password"/></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="登入系統">
<input type="reset" value="重置資料">
</td>
</tr>
</table>
</form:form>
</body>
</html>
show.jsp:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>${initParam.appName }</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
</head>
<body>
登陸成功...
</body>
</html>
效果圖: