1. 对象 转 JSON
平时,我们就是通过JSON.stringify()将js对象转换为了json对象。
2. Jackson的使用
2.1 准备工作
导包导依赖:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.13.1</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.15</version>
</dependency>
<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
public String json1() throws JsonProcessingException {
ObjectMapper objectMapper = new ObjectMapper();
User user = new User("张三",18,"男");
String s = objectMapper.writeValueAsString(user);
return s;
}
}
第二种方式,乱码统一解决,在SpringMVC的配置文件上添加一段消息StringHttpMessageConverter转换配置。(只要使用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
public class UserController {
@RequestMapping("/j3")
public String json3() throws JsonProcessingException {
ObjectMapper objectMapper = new ObjectMapper();
Date date = new Date();
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.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS,false);
Date date = new Date();
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
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字符串/来源。
Student student = mapper.readValue(jsonString, Student.class);
第3步:序列化对象到JSON。
- 使用writeValueAsString()方法来获取对象的JSON字符串表示。
jsonString = mapper.writeValueAsString(student);
3. FastJson的使用
同样,先导入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
public class UserController {
@RequestMapping("/j5")
public String json5() {
User user = new User("张三", 18, "男");
String s = JSON.toJSONString(user);
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>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>5.8.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.79</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.27</version>
</dependency>
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.2</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.2</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.6</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.6</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.15</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.3.15</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.22</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.6</version>
</dependency>
<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>
<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>
<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{
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
">
<context:property-placeholder location="classpath:db.properties"/>
<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}"/>
<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>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="configLocation" value="classpath:mybatis-config.xml"/>
</bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
<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
">
<context:component-scan base-package="com.itholmes.service"/>
<bean id="BookServiceImpl" class="com.itholmes.service.BookServiceImpl">
<property name="bookMapper" ref="bookMapper"/>
</bean>
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<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">
<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: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-config>
<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
">
<mvc:annotation-driven/>
<mvc:default-servlet-handler/>
<context:component-scan base-package="com.itholmes.controller"/>
<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注解:放到方法上(被该注解定义的方法,不经过视图解析器直接返回值。)
|