- 准备所需的jar包
- 准备数据库资源
- 新建一个项目,并加入准备的jar包
程序清单
/fkbookapp/src/db.properties
dataSource.driverClass=com.mysql.jdbc.Driver
dataSource.jdbcUrl=jdbc:mysql://127.0.0.1:3306/mybatis
dataSource.user=root
dataSource.password=root
dataSource.maxPoolSize=20
dataSource.maxIdleTime = 1000
dataSource.minPoolSize=6
dataSource.initialPoolSize=5
/fkbookapp/WebContent/WEB-INF/applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mybatis="http://mybatis.org/schema/mybatis-spring"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.1.xsd
http://mybatis.org/schema/mybatis-spring
http://mybatis.org/schema/mybatis-spring.xsd ">
<!-- mybatis:scan会将org.fkit.mapper包里的所有接口当作mapper配置,之后可以自动引入mapper类-->
<mybatis:scan base-package="org.fkit.mapper"/>
<!-- 扫描org.fkit包下面的java文件,有Spring的相关注解的类,则把这些类注册为Spring的bean -->
<context:component-scan base-package="org.fkit"/>
<!-- 使用PropertyOverrideConfigurer后处理器加载数据源参数 -->
<context:property-override location="classpath:db.properties"/>
<!-- 配置c3p0数据源 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"/>
<!-- 配置SqlSessionFactory,org.mybatis.spring.SqlSessionFactoryBean是Mybatis社区开发用于整合Spring的bean -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"
p:dataSource-ref="dataSource"/>
<!-- JDBC事务管理器 -->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager"
p:dataSource-ref="dataSource"/>
<!-- 启用支持annotation注解方式事务管理 -->
<tx:annotation-driven transaction-manager="transactionManager"/>
</beans>
/fkbookapp/WebContent/WEB-INF/springmvc-config.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:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.2.xsd">
<!-- 自动扫描该包,SpringMVC会将包下用了@controller注解的类注册为Spring的controller -->
<context:component-scan base-package="org.fkit.controller"/>
<!-- 设置默认配置方案 -->
<mvc:annotation-driven/>
<!-- 使用默认的Servlet来响应静态文件 -->
<mvc:default-servlet-handler/>
<!-- 视图解析器 -->
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- 前缀 -->
<property name="prefix">
<value>/WEB-INF/content/</value>
</property>
<!-- 后缀 -->
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
</beans>
/fkbookapp/WebContent/WEB-INF/web.xml
<?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">
<!-- 配置spring核心监听器,默认会以 /WEB-INF/applicationContext.xml作为配置文件 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- contextConfigLocation参数用来指定Spring的配置文件 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext*.xml</param-value>
</context-param>
<!-- 定义Spring MVC的前端控制器 -->
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/springmvc-config.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<!-- 让Spring MVC的前端控制器拦截所有请求 -->
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- 编码过滤器 -->
<filter>
<filter-name>characterEncodingFilter</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>characterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
持久层功能实现
/fkbookapp/src/org/fkit/domain/User.java
package org.fkit.domain;
import java.io.Serializable;
/**
* CREATE TABLE tb_user(
id INT PRIMARY KEY AUTO_INCREMENT, #id
loginname VARCHAR(50) UNIQUE, #登录名 邮箱
PASSWORD VARCHAR(18), #密码
username VARCHAR(18), #用户名
phone VARCHAR(18), #电话
address VARCHAR(255) #地址
);
* */
public class User implements Serializable{
private Integer id; // id
private String loginname; // 登录名
private String password; // 密码
private String username; // 用户名
private String phone; // 电话
private String address; // 地址
public User() {
super();
// TODO Auto-generated constructor stub
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getLoginname() {
return loginname;
}
public void setLoginname(String loginname) {
this.loginname = loginname;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return "User [id=" + id + ", loginname=" + loginname + ", password="
+ password + ", username=" + username + ", phone=" + phone
+ ", address=" + address + "]";
}
}
/fkbookapp/src/org/fkit/domain/Book.java
package org.fkit.domain;
import java.io.Serializable;
import java.util.Date;
/**
* CREATE TABLE tb_book (
id INT (11) PRIMARY KEY AUTO_INCREMENT,
name VARCHAR (54),
author VARCHAR (54),
publicationdate DATE ,
publication VARCHAR (150),
price DOUBLE ,
image VARCHAR (54),
remark VARCHAR (600)
);
* */
public class Book implements Serializable{
private Integer id; // id
private String name; // 书名
private String author; // 作者
private String publication; // 出版社
private Date publicationdate; // 出版日期
private Double price; // 价格
private String image; // 封面图片
private String remark; // 详细描述
public Book() {
super();
// TODO Auto-generated constructor stub
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getPublication() {
return publication;
}
public void setPublication(String publication) {
this.publication = publication;
}
public Date getPublicationdate() {
return publicationdate;
}
public void setPublicationdate(Date publicationdate) {
this.publicationdate = publicationdate;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
@Override
public String toString() {
return "Book [id=" + id + ", name=" + name + ", author=" + author
+ ", publication=" + publication + ", publicationdate="
+ publicationdate + ", price=" + price + ", image=" + image
+ ", remark=" + remark + "]";
}
}
/fkbookapp/src/org/fkit/mapper/UserMapper.java
package org.fkit.mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.fkit.domain.User;
/**
* UserMapper接口
* */
public interface UserMapper {
/**
* 根据登录名和密码查询用户
* @param String loginname
* @param String password
* @return 找到返回User对象,没有找到返回null
* */
@Select("select * from tb_user where loginname = #{loginname} and password = #{password}")
User findWithLoginnameAndPassword(@Param("loginname")String loginname,
@Param("password") String password);
}
/fkbookapp/src/org/fkit/mapper/BookMapper.java
package org.fkit.mapper;
import java.util.List;
import org.apache.ibatis.annotations.Select;
import org.fkit.domain.Book;
/**
* BookMapper接口
* */
public interface BookMapper {
/**
* 查询所有图书
* @return 图书对象集合
* */
@Select(" select * from tb_book ")
List<Book> findAll();
}
持久层包括和数据库表映射的User.java和Book两个JavaBean对象,并使用了MyBatis的注解映射了对应的SQL语句。
服务层功能实现
/fkbookapp/src/org/fkit/service/UserService.java
package org.fkit.service;
import org.fkit.domain.User;
/**
* User服务层接口
* */
public interface UserService {
/**
* 判断用户登录
* @param String loginname
* @param String password
* @return 找到返回User对象,没有找到返回null
* */
User login(String loginname,String password);
}
/fkbookapp/src/org/fkit/service/impl/UserServiceImpl.java
package org.fkit.service.impl;
import org.fkit.domain.User;
import org.fkit.mapper.UserMapper;
import org.fkit.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
/**
* User服务层接口实现类
* @Service("userService")用于将当前类注释为一个Spring的bean,名为userService
* */
@Transactional(propagation=Propagation.REQUIRED,isolation=Isolation.DEFAULT)
@Service("userService")
public class UserServiceImpl implements UserService {
/**
* 自动注入UserMapper
* */
@Autowired
private UserMapper userMapper;
/**
* UserService接口login方法实现
* @see { UserService }
* */
@Transactional(readOnly=true)
@Override
public User login(String loginname, String password) {
return userMapper.findWithLoginnameAndPassword(loginname, password);
}
}
/fkbookapp/src/org/fkit/service/BookService.java
package org.fkit.service;
import java.util.List;
import org.fkit.domain.Book;
/**
* Book服务层接口
* */
public interface BookService {
/**
* 查找所有图书
* @return Book对象集合
* */
List<Book> getAll();
}
/fkbookapp/src/org/fkit/service/impl/BookServiceImpl.java
package org.fkit.service.impl;
import java.util.List;
import org.fkit.domain.Book;
import org.fkit.mapper.BookMapper;
import org.fkit.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
/**
* Book服务层接口实现类
* @Service("bookService")用于将当前类注释为一个Spring的bean,名为bookService
* */
@Transactional(propagation=Propagation.REQUIRED,isolation=Isolation.DEFAULT)
@Service("bookService")
public class BookServiceImpl implements BookService {
/**
* 自动注入BookMapper
* */
@Autowired
private BookMapper bookMapper;
/**
* BookService接口getAll方法实现
* @see { BookService }
* */
@Transactional(readOnly=true)
@Override
public List<Book> getAll() {
return bookMapper.findAll();
}
}
服务层使用了Spring 的@Autowired注解自动注入持久层的Mapper对象,并且使用了@Service注解将类注解成为Spring 的bean
控制层功能实现
/fkbookapp/src/org/fkit/controller/FormController.java
package org.fkit.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* 动态页面跳转控制器
* */
@Controller
public class FormController{
@RequestMapping(value="/{formName}")
public String loginForm(@PathVariable String formName){
// 动态跳转页面
return formName;
}
}
/fkbookapp/src/org/fkit/controller/UserController.java
package org.fkit.controller;
import javax.servlet.http.HttpSession;
import org.fkit.domain.User;
import org.fkit.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;
/**
* 处理用户请求控制器
* */
@Controller
public class UserController {
/**
* 自动注入UserService
* */
@Autowired
@Qualifier("userService")
private UserService userService;
/**
* 处理/login请求
* */
@RequestMapping(value="/login")
public ModelAndView login(
String loginname,String password,
ModelAndView mv,
HttpSession session){
// 根据登录名和密码查找用户,判断用户登录
User user = userService.login(loginname, password);
if(user != null){
// 登录成功,将user对象设置到HttpSession作用范围域
session.setAttribute("user", user);
// 转发到main请求
mv.setView(new RedirectView("/fkbookapp/main"));
}else{
// 登录失败,设置失败提示信息,并跳转到登录页面
mv.addObject("message", "登录名或密码错误,请重新输入!");
mv.setViewName("loginForm");
}
return mv;
}
}
/fkbookapp/src/org/fkit/controller/BookController.java
package org.fkit.controller;
import java.util.List;
import org.fkit.domain.Book;
import org.fkit.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* 处理图书请求控制器
* */
@Controller
public class BookController {
/**
* 自动注入BookService
* */
@Autowired
@Qualifier("bookService")
private BookService bookService;
/**
* 处理/main请求
* */
@RequestMapping(value="/main")
public String main(Model model){
// 获得所有图书集合
List<Book> book_list = bookService.getAll();
// 将图书集合添加到model当中
model.addAttribute("book_list", book_list);
// 跳转到main页面
return "main";
}
}
控制层使用了Spring的@Autowired注解自动注入了服务层的Sercice对象,@Qualifier注解用于指明需要注入的具体类型,并且使用@Controller注解将类注解成为Spring MVC的Controller
jsp页面
/fkbookapp/WebContent/WEB-INF/content/loginForm.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>登录页面</title>
</head>
<body>
<h3>登录页面</h3>
<form action="login" method="post">
<font color="red">${requestScope.message }</font>
<table>
<tr>
<td><label>登录名: </label></td>
<td><input type="text" id="loginname" name="loginname" ></td>
</tr>
<tr>
<td><label>密码: </label></td>
<td><input type="password" id="password" name="password" ></td>
</tr>
<tr>
<td><input type="submit" value="登录"></td>
</tr>
</table>
</form>
</body>
</html>
/fkbookapp/WebContent/WEB-INF/content/main.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>首页</title>
<style type="text/css">
table{border-collapse:collapse;border-spacing:0;border-left:1px solid #888;border-top:1px solid #888;background:#efefef;}
th,td{border-right:1px solid #888;border-bottom:1px solid #888;padding:5px 15px;}
th{font-weight:bold;background:#ccc;}
</style>
</head>
<body>
欢迎[${sessionScope.user.username }]访问
<br>
<table border="1">
<tr>
<th>封面</th><th>书名</th><th>作者</th><th>价格</th>
</tr>
<c:forEach items="${requestScope.book_list }" var="book">
<tr>
<td><img src="images/${book.image }" height="60"></td>
<td>${book.name }</td>
<td>${book.author }</td>
<td>${book.price }</td>
</tr>
</c:forEach>
</table>
</body>
</html>
loginForm是一个登陆页面,可以在此输入登录名和密码进行登陆,登陆完成后main.jsp显示从数据列表信息
测试:
http://localhost:8090/fkbookapp/loginForm
- 邮箱:ithelei@sina.cn
- 技术讨论群:687856230
- GoodLuck