Top

JAVA Spring MyBatis DAY04

  1. 实战案例
  2. 登录

1 实战案例

1.1 问题

  1. 练习接收页面参数值
  2. 练习向页面传出数据
  3. 练习使用session
  4. 练习重定向

1.2 方案

  1. 接收页面参数值有3种方式
  2. 使用request
  3. 使用@RequestParam注解
  4. 使用实体对象
  5. 向页面传出数据有3种方式
  6. 使用ModelAndView对象
  7. 使用ModelMap对象
  8. 使用@ModelAttribute注解
  9. 在Controller方法参数上直接声明HttpSession即可使用
  10. 重定向有2种方式
  11. 使用RedirectView
  12. 使用redirect:

1.3 步骤

步骤一:创建项目,导入jar包

创建项目Spring04,导入Spring开发包,如下图:

图-1

步骤二:配置web.xml

配置web.xml,代码如下:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
	xmlns="/java.sun.com/xml/ns/javaee" 
	xmlns:xsi="/www.w3.org/2001/XMLSchema-instance" 
	xsi:schemaLocation="/java.sun.com/xml/ns/javaee 
	/java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>

	<servlet>
		<servlet-name>springmvc</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>springmvc</servlet-name>
		<url-pattern>*.do</url-pattern>
	</servlet-mapping>

</web-app>

步骤三:配置Spring配置文件

创建Spring配置文件spring-mvc.xml,代码如下:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="/www.springframework.org/schema/beans" 
	xmlns:xsi="/www.w3.org/2001/XMLSchema-instance"
	xmlns:context="/www.springframework.org/schema/context" 
	xmlns:jdbc="/www.springframework.org/schema/jdbc"  
	xmlns:jee="/www.springframework.org/schema/jee" 
	xmlns:tx="/www.springframework.org/schema/tx"
	xmlns:aop="/www.springframework.org/schema/aop" 
	xmlns:mvc="/www.springframework.org/schema/mvc"
	xmlns:util="/www.springframework.org/schema/util"
	xmlns:jpa="/www.springframework.org/schema/data/jpa"
	xsi:schemaLocation="
		/www.springframework.org/schema/beans /www.springframework.org/schema/beans/spring-beans-3.2.xsd
		/www.springframework.org/schema/context /www.springframework.org/schema/context/spring-context-3.2.xsd
		/www.springframework.org/schema/jdbc /www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd
		/www.springframework.org/schema/jee /www.springframework.org/schema/jee/spring-jee-3.2.xsd
		/www.springframework.org/schema/tx /www.springframework.org/schema/tx/spring-tx-3.2.xsd
		/www.springframework.org/schema/data/jpa /www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd
		/www.springframework.org/schema/aop /www.springframework.org/schema/aop/spring-aop-3.2.xsd
		/www.springframework.org/schema/mvc /www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
		/www.springframework.org/schema/util /www.springframework.org/schema/util/spring-util-3.2.xsd">
	
	<!--开启注解扫描 -->
	<context:component-scan base-package="com.tarena"/>
	
	<!--开启MVC注解扫描 -->
	<mvc:annotation-driven/>
	
	<!--定义视图解析器ViewResolver -->
	<bean id="viewResolver"
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/WEB-INF/"/>
		<property name="suffix" value=".jsp"/>
	</bean>
	
</beans>

步骤四:创建Controller

创建实体类User,代码如下:

package com.tarena.entity;

import java.io.Serializable;

public class User implements Serializable {

	private Integer id;
	private String userName;
	private String password;

	public Integer getId() {
		return id;
	}

	public void setId(Integer 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;
	}

}

创建Controller,代码如下:

package com.tarena.web;

import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;
import com.tarena.entity.User;

@Controller
@RequestMapping("/demo")
public class HelloController {
	
	//使用request接收参数
	@RequestMapping("/test1.do")
	public ModelAndView test1(HttpServletRequest request) {
		String userName = request.getParameter("userName");
		String password = request.getParameter("password");
		System.out.println(userName);
		System.out.println(password);
		return new ModelAndView("jsp/hello");
	}
	
	//使用方法参数接收参数
	@RequestMapping("/test2.do")
	public ModelAndView test2(String userName, 
			@RequestParam("password") String pwd) {
		System.out.println(userName);
		System.out.println(pwd);
		return new ModelAndView("jsp/hello");
	}
	
	//使用对象接收参数
	@RequestMapping("/test3.do")
	public ModelAndView test3(User user) {
		System.out.println(user.getUserName());
		System.out.println(user.getPassword());
		return new ModelAndView("jsp/hello");
	}
	
	//使用ModelAndView传出数据
	@RequestMapping("/test4.do")
	public ModelAndView test4() {
		Map<String, Object> data = new HashMap<String, Object>();
		data.put("success", true);
		data.put("message", "操作成功");
		return new ModelAndView("jsp/hello", data);
	}
	
	//使用ModelMap传出数据
	@RequestMapping("/test5.do")
	public ModelAndView test5(ModelMap model) {
		model.addAttribute("success", false);
		model.addAttribute("message", "操作失败");
		return new ModelAndView("jsp/hello");
	}
	
	
	//使用@ModelAttribute传出bean属性
	@ModelAttribute("age")
	public int getAge() {
		return 25;
	}
	
	//使用@ModelAttribute传出参数值
	@RequestMapping("/test6.do")
	public ModelAndView test6(
			@ModelAttribute("userName") String userName,
			String password) {
		return new ModelAndView("jsp/hello");
	}
	
	//使用session
	@RequestMapping("/test7.do")
	public ModelAndView test7(HttpServletRequest request, User user) {
		HttpSession session = request.getSession();
		session.setAttribute("salary", 6000.0);
		return new ModelAndView("jsp/hello");
	}
	
	//返回String
	@RequestMapping("/test8.do")
	public String test8(User user, ModelMap model) {
		model.addAttribute("user", user);
		return "jsp/hello";
	}

	//系统错误页面
	@RequestMapping("/test9.do")
	public String test9() {
		return "jsp/error";
	}
	
	//使用RedirectView重定向
	@RequestMapping("/test10.do")
	public ModelAndView test10(User user) {
		if(user.getUserName().equals("tarena")) {
			return new ModelAndView("jsp/hello");
		} else {
			return new ModelAndView(new RedirectView("test9.do"));
		}
	}
	
	//使用redirect重定向
	@RequestMapping("/test11.do")
	public String test11(User user) {
		if(user.getUserName().equals("tarena")) {
			return "jsp/hello";
		} else {
			return "redirect:test9.do";
		}
	}	
	
}

步骤五:创建页面

在index.jsp上增加表单,请求提交给HelloController,代码如下:

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">

<title>My JSP 'index.jsp' starting page</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">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
</head>

<body>

<h1>测试表单</h1>
<form action="demo/test1.do" method="post">
		账号:<input type="text" name="userName"/><br/><br/>
		密码:<input type="password" name="password"/><br/><br/>
		<input type="submit" value="提交"/>
</form>

</body>
</html>

在WEB-INF/jsp下创建hello.jsp,代码如下:

<%@page pageEncoding="utf-8"%>
<html>
<head></head>
<body>
	<h1>Hello, SpringMVC.</h1>
	
	<h1>是否成功:${success }</h1>
	<h1>提示信息:${message }</h1>
	
	<h1>年龄:${age }</h1>
	<h1>账号:${userName }</h1>
	
	<h1>工资:${salary }</h1>
	
	<h1>对象:${user.userName }</h1>
	
</body>
</html>

在WEB-INF/jsp下创建error.jsp,代码如下:

<%@page pageEncoding="utf-8"%>
<html>
<head></head>
<body>
	<h1 style="color:red;">Error.</h1>
</body>
</html>

步骤六:测试接收页面参数

通过浏览器访问/localhost:8088/Spring04/index.jsp,将表单填写完整并提交,控制台输出效果如下图:

图-2

将index.jsp中表单提交的路径分别改为“demo/test2.do”和“demo/test3.do”后,测试结果和上图一致。

步骤七:测试向页面传出数据

通过浏览器访问/localhost:8088/Spring04/demo/test4.do,浏览器显示效果如下图:

图-3

通过浏览器访问/localhost:8088/Spring04/demo/test5.do,浏览器显示效果如下图:

图-4

将index.jsp中表单提交的路径改为“demo/test6.do”,通过浏览器访问/localhost:8088/Spring04/index.jsp,将表单填写完整并提交,浏览器显示效果如下图:

图-5

步骤八:测试session

将index.jsp中表单提交的路径改为“demo/test7.do”,通过浏览器访问/localhost:8088/Spring04/index.jsp,将表单填写完整并提交,浏览器显示效果如下图:

图-6

步骤九:测试重定向

将index.jsp中表单提交的路径改为“demo/test10.do”,通过浏览器访问/localhost:8088/Spring04/index.jsp,将表单账号填写为tarena并提交,浏览器显示效果如下图:

图-7

重新将表单中账号填写为其他的值并提交,浏览器显示效果如下图:

图-8

将index.jsp中表单提交的路径改为“demo/test11.do”,重新执行上述测试,结果与上述测试结果一致。

1.4 完整代码

web.xml完整代码如下:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
	xmlns="/java.sun.com/xml/ns/javaee" 
	xmlns:xsi="/www.w3.org/2001/XMLSchema-instance" 
	xsi:schemaLocation="/java.sun.com/xml/ns/javaee 
	/java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>

	<servlet>
		<servlet-name>springmvc</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>springmvc</servlet-name>
		<url-pattern>*.do</url-pattern>
	</servlet-mapping>

</web-app>

spring-mvc.xml完整代码如下:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="/www.springframework.org/schema/beans" 
	xmlns:xsi="/www.w3.org/2001/XMLSchema-instance"
	xmlns:context="/www.springframework.org/schema/context" 
	xmlns:jdbc="/www.springframework.org/schema/jdbc"  
	xmlns:jee="/www.springframework.org/schema/jee" 
	xmlns:tx="/www.springframework.org/schema/tx"
	xmlns:aop="/www.springframework.org/schema/aop" 
	xmlns:mvc="/www.springframework.org/schema/mvc"
	xmlns:util="/www.springframework.org/schema/util"
	xmlns:jpa="/www.springframework.org/schema/data/jpa"
	xsi:schemaLocation="
		/www.springframework.org/schema/beans /www.springframework.org/schema/beans/spring-beans-3.2.xsd
		/www.springframework.org/schema/context /www.springframework.org/schema/context/spring-context-3.2.xsd
		/www.springframework.org/schema/jdbc /www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd
		/www.springframework.org/schema/jee /www.springframework.org/schema/jee/spring-jee-3.2.xsd
		/www.springframework.org/schema/tx /www.springframework.org/schema/tx/spring-tx-3.2.xsd
		/www.springframework.org/schema/data/jpa /www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd
		/www.springframework.org/schema/aop /www.springframework.org/schema/aop/spring-aop-3.2.xsd
		/www.springframework.org/schema/mvc /www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
		/www.springframework.org/schema/util /www.springframework.org/schema/util/spring-util-3.2.xsd">
	
	<!-- 开启注解扫描 -->
	<context:component-scan base-package="com.tarena"/>
	
	<!-- 开启MVC注解扫描 -->
	<mvc:annotation-driven/>
	
	<!--定义视图解析器ViewResolver -->
	<bean id="viewResolver"
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/WEB-INF/"/>
		<property name="suffix" value=".jsp"/>
	</bean>
	
</beans>

User类完整代码如下:

package com.tarena.entity;

import java.io.Serializable;

public class User implements Serializable {

	private Integer id;
	private String userName;
	private String password;

	public Integer getId() {
		return id;
	}

	public void setId(Integer 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;
	}

}

HelloController完整代码如下:

package com.tarena.web;

import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;
import com.tarena.entity.User;

@Controller
@RequestMapping("/demo")
public class HelloController {
	
	//使用request接收参数
	@RequestMapping("/test1.do")
	public ModelAndView test1(HttpServletRequest request) {
		String userName = request.getParameter("userName");
		String password = request.getParameter("password");
		System.out.println(userName);
		System.out.println(password);
		return new ModelAndView("jsp/hello");
	}
	
	//使用方法参数接收参数
	@RequestMapping("/test2.do")
	public ModelAndView test2(String userName, 
			@RequestParam("password") String pwd) {
		System.out.println(userName);
		System.out.println(pwd);
		return new ModelAndView("jsp/hello");
	}
	
	//使用对象接收参数
	@RequestMapping("/test3.do")
	public ModelAndView test3(User user) {
		System.out.println(user.getUserName());
		System.out.println(user.getPassword());
		return new ModelAndView("jsp/hello");
	}
	
	//使用ModelAndView传出数据
	@RequestMapping("/test4.do")
	public ModelAndView test4() {
		Map<String, Object> data = new HashMap<String, Object>();
		data.put("success", true);
		data.put("message", "操作成功");
		return new ModelAndView("jsp/hello", data);
	}
	
	//使用ModelMap传出数据
	@RequestMapping("/test5.do")
	public ModelAndView test5(ModelMap model) {
		model.addAttribute("success", false);
		model.addAttribute("message", "操作失败");
		return new ModelAndView("jsp/hello");
	}
	
	
	//使用@ModelAttribute传出bean属性
	@ModelAttribute("age")
	public int getAge() {
		return 25;
	}
	
	//使用@ModelAttribute传出参数值
	@RequestMapping("/test6.do")
	public ModelAndView test6(
			@ModelAttribute("userName") String userName,
			String password) {
		return new ModelAndView("jsp/hello");
	}
	
	//使用session
	@RequestMapping("/test7.do")
	public ModelAndView test7(HttpServletRequest request, User user) {
		HttpSession session = request.getSession();
		session.setAttribute("salary", 6000.0);
		return new ModelAndView("jsp/hello");
	}
	
	//返回String
	@RequestMapping("/test8.do")
	public String test8(User user, ModelMap model) {
		model.addAttribute("user", user);
		return "jsp/hello";
	}

	//系统错误页面
	@RequestMapping("/test9.do")
	public String test9() {
		return "jsp/error";
	}
	
	//使用RedirectView重定向
	@RequestMapping("/test10.do")
	public ModelAndView test10(User user) {
		if(user.getUserName().equals("tarena")) {
			return new ModelAndView("jsp/hello");
		} else {
			return new ModelAndView(new RedirectView("test9.do"));
		}
	}
	
	//使用redirect重定向
	@RequestMapping("/test11.do")
	public String test11(User user) {
		if(user.getUserName().equals("tarena")) {
			return "jsp/hello";
		} else {
			return "redirect:test9.do";
		}
	}	
	
}

hello.jsp完整代码如下:

<%@page pageEncoding="utf-8"%>
<html>
<head></head>
<body>
	<h1>Hello, SpringMVC.</h1>
	
	<h1>是否成功:${success }</h1>
	<h1>提示信息:${message }</h1>
	
	<h1>年龄:${age }</h1>
	<h1>账号:${userName }</h1>
	
	<h1>工资:${salary }</h1>
	
	<h1>对象:${user.userName }</h1>
	
</body>
</html>

error.jsp完整代码如下:

<%@page pageEncoding="utf-8"%>
<html>
<head></head>
<body>
	<h1 style="color:red;">Error.</h1>
</body>
</html>

2 登录

2.1 问题

实现NETCTOSS登录功能。

2.2 方案

开发准备:

  1. 创建项目、导入jar包
  2. 配置web.xml
  3. 配置Spring配置文件
  4. 建表

打开登录页开发步骤:

  1. 在Controller中增加打开登录页的方法
  2. 创建登录页面

提交登录验证开发步骤:

  1. 在DAO中增加根据账号查询用户的方法
  2. 在Service中增加验证账号和密码的方法
  3. 在Controller中增加登录验证的方法
  4. 修改登录页面,设置表单

2.3 步骤

步骤一:开发准备

创建项目NETCTOSS1,导入jar包,如下图:

图-9

配置web.xml,代码如下:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
	xmlns="/java.sun.com/xml/ns/javaee" 
	xmlns:xsi="/www.w3.org/2001/XMLSchema-instance" 
	xsi:schemaLocation="/java.sun.com/xml/ns/javaee 
	/java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>

	<servlet>
		<servlet-name>spring</servlet-name>
		<servlet-class>
			org.springframework.web.servlet.DispatcherServlet
		</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>classpath:applicationContext.xml</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
		<servlet-name>spring</servlet-name>
		<url-pattern>*.do</url-pattern>
	</servlet-mapping>	

</web-app>

创建数据库连接资源文件jdbc.properties,代码如下:

url=jdbc:oracle:thin:@localhost:1521:xe
driver=oracle.jdbc.OracleDriver
user=lhh
password=123456

创建Spring配置文件applicationContext.xml,代码如下:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="/www.springframework.org/schema/beans" 
	xmlns:xsi="/www.w3.org/2001/XMLSchema-instance"
	xmlns:context="/www.springframework.org/schema/context" 
	xmlns:jdbc="/www.springframework.org/schema/jdbc"  
	xmlns:jee="/www.springframework.org/schema/jee" 
	xmlns:tx="/www.springframework.org/schema/tx"
	xmlns:aop="/www.springframework.org/schema/aop" 
	xmlns:mvc="/www.springframework.org/schema/mvc"
	xmlns:util="/www.springframework.org/schema/util"
	xmlns:jpa="/www.springframework.org/schema/data/jpa"
	xsi:schemaLocation="
		/www.springframework.org/schema/beans /www.springframework.org/schema/beans/spring-beans-3.2.xsd
		/www.springframework.org/schema/context /www.springframework.org/schema/context/spring-context-3.2.xsd
		/www.springframework.org/schema/jdbc /www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd
		/www.springframework.org/schema/jee /www.springframework.org/schema/jee/spring-jee-3.2.xsd
		/www.springframework.org/schema/tx /www.springframework.org/schema/tx/spring-tx-3.2.xsd
		/www.springframework.org/schema/data/jpa /www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd
		/www.springframework.org/schema/aop /www.springframework.org/schema/aop/spring-aop-3.2.xsd
		/www.springframework.org/schema/mvc /www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
		/www.springframework.org/schema/util /www.springframework.org/schema/util/spring-util-3.2.xsd">
	
	<util:properties id="jdbc" location="classpath:jdbc.properties"/>
	
	<!--定义数据源 -->
	<bean id="ds" 
		class="org.apache.commons.dbcp.BasicDataSource"
		destroy-method="close">
		<property name="url" value="#{jdbc.url}"/>
		<property name="driverClassName" value="#{jdbc.driver}"/>
		<property name="username" value="#{jdbc.user}"/>
		<property name="password" value="#{jdbc.password}"/>
	</bean>	
	
	<!--开启注解扫描 -->
	<context:component-scan base-package="com.tarena"/>
	
	<!--开启MVC注解扫描 -->
	<mvc:annotation-driven/>
	
	<!--定义视图解析器ViewResolver -->
	<bean id="viewResolver"
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/WEB-INF/"/>
		<property name="suffix" value=".jsp"/>
	</bean>
	
</beans>

创建用户表,代码如下:

--用户表
create table admin_info(
	admin_id	number(8) primary key not null,
	admin_code 	varchar2(30) not null,
	password	varchar2(30) not null,
	name		varchar2(30) not null,
	telephone	varchar2(15),
	email		varchar2(50),
	enrolldate	date default sysdate not null
);

create sequence admin_seq start with 10000;

insert into admin_info values
(5000,'caocao','123','CaoCao','123456789','caocao@tarena.com.cn',sysdate);
commit;

步骤二:打开登录页

创建LoginController,代码如下:

package com.tarena.web;

import java.io.Serializable;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/login")
public class LoginController implements Serializable {

	@RequestMapping("/toLogin.do")
	public String toLogin() {
		return "main/login";
	}
	
}

在WebRoot下,导入项目的图片和样式文件,如下图:

图-10

在WEB-INF/main下,创建登录页面,代码如下:

<%@page pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "/www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="/www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title> -NetCTOSS</title>
<link type="text/css" rel="stylesheet" media="all" href="../styles/global.css" />
<link type="text/css" rel="stylesheet" media="all" href="../styles/global_color.css" />
</head>
<body class="index">
<div class="login_box">
<table>
<tr>
<td class="login_info">账号:</td>
<td colspan="2"><input name="adminCode" value="" type="text" class="width150" /></td>
<td class="login_error_info"><span class="required">30长度的字母、数字和下划线</span></td>
</tr>
<tr>
<td class="login_info">密码:</td>
<td colspan="2"><input name="password" value="" type="password" class="width150" /></td>
<td><span class="required">30长度的字母、数字和下划线</span></td>
</tr>
<tr>
<td class="login_info">验证码:</td>
<td class="width70"><input name="" type="text" class="width70" /></td>
<td><img src="../images/valicode.jpg" alt="验证码" title="点击更换" /></td>
<td><span class="required"></span></td>
</tr>
<tr>
<td></td>
<td class="login_button" colspan="2">
<a href="#"><img src="../images/login_btn.png" /></a>
</td>
<td><span class="required"></span></td>
</tr>
</table>
</div>
</body>
</html>

步骤三:测试打开登陆页

部署项目并启动Tomcat/localhost:8088/NETCTOSS1/login/toLogin.do,通过浏览器访问,浏览器显示效果如下图:

图-11

步骤四:提交登录验证

创建实体类Admin,代码如下:

package com.tarena.entity;

import java.io.Serializable;
import java.sql.Timestamp;

public class Admin implements Serializable {

	private Integer adminId;
	private String adminCode;
	private String password;
	private String name;
	private String telephone;
	private String email;
	private Timestamp enrolldate;

	public Integer getAdminId() {
		return adminId;
	}

	public void setAdminId(Integer adminId) {
		this.adminId = adminId;
	}

	public String getAdminCode() {
		return adminCode;
	}

	public void setAdminCode(String adminCode) {
		this.adminCode = adminCode;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getTelephone() {
		return telephone;
	}

	public void setTelephone(String telephone) {
		this.telephone = telephone;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public Timestamp getEnrolldate() {
		return enrolldate;
	}

	public void setEnrolldate(Timestamp enrolldate) {
		this.enrolldate = enrolldate;
	}

}

创建数据访问接口AdminDao,代码如下:

package com.tarena.dao;

import com.tarena.entity.Admin;

public interface AdminDao {
	
	Admin findByCode(String adminCode);

}

创建接口的实现类JdbcAdminDao,代码如下:

package com.tarena.dao;

import java.io.Serializable;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.annotation.Resource;
import javax.sql.DataSource;

import org.springframework.stereotype.Repository;

import com.tarena.entity.Admin;

@Repository
public class JdbcAdminDao implements AdminDao, Serializable {

	@Resource
	private DataSource ds;

	@Override
	public Admin findByCode(String adminCode) {
		if (adminCode == null)
			return null;
		
		Connection conn = null;
		try {
			conn = ds.getConnection();
			String sql = "select * from admin_info where admin_code=?";
			PreparedStatement ps = conn.prepareStatement(sql);
			ps.setString(1, adminCode);
			ResultSet rs = ps.executeQuery();
			if(rs.next()) {
				Admin admin = new Admin();
				admin.setAdminId(rs.getInt("admin_id"));
				admin.setAdminCode(rs.getString("admin_code"));
				admin.setPassword(rs.getString("password"));
				admin.setName(rs.getString("name"));
				admin.setTelephone(rs.getString("telephone"));
				admin.setEmail(rs.getString("email"));
				admin.setEnrolldate(rs.getTimestamp("enrolldate"));
				return admin;
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException("根据编码查询管理员失败", e);
		} finally {
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		
		return null;
	}

}

创建异常类AdminCodeException,代码如下:

package com.tarena.exception;

/**
 *	账号错误异常
 */
public class AdminCodeException extends RuntimeException {

	public AdminCodeException(String message) {
		super(message);
	}

}

创建异常类PasswordException,代码如下:

package com.tarena.exception;

/**
 *	密码错误异常
 */
public class PasswordException extends RuntimeException {

	public PasswordException(String message) {
		super(message);
	}

}

创建业务组件LoginService,代码如下:

package com.tarena.service;

import java.io.Serializable;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import com.tarena.dao.AdminDao;
import com.tarena.entity.Admin;
import com.tarena.exception.AdminCodeException;
import com.tarena.exception.PasswordException;

@Service
public class LoginService implements Serializable {

	@Resource
	private AdminDao adminDao;

	/**
	 * 校验管理员账号和密码
	 * @param adminCode 账号
	 * @param password 密码
	 * @return 验证通过时返回管理员对象
	 */
	public Admin checkAdminCodeAndPwd(
			String adminCode, String password)
			throws AdminCodeException, PasswordException {
		Admin admin = adminDao.findByCode(adminCode);
		if(admin == null) {
			throw new AdminCodeException("账号错误");
		} else if (!admin.getPassword().equals(password)) {
			throw new PasswordException("密码错误");
		} else {
			return admin;
		}
	}

}

在LoginController中增加登录验证的方法,代码如下:

package com.tarena.web;

import java.io.Serializable;
import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import com.tarena.entity.Admin;
import com.tarena.exception.AdminCodeException;
import com.tarena.exception.PasswordException;
import com.tarena.service.LoginService;

@Controller
@RequestMapping("/login")
public class LoginController implements Serializable {
	
	@Resource
	private LoginService loginService;

	@RequestMapping("/toLogin.do")
	public String toLogin() {
		return "main/login";
	}
	
	@RequestMapping("/toIndex.do")
	public String toIndex() {
		return "main/index";
	}
	
	@RequestMapping("/checkLogin.do")
	public String checkLogin(String adminCode, String password, 
			ModelMap model, HttpSession session) {
		try {
			Admin admin = 
				loginService.checkAdminCodeAndPwd(adminCode, password);
			session.setAttribute("admin", admin);
		} catch (AdminCodeException e) {
			model.addAttribute("message", e.getMessage());
			model.addAttribute("adminCode", adminCode);
			model.addAttribute("password", password);
			return "main/login";
		} catch (PasswordException e) {
			model.addAttribute("message", e.getMessage());
			model.addAttribute("adminCode", adminCode);
			model.addAttribute("password", password);
			return "main/login";
		}
		return "redirect:toIndex.do";
	}
	
}

修改login.jsp,设置表单,代码如下:

<%@page pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "/www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="/www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title> -NetCTOSS</title>
<link type="text/css" rel="stylesheet" media="all" href="../styles/global.css" />
<link type="text/css" rel="stylesheet" media="all" href="../styles/global_color.css" />
</head>
<body class="index">
<div class="login_box">
	<form action="checkLogin.do" method="post">
<table>
<tr>
<td class="login_info">账号:</td>
<td colspan="2"><input name="adminCode" value="${adminCode}" type="text" class="width150" /></td>
<td class="login_error_info"><span class="required">30长度的字母、数字和下划线</span></td>
</tr>
<tr>
<td class="login_info">密码:</td>
<td colspan="2"><input name="password" value="${password}" type="password" class="width150" /></td>
<td><span class="required">30长度的字母、数字和下划线</span></td>
</tr>
<tr>
<td class="login_info">验证码:</td>
<td class="width70"><input name="" type="text" class="width70" /></td>
<td><img src="../images/valicode.jpg" alt="验证码" title="点击更换" /></td>
<td><span class="required"></span></td>
</tr>
<tr>
<td></td>
<td class="login_button" colspan="2">
<a href="javascript:document.forms[0].submit();"><img src="../images/login_btn.png" /></a>
</td>
<td><span class="required">${message}</span></td>
</tr>
</table>
</form>
</div>
</body>
</html>
在WEB-INF/main下,创建NETCTOSS首页index.jsp,代码如下:
<%@page pageEncoding="utf-8"%>
<%@taglib uri="/java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "/www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="/www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title> -NetCTOSS</title>
<link type="text/css" rel="stylesheet" media="all" href="../styles/global.css" />
<link type="text/css" rel="stylesheet" media="all" href="../styles/global_color.css" />
</head>
<body class="index">
<!--导航区域开始-->
<div id="index_navi">
<ul id="menu">
<li><a href="index.html" class="index_on"></a></li>
	<li><a href="/NETCTOSS/" class="role_off"></a></li>
	<li><a href="admin/admin_list.html" class="admin_off"></a></li>
	<li><a href="fee/fee_list.html" class="fee_off"></a></li>
	<li><a href="account/account_list.html" class="account_off"></a></li>
	<li><a href="service/service_list.html" class="service_off"></a></li>
	<li><a href="bill/bill_list.html" class="bill_off"></a></li>
	<li><a href="report/report_list.html" class="report_off"></a></li>
<li><a href="user/user_info.html" class="information_off"></a></li>
<li><a href="user/user_modi_pwd.html" class="password_off"></a></li>
</ul>
</div>
</body>
</html>

步骤五:测试登录验证

打开登陆页面,填写错误的账号或密码,点击登录按钮,效果如下图:

图-12

改为正确的账号和密码,点击登录按钮,效果如下图:

图-13

2.4 完整代码

建表脚本完整代码如下:

--用户表
create table admin_info(
	admin_id	number(8) primary key not null,
	admin_code 	varchar2(30) not null,
	password	varchar2(30) not null,
	name		varchar2(30) not null,
	telephone	varchar2(15),
	email		varchar2(50),
	enrolldate	date default sysdate not null
);

create sequence admin_seq start with 10000;

insert into admin_info values
(5000,'caocao','123','CaoCao','123456789','caocao@tarena.com.cn',sysdate);
commit;

web.xml完整代码如下:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
	xmlns="/java.sun.com/xml/ns/javaee" 
	xmlns:xsi="/www.w3.org/2001/XMLSchema-instance" 
	xsi:schemaLocation="/java.sun.com/xml/ns/javaee 
	/java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>

	<servlet>
		<servlet-name>spring</servlet-name>
		<servlet-class>
			org.springframework.web.servlet.DispatcherServlet
		</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>classpath:applicationContext.xml</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
		<servlet-name>spring</servlet-name>
		<url-pattern>*.do</url-pattern>
	</servlet-mapping>

</web-app>

jdbc.properties完整代码如下:

url=jdbc:oracle:thin:@localhost:1521:xe
driver=oracle.jdbc.OracleDriver
user=lhh
password=123456

applicationContext.xml完整代码如下:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="/www.springframework.org/schema/beans" 
	xmlns:xsi="/www.w3.org/2001/XMLSchema-instance"
	xmlns:context="/www.springframework.org/schema/context" 
	xmlns:jdbc="/www.springframework.org/schema/jdbc"  
	xmlns:jee="/www.springframework.org/schema/jee" 
	xmlns:tx="/www.springframework.org/schema/tx"
	xmlns:aop="/www.springframework.org/schema/aop" 
	xmlns:mvc="/www.springframework.org/schema/mvc"
	xmlns:util="/www.springframework.org/schema/util"
	xmlns:jpa="/www.springframework.org/schema/data/jpa"
	xsi:schemaLocation="
		/www.springframework.org/schema/beans /www.springframework.org/schema/beans/spring-beans-3.2.xsd
		/www.springframework.org/schema/context /www.springframework.org/schema/context/spring-context-3.2.xsd
		/www.springframework.org/schema/jdbc /www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd
		/www.springframework.org/schema/jee /www.springframework.org/schema/jee/spring-jee-3.2.xsd
		/www.springframework.org/schema/tx /www.springframework.org/schema/tx/spring-tx-3.2.xsd
		/www.springframework.org/schema/data/jpa /www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd
		/www.springframework.org/schema/aop /www.springframework.org/schema/aop/spring-aop-3.2.xsd
		/www.springframework.org/schema/mvc /www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
		/www.springframework.org/schema/util /www.springframework.org/schema/util/spring-util-3.2.xsd">
	
	<util:properties id="jdbc" location="classpath:jdbc.properties"/>
	
	<!--定义数据源 -->
	<bean id="ds" 
		class="org.apache.commons.dbcp.BasicDataSource"
		destroy-method="close">
		<property name="url" value="#{jdbc.url}"/>
		<property name="driverClassName" value="#{jdbc.driver}"/>
		<property name="username" value="#{jdbc.user}"/>
		<property name="password" value="#{jdbc.password}"/>
	</bean>	
	
	<!--开启注解扫描 -->
	<context:component-scan base-package="com.tarena"/>
	
	<!--开启MVC注解扫描 -->
	<mvc:annotation-driven/>
	
	<!--定义视图解析器ViewResolver -->
	<bean id="viewResolver"
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/WEB-INF/"/>
		<property name="suffix" value=".jsp"/>
	</bean>
	
</beans>

Admin类完整代码如下:

package com.tarena.entity;

import java.io.Serializable;
import java.sql.Timestamp;

public class Admin implements Serializable {

	private Integer adminId;
	private String adminCode;
	private String password;
	private String name;
	private String telephone;
	private String email;
	private Timestamp enrolldate;

	public Integer getAdminId() {
		return adminId;
	}

	public void setAdminId(Integer adminId) {
		this.adminId = adminId;
	}

	public String getAdminCode() {
		return adminCode;
	}

	public void setAdminCode(String adminCode) {
		this.adminCode = adminCode;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getTelephone() {
		return telephone;
	}

	public void setTelephone(String telephone) {
		this.telephone = telephone;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public Timestamp getEnrolldate() {
		return enrolldate;
	}

	public void setEnrolldate(Timestamp enrolldate) {
		this.enrolldate = enrolldate;
	}

}

AdminDao完整代码如下:

package com.tarena.dao;

import com.tarena.entity.Admin;

public interface AdminDao {
	
	Admin findByCode(String adminCode);

}

JdbcAdminDao完整代码如下:

package com.tarena.dao;

import java.io.Serializable;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.annotation.Resource;
import javax.sql.DataSource;

import org.springframework.stereotype.Repository;

import com.tarena.entity.Admin;

@Repository
public class JdbcAdminDao implements AdminDao, Serializable {

	@Resource
	private DataSource ds;

	@Override
	public Admin findByCode(String adminCode) {
		if (adminCode == null)
			return null;
		
		Connection conn = null;
		try {
			conn = ds.getConnection();
			String sql = "select * from admin_info where admin_code=?";
			PreparedStatement ps = conn.prepareStatement(sql);
			ps.setString(1, adminCode);
			ResultSet rs = ps.executeQuery();
			if(rs.next()) {
				Admin admin = new Admin();
				admin.setAdminId(rs.getInt("admin_id"));
				admin.setAdminCode(rs.getString("admin_code"));
				admin.setPassword(rs.getString("password"));
				admin.setName(rs.getString("name"));
				admin.setTelephone(rs.getString("telephone"));
				admin.setEmail(rs.getString("email"));
				admin.setEnrolldate(rs.getTimestamp("enrolldate"));
				return admin;
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException("根据编码查询管理员失败", e);
		} finally {
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		
		return null;
	}

}

AdminCodeException完整代码如下:

package com.tarena.exception;

/**
 *	账号错误异常
 */
public class AdminCodeException extends RuntimeException {

	public AdminCodeException(String message) {
		super(message);
	}

}

PasswordException完整代码如下:

package com.tarena.exception;

/**
 *	密码错误异常
 */
public class PasswordException extends RuntimeException {

	public PasswordException(String message) {
		super(message);
	}

}

LoginService完整代码如下:

package com.tarena.service;

import java.io.Serializable;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import com.tarena.dao.AdminDao;
import com.tarena.entity.Admin;
import com.tarena.exception.AdminCodeException;
import com.tarena.exception.PasswordException;

@Service
public class LoginService implements Serializable {

	@Resource
	private AdminDao adminDao;

	/**
	 * 校验管理员账号和密码
	 * @param adminCode 账号
	 * @param password 密码
	 * @return 验证通过时返回管理员对象
	 */
	public Admin checkAdminCodeAndPwd(
			String adminCode, String password)
			throws AdminCodeException, PasswordException {
		Admin admin = adminDao.findByCode(adminCode);
		if(admin == null) {
			throw new AdminCodeException("账号错误");
		} else if (!admin.getPassword().equals(password)) {
			throw new PasswordException("密码错误");
		} else {
			return admin;
		}
	}

}

LoginController完整代码如下:

package com.tarena.web;

import java.io.Serializable;
import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import com.tarena.entity.Admin;
import com.tarena.exception.AdminCodeException;
import com.tarena.exception.PasswordException;
import com.tarena.service.LoginService;

@Controller
@RequestMapping("/login")
public class LoginController implements Serializable {
	
	@Resource
	private LoginService loginService;

	@RequestMapping("/toLogin.do")
	public String toLogin() {
		return "main/login";
	}
	
	@RequestMapping("/toIndex.do")
	public String toIndex() {
		return "main/index";
	}
	
	@RequestMapping("/checkLogin.do")
	public String checkLogin(String adminCode, String password, 
			ModelMap model, HttpSession session) {
		try {
			Admin admin = 
				loginService.checkAdminCodeAndPwd(adminCode, password);
			session.setAttribute("admin", admin);
		} catch (AdminCodeException e) {
			model.addAttribute("message", e.getMessage());
			model.addAttribute("adminCode", adminCode);
			model.addAttribute("password", password);
			return "main/login";
		} catch (PasswordException e) {
			model.addAttribute("message", e.getMessage());
			model.addAttribute("adminCode", adminCode);
			model.addAttribute("password", password);
			return "main/login";
		}
		return "redirect:toIndex.do";
	}
	
}

login.jsp完整代码如下:

<%@page pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "/www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="/www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title> -NetCTOSS</title>
<link type="text/css" rel="stylesheet" media="all" href="../styles/global.css" />
<link type="text/css" rel="stylesheet" media="all" href="../styles/global_color.css" />
</head>
<body class="index">
<div class="login_box">
	<form action="checkLogin.do" method="post">
<table>
<tr>
<td class="login_info">账号:</td>
<td colspan="2"><input name="adminCode" value="${adminCode}" type="text" class="width150" /></td>
<td class="login_error_info"><span class="required">30长度的字母、数字和下划线</span></td>
</tr>
<tr>
<td class="login_info">密码:</td>
<td colspan="2"><input name="password" value="${password}" type="password" class="width150" /></td>
<td><span class="required">30长度的字母、数字和下划线</span></td>
</tr>
<tr>
<td class="login_info">验证码:</td>
<td class="width70"><input name="" type="text" class="width70" /></td>
<td><img src="../images/valicode.jpg" alt="验证码" title="点击更换" /></td>
<td><span class="required"></span></td>
</tr>
<tr>
<td></td>
<td class="login_button" colspan="2">
<a href="javascript:document.forms[0].submit();"><img src="../images/login_btn.png" /></a>
</td>
<td><span class="required">${message}</span></td>
</tr>
</table>
</form>
</div>
</body>
</html>

index.jsp完整代码如下:

<%@page pageEncoding="utf-8"%>
<%@taglib uri="/java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "/www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="/www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title> -NetCTOSS</title>
<link type="text/css" rel="stylesheet" media="all" href="../styles/global.css" />
<link type="text/css" rel="stylesheet" media="all" href="../styles/global_color.css" />
</head>
<body class="index">
<!--导航区域开始-->
<div id="index_navi">
<ul id="menu">
<li><a href="index.html" class="index_on"></a></li>
	<li><a href="/NETCTOSS/" class="role_off"></a></li>
	<li><a href="admin/admin_list.html" class="admin_off"></a></li>
	<li><a href="fee/fee_list.html" class="fee_off"></a></li>
	<li><a href="account/account_list.html" class="account_off"></a></li>
	<li><a href="service/service_list.html" class="service_off"></a></li>
	<li><a href="bill/bill_list.html" class="bill_off"></a></li>
	<li><a href="report/report_list.html" class="report_off"></a></li>
<li><a href="user/user_info.html" class="information_off"></a></li>
<li><a href="user/user_modi_pwd.html" class="password_off"></a></li>
</ul>
</div>
</body>
</html>