ssm搭建的圖書管理小demo(login、CURD)

學完ssm後就可以練手的小項目,圖書管理有login、CURD這四個功能。第一次寫完整的項目,儘量寫的很詳細,自己也從新梳理一遍

搭建環境:maven+eclipse+ssm+mysql

項目結構圖:

pom.xml文件內容如下

 1 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 2   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
 3   <modelVersion>4.0.0</modelVersion>
 4   <groupId>com.li</groupId>
 5   <artifactId>bookstore</artifactId>
 6   <packaging>war</packaging>
 7   <version>0.0.1-SNAPSHOT</version>
 8   <name>bookstore Maven Webapp</name>
 9   <url>http://maven.apache.org</url>
10   
11   <properties>
12       <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
13       <spring.version>4.3.0.RELEASE</spring.version>
14   </properties>
15   
16   <dependencies>
17         <!--Spring框架核心庫 -->
18         <dependency>
19             <groupId>org.springframework</groupId>
20             <artifactId>spring-context</artifactId>
21             <version>${spring.version}</version>
22         </dependency>
23         <!-- aspectJ AOP 織入器 -->
24         <dependency>
25             <groupId>org.aspectj</groupId>
26             <artifactId>aspectjweaver</artifactId>
27             <version>1.8.9</version>
28         </dependency>
29         <!-- Spring Web -->
30         <dependency>
31             <groupId>org.springframework</groupId>
32             <artifactId>spring-web</artifactId>
33             <version>${spring.version}</version>
34         </dependency>
35         <dependency>
36             <groupId>org.springframework</groupId>
37             <artifactId>spring-webmvc</artifactId>
38             <version>${spring.version}</version>
39         </dependency>
40         <!--mybatis-spring適配器 -->
41         <dependency>
42             <groupId>org.mybatis</groupId>
43             <artifactId>mybatis-spring</artifactId>
44             <version>1.3.0</version>
45         </dependency>
46         <!--Spring java數據庫訪問包,在本例中主要用於提供數據源 -->
47         <dependency>
48             <groupId>org.springframework</groupId>
49             <artifactId>spring-jdbc</artifactId>
50             <version>${spring.version}</version>
51         </dependency>
52         <!--mysql數據庫驅動 -->
53         <dependency>
54             <groupId>mysql</groupId>
55             <artifactId>mysql-connector-java</artifactId>
56             <version>5.1.38</version>
57         </dependency>
58         <!--log4j日誌包 -->
59         <dependency>
60             <groupId>org.apache.logging.log4j</groupId>
61             <artifactId>log4j-core</artifactId>
62             <version>2.6.1</version>
63         </dependency>
64         <!-- mybatis ORM框架 -->
65         <dependency>
66             <groupId>org.mybatis</groupId>
67             <artifactId>mybatis</artifactId>
68             <version>3.4.1</version>
69         </dependency>
70         <!-- JUnit單元測試工具 -->
71         <dependency>
72             <groupId>junit</groupId>
73             <artifactId>junit</artifactId>
74             <version>4.10</version>
75         </dependency>
76         <!--c3p0 連接池 -->
77         <dependency>
78             <groupId>c3p0</groupId>
79             <artifactId>c3p0</artifactId>
80             <version>0.9.1.2</version>
81         </dependency>
82         <!-- jstl -->
83         <dependency>
84             <groupId>javax.servlet</groupId>
85             <artifactId>jstl</artifactId>
86             <version>1.2</version>
87         </dependency>
88     </dependencies>
89 </project>
View Code

數據庫內創建兩個表,一個用於登錄,一個用於對應book,sql腳本如下

 1 USE `my_db`;
 2 
 3 /*Table structure for table `books` */
 4 
 5 DROP TABLE IF EXISTS `books`;
 6 
 7 CREATE TABLE `books` (
 8   `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '編號',
 9   `title` varchar(100) NOT NULL COMMENT '書名',
10   `price` decimal(10,2) DEFAULT NULL COMMENT '價格',
11   `publishDate` timestamp NULL DEFAULT CURRENT_TIMESTAMP COMMENT '出版日期',
12   PRIMARY KEY (`id`),
13   UNIQUE KEY `title` (`title`)
14 ) ENGINE=InnoDB AUTO_INCREMENT=15 DEFAULT CHARSET=utf8;
15 
16 /*Data for the table `books` */
17 
18 insert  into `books`(`id`,`title`,`price`,`publishDate`) values (14,'HeadFirst Java','56.00','1990-12-12 00:00:00');
19 
20 /*Table structure for table `myuser` */
21 
22 DROP TABLE IF EXISTS `myuser`;
23 
24 CREATE TABLE `myuser` (
25   `id` int(11) NOT NULL,
26   `username` varchar(20) DEFAULT NULL,
27   `age` int(11) DEFAULT NULL,
28   `password` varchar(20) DEFAULT NULL,
29   PRIMARY KEY (`id`)
30 ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
31 
32 /*Data for the table `myuser` */
33 
34 insert  into `myuser`(`id`,`username`,`age`,`password`) values (1,'aaa',20,'123'),(2,'bbb',23,'234'),(3,'ccc',12,'234'),(5,'poo',23,'876');
View Code

然後創建與數據表對應的類,User.java 、Books.java

 1 package com.pojo;
 2 
 3 import java.text.ParseException;
 4 import java.text.SimpleDateFormat;
 5 import java.util.Date;
 6 
 7 public class Books {
 8 
 9     private int id;
10     private String title;
11     private double price;
12     private Date publishDate;
13     
14     public Books() {
15         super();
16     }
17     
18     public Books(int id, String title, double price, Date publishDate) {
19         super();
20         this.id = id;
21         this.title = title;
22         this.price = price;
23         this.publishDate = publishDate;
24     }
25     @Override
26     public String toString() {
27         return "Books [id=" + id + ", title=" + title + ", price=" + price + ", publishDate=" + publishDate + "]";
28     }
29     public int getId() {
30         return id;
31     }
32     public void setId(int id) {
33         this.id = id;
34     }
35     public String getTitle() {
36         return title;
37     }
38     public void setTitle(String title) {
39         this.title = title;
40     }
41     public double getPrice() {
42         return price;
43     }
44     public void setPrice(double price) {
45         this.price = price;
46     }
47     public Date getPublishDate() {
48         return publishDate;
49     }
50     
51     public void setPublishDate(String str) {
52         SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
53         Date publishDate;
54         try {
55             publishDate = sdf.parse(str);
56             this.publishDate = publishDate;
57         } catch (ParseException e) {
58             e.printStackTrace();
59         }
60     }
61     
62 }
View Code
 1 package com.pojo;
 2 
 3 public class User {
 4 
 5     private int id;
 6     private String username;
 7     private String password;
 8     private int age;
 9     public int getId() {
10         return id;
11     }
12     public void setId(int id) {
13         this.id = id;
14     }
15     public String getUsername() {
16         return username;
17     }
18     public void setUsername(String username) {
19         this.username = username;
20     }
21     public String getPassword() {
22         return password;
23     }
24     public void setPassword(String password) {
25         this.password = password;
26     }
27     public int getAge() {
28         return age;
29     }
30     public void setAge(int age) {
31         this.age = age;
32     }
33     @Override
34     public String toString() {
35         return "User [id=" + id + ", username=" + username + ", password=" + password + ", age=" + age + "]";
36     }
37     
38     
39     
40 }
View Code

根據mybatis的用法需要創建對應的接口,調用數據庫來實現相對應的功能。UserDao.java、BooksDao.java

 1 package com.dao;
 2 
 3 import java.util.List;
 4 
 5 import com.pojo.Books;
 6 
 7 public interface BooksDao {
 8 
 9     public Books getBooksById(int id);
10     
11     public int updateBooks(Books book);
12     
13     public int addBooks(Books book);
14     
15     public int deleteBooksById(int id);
16     
17     public List<Books> getBooksAll();
18         
19     
20 }
View Code
1 package com.dao;
2 
3 import com.pojo.User;
4 
5 public interface UserDao {
6 
7     public User getUser(String username);
8     
9 }
View Code

然後創建與其對應的mapper文件,每個mapper文件的命名空間需要對應自己的接口類。這樣mybatis就會調用數據庫來創建相應的對象賦給接口類。BooksMapper.xml、UserMapper.xml。

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" 
 3             "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
 4             
 5 <!--命名空間應該是對應接口的包名+接口名 -->
 6 <mapper namespace="com.dao.UserDao">
 7 
 8     <select id="getUser" parameterType="string" resultType="User">
 9         select * from myuser where username=#{username}
10     </select>
11 
12 </mapper>
View Code
 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" 
 3             "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
 4             
 5 <!--命名空間應該是對應接口的包名+接口名 -->
 6 <mapper namespace="com.dao.BooksDao">
 7 
 8     <insert id="addBooks">
 9         insert into books (title,price,publishDate) values(#{title},#{price},#{publishDate})
10     </insert>
11 
12     <update id="updateBooks">
13         update books set title=#{title},price=#{price},publishDate=#{publishDate} where id=#{id}
14     </update>
15 
16     <delete id="deleteBooksById">
17         delete from books where id=#{id}
18     </delete>
19 
20     <select id="getBooksById" parameterType="int" resultType="Books">
21         select * from books where id=#{id}
22     </select>
23 
24     <select id="getBooksAll" resultType="Books">
25         select * from books
26     </select>
27 
28 </mapper>
View Code

接着創建service層,也是分別創建UserService.java、BooksService.java。

 1 package com.service;
 2 
 3 import java.util.List;
 4 
 5 import javax.annotation.Resource;
 6 
 7 import org.springframework.stereotype.Service;
 8 
 9 import com.dao.BooksDao;
10 import com.pojo.Books;
11 
12 @Service
13 public class BooksService {
14 
15     @Resource
16     private BooksDao booksDao;
17     
18     public int deleteBooksById(int id) {
19         return booksDao.deleteBooksById(id);
20     }
21     
22     public int addBooks(Books book) {
23         return booksDao.addBooks(book);
24     }
25     
26     public int updateBooks(Books book) {
27         return booksDao.updateBooks(book);
28     }
29     
30     public Books getBooksById(int id) {
31         Books books = booksDao.getBooksById(id);
32         return books;
33     }
34     
35     public List<Books> getBooksAll(){
36         List<Books> list = booksDao.getBooksAll();
37         return list;
38     }
39     
40 }
View Code
 1 package com.service;
 2 
 3 import javax.annotation.Resource;
 4 
 5 import org.springframework.stereotype.Service;
 6 
 7 import com.dao.UserDao;
 8 import com.pojo.User;
 9 
10 @Service
11 public class UserService {
12 
13     @Resource
14     private UserDao userDao;
15     
16     public User getUser(String username) {
17         
18         User user = userDao.getUser(username);
19         return user;
20         
21     }
22     
23 }
View Code

添加spring-mybatis整合的文件,文件名還是叫applicationContext.xml

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
 4     xmlns:p="http://www.springframework.org/schema/p"
 5     xmlns:aop="http://www.springframework.org/schema/aop" 
 6     xmlns:context="http://www.springframework.org/schema/context"
 7     xmlns:tx="http://www.springframework.org/schema/tx"
 8     xsi:schemaLocation="http://www.springframework.org/schema/beans
 9         http://www.springframework.org/schema/beans/spring-beans.xsd
10         http://www.springframework.org/schema/context
11         http://www.springframework.org/schema/context/spring-context-4.3.xsd
12         http://www.springframework.org/schema/aop
13         http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
14         http://www.springframework.org/schema/tx
15         http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">
16 
17     <!--1 引入屬性文件,在配置中佔位使用 -->
18     <context:property-placeholder location="classpath*:db.properties" />
19 
20     <!--2 配置C3P0數據源 -->
21     <bean id="datasource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
22         <!--驅動類名 -->
23         <property name="driverClass" value="${jdbc.driver}" />
24         <!-- url -->
25         <property name="jdbcUrl" value="${jdbc.url}" />
26         <!-- 用戶名 -->
27         <property name="user" value="${jdbc.uid}" />
28         <!-- 密碼 -->
29         <property name="password" value="${jdbc.pwd}" />
30         
31         <!-- 當連接池中的連接耗盡的時候c3p0一次同時獲取的連接數  -->
32         <property name="acquireIncrement" value="5"></property>
33         <!-- 初始連接池大小 -->
34         <property name="initialPoolSize" value="10"></property>
35         <!-- 連接池中連接最小個數 -->
36         <property name="minPoolSize" value="5"></property>
37         <!-- 連接池中連接最大個數 -->
38         <property name="maxPoolSize" value="20"></property>
39     </bean>
40     
41     <!--3 會話工廠bean sqlSessionFactoryBean -->
42     <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
43         <!-- 數據源 -->
44         <property name="dataSource" ref="datasource"></property>
45         <!-- 別名 -->
46         <property name="typeAliasesPackage" value="com.pojo"></property>
47         <!-- sql映射文件路徑 -->
48         <property name="mapperLocations" value="classpath*:com/dao/*Mapper.xml"></property>
49     </bean>
50     
51     <!--4 自動掃描對象關係映射 -->
52     <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
53         <!--指定會話工廠,如果當前上下文中只定義了一個則該屬性可省去 -->
54         <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
55         <!-- 指定要自動掃描接口的基礎包,實現接口 -->
56         <property name="basePackage" value="com.dao"></property>
57     </bean>
58     
59     <!--5 聲明式事務管理 -->
60     <!--定義事物管理器,由spring管理事務 -->
61     <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
62         <property name="dataSource" ref="datasource"></property>
63     </bean>
64     <!--支持註解驅動的事務管理,指定事務管理器 -->
65     <tx:annotation-driven transaction-manager="transactionManager"/>
66 
67     <!--6 容器自動掃描IOC組件  -->
68     <context:component-scan base-package="com"></context:component-scan>
69     
70     <!--7 aspectj支持自動代理實現AOP功能 -->
71     <aop:aspectj-autoproxy proxy-target-class="true"></aop:aspectj-autoproxy>
72 </beans>
View Code

添加db.properties

1 #mysql jdbc
2 jdbc.driver=com.mysql.jdbc.Driver
3 jdbc.url=jdbc:mysql://localhost:3306/my_db?useUnicode=true&characterEncoding=UTF-8
4 jdbc.uid=root
5 jdbc.pwd=123456
View Code

創建單元測試類來測試是否能夠調用數據庫。UserServiceTest.java、BooksServiceTest.java

 1 package com.service;
 2 
 3 import org.junit.BeforeClass;
 4 import org.junit.Test;
 5 import org.springframework.context.ApplicationContext;
 6 import org.springframework.context.support.ClassPathXmlApplicationContext;
 7 
 8 import com.pojo.User;
 9 
10 public class UserServiceTest {
11 
12     private static UserService service;
13     
14     //測試前需加載的方法
15     @BeforeClass
16     public static void before(){
17         ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
18         service = context.getBean(UserService.class);
19     }
20     
21     @Test
22     public void testGetUser() {
23         
24         User user = service.getUser("aaa");
25         
26         System.out.println(user.toString());
27         
28     }
29 
30 }
View Code
 1 package com.service;
 2 
 3 import static org.junit.Assert.*;
 4 
 5 import java.util.List;
 6 
 7 import org.junit.BeforeClass;
 8 import org.junit.Test;
 9 import org.springframework.context.ApplicationContext;
10 import org.springframework.context.support.ClassPathXmlApplicationContext;
11 
12 import com.dao.BooksDao;
13 import com.pojo.Books;
14 
15 public class BooksServiceTest {
16 
17     private static BooksDao booksDao;
18     
19     @BeforeClass
20     public static void before(){
21         ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
22         booksDao = context.getBean(BooksDao.class);
23     }
24     
25     @Test
26     public void testDeleteBooksById() {
27         fail("Not yet implemented");
28     }
29 
30     @Test
31     public void testAddBooks() {
32         fail("Not yet implemented");
33     }
34 
35     @Test
36     public void testUpdateBooks() {
37         fail("Not yet implemented");
38     }
39 
40     @Test
41     public void testGetBooksById() {
42         fail("Not yet implemented");
43     }
44 
45     @Test
46     public void testGetBooksAll() {
47         List<Books> list = booksDao.getBooksAll();
48         for(Books book : list) {
49             System.out.println(book.toString());
50         }
51     }
52 
53 }
View Code

如果測試發現沒有問題,則就可以開始實現前端了。先實現登錄功能。用用戶輸入的用戶名作爲查詢條件,得到數據表內與其對應的密碼,該密碼若與用戶輸入的密碼不同則提示“用戶名或密碼錯誤”再重新輸入,若相同則轉發到信息展示頁面。

此時需要配置DispatcherServlet,在web.xml中進行配置。

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 3     xmlns="http://java.sun.com/xml/ns/javaee"
 4     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
 5     id="WebApp_ID" version="3.0" >
 6     
 7     <servlet>
 8         <servlet-name>controller</servlet-name>
 9         <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
10         <load-on-startup>1</load-on-startup>
11     </servlet>
12     <servlet-mapping>
13         <servlet-name>controller</servlet-name>
14         <url-pattern>/</url-pattern>
15     </servlet-mapping>
16         
17     <listener>
18         <description>contextLoaderListener</description>
19         <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
20     </listener>
21     <context-param>
22         <description>ContextLoaderListener</description>
23         <param-name>contextConfigLocation</param-name>
24         <param-value>classpath*:applicationContext.xml</param-value>
25     </context-param>
26 </web-app>
View Code

默認需要配置DispatcherServlet的<name>-servlet.xml作爲視圖解析器的配置文件,controller-servlet.xml。放在WEB-INF下。

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4     xmlns:aop="http://www.springframework.org/schema/aop"
 5     xmlns:c="http://www.springframework.org/schema/c"
 6     xmlns:cache="http://www.springframework.org/schema/cache"
 7     xmlns:context="http://www.springframework.org/schema/context"
 8     xmlns:jdbc="http://www.springframework.org/schema/jdbc"
 9     xmlns:jee="http://www.springframework.org/schema/jee"
10     xmlns:lang="http://www.springframework.org/schema/lang"
11     xmlns:mvc="http://www.springframework.org/schema/mvc"
12     xmlns:p="http://www.springframework.org/schema/p"
13     xmlns:task="http://www.springframework.org/schema/task"
14     xmlns:tx="http://www.springframework.org/schema/tx"
15     xmlns:util="http://www.springframework.org/schema/util"
16     xsi:schemaLocation="http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.3.xsd
17         http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
18         http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
19         http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
20         http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.3.xsd
21         http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.3.xsd
22         http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-4.3.xsd
23         http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.3.xsd
24         http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
25         http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang-4.3.xsd
26         http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd ">
27  
28      <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" 
29          p:prefix="/"
30          p:suffix=".jsp"
31      />
32      
33      <context:component-scan base-package="com.controller"></context:component-scan>
34  
35         
36 </beans>
View Code

配置登錄用的controller,LoginController.java。使用springmvc的參數綁定標籤獲取jsp表單中的數據

 1 package com.controller;
 2 
 3 import java.util.List;
 4 
 5 import org.springframework.beans.factory.annotation.Autowired;
 6 import org.springframework.stereotype.Controller;
 7 import org.springframework.web.bind.annotation.RequestMapping;
 8 import org.springframework.web.bind.annotation.RequestMethod;
 9 import org.springframework.web.bind.annotation.RequestParam;
10 import org.springframework.web.servlet.ModelAndView;
11 
12 import com.pojo.Books;
13 import com.pojo.User;
14 import com.service.BooksService;
15 import com.service.UserService;
16 
17 @Controller
18 @RequestMapping("/bookstore")
19 public class LoginController {
20 
21     @Autowired
22     private UserService userService;
23     
24     @Autowired
25     private BooksService booksService;
26     
27     @RequestMapping(path = "/login" ,method = RequestMethod.POST)
28     public ModelAndView userLogin(@RequestParam("username")String username,@RequestParam("password")String password) {
29         
30         ModelAndView modelAndView = new ModelAndView();
31         
32         User user = userService.getUser(username);
33         
34         List<Books> books = booksService.getBooksAll();
35         
36         if(password.equals(user.getPassword())){
37             modelAndView.setViewName("ListBook");
38             modelAndView.addObject("books", books);
39         }
40         else {
41             modelAndView.setViewName("login");
42             modelAndView.addObject("user", user);
43             modelAndView.addObject("message", "用戶名或密碼錯誤");
44         }
45         
46         return modelAndView;
47         
48     }
49     
50 }
View Code

再添加登錄頁面login.jsp,裏面使用jstl標籤獲取ModelAndView內的信息

 1 <%@ page language="java" contentType="text/html; charset=UTF-8"
 2     pageEncoding="UTF-8"%>
 3 <%@taglib  uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
 4 <!DOCTYPE html>
 5 <html>
 6 <head>
 7 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 8 <link href="styles/main.css" type="text/css" rel="stylesheet" />
 9 <title>系統登錄</title>
10 </head>
11 <body>
12     
13     <div class="main">
14         <h2 class="title"><span>系統登錄</span></h2>
15         <form action="<c:url value="/bookstore/login" />" method="post">
16               <p>用戶名: <input type="text" name="username" value="${user.getUsername()}" /></p>
17               <p>&nbsp;&nbsp;&nbsp;&nbsp;碼: <input type="password" name="password" value="${user.getPassword() }" /></p>
18               <input type = "submit" name="login" value ="登錄"/>
19         </form>
20         <p style="color: red">${message}</p>
21     </div>
22     
23 </body>
24 </html>
View Code

登錄實現後就開始實現CURD功能。先是ListBook.jsp,獲取數據庫內的所有數據,從login.jsp轉發到該頁面。

 1 <%@ page language="java" contentType="text/html; charset=UTF-8"
 2     pageEncoding="UTF-8"%>
 3 <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
 4 <%@taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
 5 <!DOCTYPE html>
 6 <html>
 7 <head>
 8 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 9 <link href="styles/main.css" type="text/css" rel="stylesheet" />
10 <title>圖書管理</title>
11 </head>
12 <body>
13     <div class="main">
14         <h2 class="title"><span>圖書管理</span></h2>
15         <form action="<c:url value="/bookstore/deletes" />" method="post">
16         <table border="1" width="100%" class="tab">
17             <tr>
18                 <th><input type="checkbox" id="chbAll"></th>
19                 <th>編號</th>
20                 <th>書名</th>
21                 <th>價格</th>
22                 <th>出版日期</th>
23                 <th>操作</th>
24             </tr>
25             <c:forEach var="book" items="${books}">
26                 <tr>
27                     <th><input type="checkbox" name="ids" value="${book.id}"></th>
28                     <td>${book.id}</td>
29                     <td>${book.title}</td>
30                     <td>${book.price}</td>
31                     <td><fmt:formatDate value="${book.publishDate}" pattern="yyyy年MM月dd日"/></td>
32                     <td>
33                     <a href="<c:url value="/bookstore/delete" />?id=${book.id}" class="abtn">刪除</a>
34                     <a href="<c:url value="/bookstore/update" />?id=${book.id}" class="abtn">編輯</a>
35                     </td>
36                 </tr>
37             </c:forEach>
38         </table>
39         <p style="color: red">${message}</p>
40         <p>
41             <a href="<c:url value="/bookstore/add" />" class="abtn">添加</a>
42             <input type="submit"  value="刪除選擇項" class="btn"/>
43         </p>
44     </form>
45     </div>
46 </body>
47 </html>
View Code

接着實現ListBook.jsp內的所有按鈕功能。先說刪除和多項刪除。刪除的話就是直接拿到id調用數據庫進行刪除,多項刪除拿到要被刪除的所有id一個一個的刪除,實現思路都是用springmvc的參數綁定標籤獲取jsp表單中的數據,也就是封裝servlet的request、response。其實也沒有啥思路好說的(2333),修改和添加頁面都是如此,EditBook.jsp、AddBook.jsp。

 1 <%@ page language="java" contentType="text/html; charset=UTF-8"
 2     pageEncoding="UTF-8"%>
 3 <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
 4 <%@taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
 5 <!DOCTYPE html>
 6 <html>
 7 <head>
 8 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 9 <link href="styles/main.css" type="text/css" rel="stylesheet" />
10 <title>編輯圖書</title>
11 </head>
12 <body>
13     <div class="main">
14         <h2 class="title"><span>編輯圖書</span></h2>
15         <form action="<c:url value="/bookstore/updatePost" />" method="post">
16         <fieldset>
17             <legend>圖書</legend>
18             <p>
19                 <label for="title">圖書名稱:</label>
20                 <input type="text" id="title" name="title"  value="${book.title}"/>
21             </p>
22             <p>
23                 <label for="title">圖書價格:</label>
24                 <input type="text" id="price" name="price" value="${book.price}"/>
25             </p>
26             <p>
27                 <label for="title">出版日期:</label>
28                 <input type="text" id="publishDate" name="publishDate"  value="<fmt:formatDate value="${book.publishDate}" pattern="yyyy-MM-dd"/>"/>
29             </p>
30             <p>
31                <input type="hidden" id="id" name="id" value="${book.id}"/>
32               <input type="submit" value="保存" class="btn">
33             </p>
34         </fieldset>
35         </form>
36         <p style="color: red">${message}</p>
37         <p>
38             <a href="<c:url value="/bookstore/list" />" class="abtn">返回列表</a>
39         </p>
40     </div>
41 </body>
42 </html>
View Code
 1 <%@ page language="java" contentType="text/html; charset=UTF-8"
 2     pageEncoding="UTF-8"%>
 3 <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
 4 <!DOCTYPE html>
 5 <html>
 6 <head>
 7 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 8 <link href="styles/main.css" type="text/css" rel="stylesheet" />
 9 <title>新增圖書</title>
10 </head>
11 <body>
12     <div class="main">
13         <h2 class="title"><span>新增圖書</span></h2>
14         <form action="<c:url value="/bookstore/addPost" />" method="post">
15         <fieldset>
16             <legend>圖書</legend>
17             <p>
18                 <label for="title">圖書名稱:</label>
19                 <input type="text" id="title" name="title"/>
20             </p>
21             <p>
22                 <label for="title">圖書價格:</label>
23                 <input type="text" id="price" name="price" />
24             </p>
25             <p>
26                 <label for="title">出版日期:</label>
27                 <input type="text" id="publishDate" name="publishDate" />
28             </p>
29             <p>
30               <input type="submit" value="保存" class="btn">
31             </p>
32         </fieldset>
33         </form>
34         <p style="color: red">${message}</p>
35         <p>
36             <a href="<c:url value="/bookstore/list" />" class="abtn">返回列表</a>
37         </p>
38     </div>
39 </body>
40 </html>
View Code

到這裏所有功能都已經完善,說說其中碰到的問題:

1:頁面404問題

  (一)、未加載controller包,無法加載controller,但我在Spring-mybatis裏已經配置過掃描所有包了,目前還沒查具體原因(2333,急着做項目準備找工作,哪位要是知道也可以在底下評論告訴我下),無奈只能在springmvc文件裏又重新掃描controller包,解決了該問題。

  (二)、我一開始在jsp頁面中所有請求都是直接寫路徑,一直都是404就很煩,突然看到瀏覽器地址欄的路徑,在提交之後會直接變成jsp頁面內表單的action路徑,地址欄路徑裏的項目名沒有了,用了jstl裏的<c:url >標籤解決。

2:表單內容無法封裝到springmvc內

  springmvc會自動得到表單內容封裝到相對應對象屬性中,發現無法封裝,百度後知道問題是出在數據表的publishDate字段,看別人博客裏說的是在set方法中,傳入字符串再強轉爲日期類型,因爲springmvc只能封裝string類型。

3:亂碼問題

  就是在添加和修改頁面所提交的漢字會亂碼,debug發現是springmvc封裝裏的內容亂碼,從springMVC獲取內容再轉碼調用數據庫。

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章