文章目录
1. 对象 转 JSON
平时,我们就是通过JSON.stringify()将js对象转换为了json对象。
2. Jackson的使用
2.1 准备工作
导包导依赖:
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.13.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.15</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.22</version>
<scope>provided</scope>
</dependency>
配置web.xml文件:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<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:springmvc-servlet.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<filter>
<filter-name>encoding</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>encoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
配置指向的springmvc-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:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
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.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
">
<context:component-scan base-package="com.itholmes.controller"/>
<mvc:default-servlet-handler/>
<mvc:annotation-driven/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>
在WEB-INF目录下,创建jsp目录存放jsp文件(放在WEB-INF目录下,安全):
2.2 @ResponseBody注解 和 @RestController注解
只要声明了@ResponseBody注解,它就不会走视图解析器,而是直接给前端返回一个字符串。
@RestController注解,一方面是声明当前是一个控制器类并且接受扫描,另一方面是当前类的方法返回的内容都不会走视图解析器!
这两个注解看情况使用,如果写的是前后端分离的项目,我们一般直接@RestController就可以了。而@ResponseBody注解和@Controller注解配合使用,用于部分方法返回字符串。
2.3 使用jackson来转json格式的字符串
我们使用jackson中的objectMapper对象的writeValueAsString(obj)方法来将obj转成json格式的字符串。
如果我们用汉字,就会乱码!
2.4 jackson转换的乱码问题
第一种方式:我们可以使用@RequestMapping的参数produces来指定类型。
package com.itholmes.controller;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.itholmes.pojo.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class UserController {
@RequestMapping(value = "/j1",produces = "application/json;charset=utf-8")
@ResponseBody//只要声明了@ResponseBody注解,它就不会走视图解析器,而是直接返回一个字符串。
public String json1() throws JsonProcessingException {
//jackson中的ObjectMapper对象
ObjectMapper objectMapper = new ObjectMapper();
User user = new User("张三",18,"男");//创建一个对象
//我们使用writeValueAsString方法来讲user对象转成一个json格式的字符串。
String s = objectMapper.writeValueAsString(user);
return s;
}
}
第二种方式,乱码统一解决,在SpringMVC的配置文件上添加一段消息StringHttpMessageConverter转换配置。(只要使用jackson,我们就配置下面就可以了,推荐也是推荐使用这种方式来进行的。)
<!--Jackson的JSON乱码问题配置,这个是固定的!只要用jackson来操作就必须配置这些内容,不然就会乱码。-->
<mvc:annotation-driven>
<mvc:message-converters>
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<constructor-arg value="UTF-8"/>
</bean>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="objectMapper">
<bean class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean">
<property name="failOnEmptyBeans" value="false"/>
</bean>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
2.5 jackson将各种类型的数据转换成字符串
jackson将List集合转成json格式字符串。
jackson对date日期类型的数据操作:
- json3方法是我们直接设置simpledateformat来定义的格式化。
- json4方法是通过改变jackson对date格式化的自定义格式来操作的。
package com.itholmes.controller;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.itholmes.pojo.User;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
@RestController//@RestController注解,一方面是声明当前是一个控制器类并且接受扫描,另一方面是当前类的方法返回的内容都不会走视图解析器!
public class UserController {
@RequestMapping("/j3")
public String json3() throws JsonProcessingException {
ObjectMapper objectMapper = new ObjectMapper();
Date date = new Date();//一般我们这里会得到一个timestamps时间戳
//按照平时我们的java代码使用simpledateformate对象来格式化它。
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
String s = format.format(date);
String str = objectMapper.writeValueAsString(s);
return str;
}
@RequestMapping("/j4")
public String json4() throws JsonProcessingException {
ObjectMapper objectMapper = new ObjectMapper();
//使用ObjectMapper对象来格式化输出
//下面这句代码就是关闭objectMapper对象时间戳定义的方式。
objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS,false);
Date date = new Date();//一般我们这里会得到一个timestamps时间戳
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
//然后我们自定义了Date格式化的方式。
objectMapper.setDateFormat(format);
String str = objectMapper.writeValueAsString(date);
return str;
}
}
其实上面很多操作,都可以在utils层给设置静态方法方便调用,方便代码的复用。
2.6 jackson总结
第1步:创建ObjectMapper对象。
- 创建ObjectMapper对象。它是一个可重复使用的对象。
ObjectMapper mapper = new ObjectMapper();
第2步:反序列化JSON到对象。
- 从JSON对象使用readValue()方法来获取。通过JSON字符串和对象类型作为参数JSON字符串/来源。
//Object to JSON Conversion
Student student = mapper.readValue(jsonString, Student.class);
第3步:序列化对象到JSON。
- 使用writeValueAsString()方法来获取对象的JSON字符串表示。
//Object to JSON Conversion
jsonString = mapper.writeValueAsString(student);
3. FastJson的使用
同样,先导入FastJson的依赖:
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.79</version>
</dependency>
package com.itholmes.controller;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.itholmes.pojo.User;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
@RestController//@RestController注解,一方面是声明当前是一个控制器类并且接受扫描,另一方面是当前类的方法返回的内容都不会走视图解析器!
public class UserController {
@RequestMapping("/j5")
public String json5() {
User user = new User("张三", 18, "男");
//fastjson序列化
String s = JSON.toJSONString(user);
//fastjson反序列化
User user1 = JSON.parseObject(s, User.class);
System.out.println(user1);
return s;
}
}
比较重要的就是fastjson的序列化和反序列化的两个方式,记住就可以。
有时候使用fastjson可能会看到下面的几种转换,Java对象,JSON字符串,JSON对象,如下图:
4. ssm 之 整合Mybatis
其实,整合Mybatis,Spring和SpringMVC就是写一个前后端增删改查的效果。
4.1 创建数据库 + 导入依赖
有了数据库就得写db.properties文件:
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://rm-bp168t05xk88zzbv7ro.mysql.rds.aliyuncs.com/ssmbuild?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf8&useSSL=true
jdbc.username=root
jdbc.password=root
导包,导依赖。
需要的包有:junit , 数据库驱动, 连接池,servlet-api(如果是jsp项目需要导入:jsp-api,jstl),mybatis,spring和spring-webmvc。
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.junit.jupiter/junit-jupiter-api -->
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>5.8.2</version>
<scope>test</scope>
</dependency>
<!--json-->
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.79</version>
</dependency>
<!--mysql驱动-->
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.27</version>
</dependency>
<!--C3p0连接池-->
<!-- https://mvnrepository.com/artifact/com.mchange/c3p0 -->
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.2</version>
</dependency>
<!--Servlet-->
<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.servlet.jsp/jsp-api -->
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.servlet/jstl -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!--Mybatis-->
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.6</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.6</version>
</dependency>
<!--Spring-->
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.15</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.3.15</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.22</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.6</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-tx -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>5.3.15</version>
</dependency>
4.2 创建mybatis配置文件 和 pojo类
mybatis-config.xml文件:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!--配置dataSource数据源,交给Spring去做!我们不用mybatis。-->
<settings>
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
<typeAliases>
<typeAlias type="com.itholmes.pojo.Books" alias="Books"/>
</typeAliases>
<mappers>
<mapper class="com.itholmes.dao.BookMapper"/>
</mappers>
</configuration>
pojo层的实体类Books :
package com.itholmes.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Books {
private int bookID;
private String bookName;
private int bookCounts;
private String detail;
}
4.3 搭建dao层接口
BookMapper接口类对应实体类Books的增删改查:
package com.itholmes.dao;
import com.itholmes.pojo.Books;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface BookMapper {
//增加一本书
int addBook(Books books);
//删除一本书
int deleteBookById(@Param("bookId") int id);
//修改一本书
int updateBookById(Books books);
//查询一本书
Books queryBookById(@Param("bookId") int id);
//查询全部的书
List<Books> queryAllBook();
}
在mybatis中,有了接口就有对应的BookMapper.xml文件来配置它:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.itholmes.dao.BookMapper">
<insert id="addBook" parameterType="Books">
insert into ssmbuild.books (bookName,bookCounts,detail)
values (#{bookName},#{bookCounts},#{detail});
</insert>
<!--这里的int类型指的是integer包装类的类型,如果指定基本int类型,就用_int,别名的效果-->
<delete id="deleteBookById" parameterType="int">
delete from ssmbuild.books where bookID = #{bookId};
</delete>
<update id="updateBookById" parameterType="Books">
update ssmbuild.books
set bookName=#{bookName},bookCounts=#{bookCounts},detail=#{detail}
where bookID=#{bookID}
</update>
<select id="queryBookById" parameterType="int" resultType="Books">
select * from ssmbuild.books where bookID=#{bookId}
</select>
<select id="queryAllBook" resultType="Books">
select * from ssmbuild.books
</select>
</mapper>
4.4 搭建service层
service业务层的本质调用dao持久层的东西,所以在这里写起来很简单。
BookService接口类:
package com.itholmes.service;
import com.itholmes.pojo.Books;
import java.util.List;
@Service
public interface BookService {
//增加一本书
int addBook(Books books);
//删除一本书
int deleteBookById(int id);
//修改一本书
int updateBookById(Books books);
//查询一本书
Books queryBookById(int id);
//查询全部的书
List<Books> queryAllBook();
}
BookServiceImpl实现类:
package com.itholmes.service;
import com.itholmes.dao.BookMapper;
import com.itholmes.pojo.Books;
import java.util.List;
public class BookServiceImpl implements BookService{
//service业务层调用dao持久层
private BookMapper bookMapper;
public void setBookMapper(BookMapper bookMapper) {
this.bookMapper = bookMapper;
}
@Override
public int addBook(Books books) {
return bookMapper.addBook(books);
}
@Override
public int deleteBookById(int id) {
return bookMapper.deleteBookById(id);
}
@Override
public int updateBookById(Books books) {
return bookMapper.updateBookById(books);
}
@Override
public Books queryBookById(int id) {
return bookMapper.queryBookById(id);
}
@Override
public List<Books> queryAllBook() {
return bookMapper.queryAllBook();
}
}
5. ssm 之 整合Spring
接着上面的Mybatis继续整合Spring。
Spring整合的话就是对应三个配置文件,加一个总配置文件的配置。
- 三个配置文件分别对应dao,service,mvc的三个配置文件。
spring-dao.xml文件:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
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.xsd
">
<!--1.关联数据库配置文件,这里是通过spring来读取db.properties文件中的数据库配置。-->
<context:property-placeholder location="classpath:db.properties"/>
<!--
2.datasource连接池
常用的数据库池有
dbcp:半自动化操作,不能自动连接。
c3p0:自动化操作,自动化的加载配置文件。
druid和hikari:公司常用的连接池。
-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driver}"/>
<property name="jdbcUrl" value="${jdbc.url}"/>
<property name="user" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
<!--c3p0连接池的私有属性-->
<property name="maxPoolSize" value="30"/>
<property name="minPoolSize" value="10"/>
<!--关闭连接后不自动提交-->
<property name="autoCommitOnClose" value="false"/>
<!--获取连接超时时间-->
<property name="checkoutTimeout" value="10000"/>
<!--当获取连接失败重试次数-->
<property name="acquireRetryAttempts" value="2"/>
</bean>
<!--3.sqlSessionFactory对象,注意需要将dataSource和configLocation两个参数给他传入。-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<!--绑定Mybatis的配置文件-->
<property name="configLocation" value="classpath:mybatis-config.xml"/>
</bean>
<!--4.配置dao接口扫描包,动态的实现了Dao接口可以注入到Spring容器中-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!--注入sqlSessionFactory-->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
<!--要扫描的dao包-->
<property name="basePackage" value="com.itholmes.dao"/>
</bean>
</beans>
spring-service.xml文件:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
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.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
">
<!--1.扫描service下的包-->
<context:component-scan base-package="com.itholmes.service"/>
<!--2.将我们的所有业务类,注入到Spring,可以通过配置或者注解。-->
<bean id="BookServiceImpl" class="com.itholmes.service.BookServiceImpl">
<property name="bookMapper" ref="bookMapper"/>
</bean>
<!--3.声明式事务配置-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!--注入数据源-->
<property name="dataSource" ref="dataSource"/>
</bean>
<!--4.aop事务支持。-->
<!--配置事务通知-->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="*" propagation="REQUIRED"/>
</tx:attributes>
</tx:advice>
<!--配置事务切入-->
<aop:config>
<aop:pointcut id="txPointCut" expression="execution(* com.itholmes.dao.*.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"/>
</aop:config>
</beans>
6. ssm 之 整合SpringMVC
web.xml文件:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<!--DispatchServlet-->
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<!--配置成applicationContext.xml确保bean能够被使用到。-->
<param-value>classpath:applicationContext.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<!-- / 的话只会过滤请求。-->
<url-pattern>/</url-pattern>
</servlet-mapping>
<!--乱码过滤-->
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>utf-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!--Session-->
<session-config>
<!--设置session会话时间为15分钟-->
<session-timeout>15</session-timeout>
</session-config>
</web-app>
spring-mvc.xml文件:(这也是spring的内容,只不过放到了mvc这一小节中)
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
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.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
">
<!--1.注解驱动-->
<mvc:annotation-driven/>
<!--2.静态资源过滤-->
<mvc:default-servlet-handler/>
<!--3.扫描包-->
<context:component-scan base-package="com.itholmes.controller"/>
<!--4.视图解析器-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>
最后全部导入到一个配置文件applicationContext.xml中去,这样非常好理解:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<import resource="classpath:spring-dao.xml"/>
<import resource="classpath:spring-mvc.xml"/>
<import resource="classpath:spring-service.xml"/>
</beans>
7. ssm 之 视图层对应controller层
index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>主页</title>
<style>
a{
text-decoration: none;
color: black;
font-size: 18px;
}
h3{
width: 180px;
height: 38px;
margin: 100px auto;
text-align: center;
line-height: 38px;
background: deepskyblue;
border-radius: 5px;
}
</style>
</head>
<body>
<h3>
<a href="${pageContext.request.contextPath}/book/allBook">进入书籍页面</a>
</h3>
</body>
</html>
addBook.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
<link href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
<div class="row clearfix">
<div class="col-md-12 column">
<div class="page-header">
<h1>
<small>新增书籍</small>
</h1>
</div>
</div>
</div>
<form action="${pageContext.request.contextPath}/book/addBook" method="post">
<div class="form-group">
<label for="bkname">书籍名称</label>
<input type="text" class="form-control" id="bkname" name="bookName" required>
</div>
<div class="form-group">
<label for="bkname2">书籍数量</label>
<input type="text" class="form-control" id="bkname2" name="bookCounts" required>
</div>
<div class="form-group">
<label for="bkname3">书籍描述</label>
<input type="text" class="form-control" id="bkname3" name="detail" required>
</div>
<div class="form-group">
<input type="submit" class="form-control" value="添加">
</div>
</form>
</div>
</body>
</html>
allBook.jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>书籍展示页面</title>
<link href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
<div class="row clearfix">
<div class="col-md-12 column">
<div class="page-header">
<h1>
<small>书籍列表 ---- 显示所有书籍</small>
</h1>
</div>
</div>
<div class="row">
<div class="col-md-4 column">
<%--这里就需要跳转增加页面--%>
<a class="btn btn-primary" href="${pageContext.request.contextPath}/book/toAddBook">新增书籍</a>
</div>
</div>
</div>
<div class="row clearfix">
<div class="col-md-12 column">
<table class="table table-hover table-striped">
<thead>
<tr>
<th>书籍编号</th>
<th>书籍名称</th>
<th>书籍数量</th>
<th>书籍详情</th>
</tr>
</thead>
<%--书籍从数据库中查询出来,从list中遍历出来。--%>
<tbody>
<c:forEach var="book" items="${list}" >
<tr>
<td>${book.bookID}</td>
<td>${book.bookName}</td>
<td>${book.bookCounts}</td>
<td>${book.detail}</td>
<td>
<a href="${pageContext.request.contextPath}/book/toUpdate/${book.bookID}">修改</a>
|
<a href="${pageContext.request.contextPath}/book/deleteBook/${book.bookID}">删除</a>
</td>
</tr>
</c:forEach>
</tbody>
</table>
</div>
</div>
</div>
</body>
</html>
updateBook.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>修改书籍</title>
<link href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="row clearfix">
<div class="col-md-12 column">
<div class="page-header">
<h1>
<small>修改书籍</small>
</h1>
</div>
</div>
</div>
<form action="${pageContext.request.contextPath}/book/updateBook" method="post">
<%--因为这里我们update需要id,因此需要前端传递隐藏域--%>
<input type="hidden" name="bookID" value="${Qbooks.bookID}">
<div class="form-group">
<label for="bkname">书籍名称</label>
<input type="text" class="form-control" id="bkname" name="bookName" value="${Qbooks.bookName}" required>
</div>
<div class="form-group">
<label for="bkname2">书籍数量</label>
<input type="text" class="form-control" id="bkname2" name="bookCounts" value="${Qbooks.bookCounts}" required>
</div>
<div class="form-group">
<label for="bkname3">书籍描述</label>
<input type="text" class="form-control" id="bkname3" name="detail" value="${Qbooks.detail}" required>
</div>
<div class="form-group">
<input type="submit" class="form-control" value="修改">
</div>
</form>
</body>
</html>
这样一个ssm的增删改查就完成了!
8. 整合的时候 注意细节
如果报错说 bean不存在的话,查询步骤如下所示:
前端form标签属性中有个required属性,要求必须写上才能提交给后台。
并且视图层这一块多数用了bootstrap的css框架来渲染修饰。
9. ajax 和 ssm
上面我们创建的增删改查都是基于jsp的是前后端不分离的情况,如果想用前后端分离就需要ajax(一般用jq的ajax)来实现。
ajax后台调用接口注意事项:
- 是否跨源。
- 控制类一般使用@RestController注解 和 @ResponseBody注解来配合ajax使用。
- @RestController注解:放到类上(和@Controller功能一样,只不过它定义的类的方法返回值不经过视图解析器,直接返回值。)
- @ResponseBody注解:放到方法上(被该注解定义的方法,不经过视图解析器直接返回值。)