目录
一、JSP概述
二、JSP快速入门
三、JSP原理
四、JSP脚本
五、 JSP缺点
六、EL表达式
七、JSTL标签
C标签:
八、MVC模式和三层架构
MVC模式:
三层架构:
两者之间的关系:
九、案例练习
9.1 环境准备
引坐标:
<packaging>war</packaging>
<!--依赖-->
<dependencies>
<!--mybatis-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.5</version>
</dependency>
<!--mysql-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.34</version>
</dependency>
<!--servlet-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<!--jsp-->
<dependency>
<groupId>org.glassfish.web</groupId>
<artifactId>jsp</artifactId>
<version>2.2</version>
<scope>provided</scope>
</dependency>
<!--jstl-->
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!--standard库-->
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
</dependencies>
<!--插件-->
<build>
<plugins>
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.2</version>
</plugin>
</plugins>
</build>
创建三层架构的包结构:
Mybatis基础环境:
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>
<!--起别名-->
<typeAliases>
<package name="com.itheima.pojo"/>
</typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql:///db1?useSSL=false&useServerPrepStmts=true"/>
<property name="username" value="root"/>
<property name="password" value=""/>
</dataSource>
</environment>
</environments>
<mappers>
<!--扫描mapper-->
<package name="com.itheima.mapper"/>
</mappers>
</configuration>
BrandMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.itheima.mapper.BrandMapper">
</mapper>
BrandMapper接口:
package com.itheima.mapper;
public interface BrandMapper {
}
9.2 查询所有
Mapper接口(Dao层):
/**
* 查询所有
* @return
*/
@Select("select * from tb_brand")
// @ResultMap("brandResultMap")
List<Brand> selectAll();
Service层:
//1.获取SqlSessionFactory对象
SqlSessionFactory factory = SqlSessionFactoryUtils.getSqlSessionFactory();
//2.获取SqlSession对象
SqlSession sqlSession = factory.openSession();
//3.获取BrandMapper对象
BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
//4.调用方法
List<Brand> brands = mapper.selectAll();
//5.关闭资源
sqlSession.close();
return brands;
Web层:
@WebServlet("/selectAllServlet")
public class SelectAllServlet extends HttpServlet {
private BrandService service = new BrandService();
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1.调用BrandService查询数据,并封装为List对象
List<Brand> brands = service.selectAll();
//2.将数据存到request域中
request.setAttribute("brands",brands);
//3.转发到brand.jsp
request.getRequestDispatcher("/brand.jsp").forward(request,response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
}
注意:
在BrandMapper.xml里 设置resultMap来解决数据库和java的名称命名不一致,即映射属性名和数据库中的字段名
在mapper接口中记得添加注解使用
另一种方法:在mybatis-config.xml中设置
<!--开启驼峰命名自动映射-->
<settings>
<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
9.3 添加数据
Mapper接口(Dao层):
@Insert("insert into tb_brand values(null,#{brandName},#{companyName},#{ordered},#{description},#{status})")
// @ResultMap("brandResultMap")
void add(Brand brand);
Service层:
/**
* 添加
* @param brand
*/
public void add(Brand brand){
//1.获取SqlSessionFactory对象
SqlSessionFactory factory = SqlSessionFactoryUtils.getSqlSessionFactory();
//2.获取sqlSession对象
SqlSession sqlSession = factory.openSession();
//3.获取BrandMapper对象
BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
//4.调用方法
mapper.add(brand);
//5.增删改需要提交事务
sqlSession.commit();
//6.释放资源
sqlSession.close();
Web层:
@WebServlet("/addServlet")
public class AddServlet extends HttpServlet {
private BrandService service = new BrandService();
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//解决Post中文乱码问题
request.setCharacterEncoding("utf-8");
//1.接受表单提交的数据并将其封装为一个Brand对象
String brandName = request.getParameter("brandName");
String companyName = request.getParameter("companyName");
String ordered = request.getParameter("ordered");
String description = request.getParameter("description");
String status = request.getParameter("status");
//封装为Brand对象
Brand brand = new Brand();
brand.setBrandName(brandName);
brand.setCompanyName(companyName);
brand.setOrdered(Integer.parseInt(ordered));//将字符类型转为Int类型
brand.setDescription(description);
brand.setStatus(Integer.parseInt(status));
//2.调用service完成添加操作
service.add(brand);
//3.转发到查询所有Servlet
request.getRequestDispatcher("/selectAllServlet").forward(request,response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
}
注意:
中文乱码问题:post请求只需要在AddServlet中添加一行代码
//解决Post中文乱码问题
request.setCharacterEncoding("utf-8");
MySQL中增删改操作需要提交事务
可以在获取sqlSession对象设置为自动提交:
//2.获取sqlSession对象
SqlSession sqlSession = factory.openSession(true);
也可以手动提交:
//5.增删改需要提交事务
sqlSession.commit();
9.4 回显数据
Mapper接口(Dao层):
/**
* 根据id查询
* @param id
* @return
*/
@Select("select * from tb_brand where id = #{id}")
Brand selectById(int id);
Service层:
/**
* 根据id查询
* @param id
* @return
*/
public Brand selectById(int id){
//调用BrandselectAll()
//1.获取SqlSessionFactory对象
SqlSessionFactory factory = SqlSessionFactoryUtils.getSqlSessionFactory();
//2.获取SqlSession对象
SqlSession sqlSession = factory.openSession();
//3.获取BrandMapper对象
BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
//4.调用方法
Brand brand = mapper.selectById(id);
//5.关闭资源
sqlSession.close();
return brand;
}
Web层:
@WebServlet("/selectByIdServlet")
public class SelectByIdServlet extends HttpServlet {
private BrandService service = new BrandService();
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1.接受id
String id = request.getParameter("id");
//2.调用Service查询
Brand brand = service.selectById(Integer.parseInt(id));
//3.存储到request域中
request.setAttribute("brand", brand);
//4.转发到update.jsp中
request.getRequestDispatcher("/update.jsp").forward(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
}
9.5 修改数据
Mapper接口(Dao层):
/**
* 修改操作
* @param brand
*/
@Update("update tb_brand set brand_name = #{brandName}," +
" company_name = #{companyName}," +
" ordered = #{ordered}," +
" description = #{description}," +
" status = #{status} " +
" where id = #{id}")
void update(Brand brand);
Service层:
/**
* 修改
* @param brand
*/
public void update(Brand brand){
//1.获取SqlSessionFactory对象
SqlSessionFactory factory = SqlSessionFactoryUtils.getSqlSessionFactory();
//2.获取sqlSession对象
SqlSession sqlSession = factory.openSession();
//3.获取BrandMapper对象
BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
//4.调用方法
mapper.update(brand);
//5.增删改需要提交事务
sqlSession.commit();
//6.释放资源
sqlSession.close();
}
Web层:
@WebServlet("/updateServlet")
public class UpdateServlet extends HttpServlet {
private BrandService service = new BrandService();
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//解决Post中文乱码问题
request.setCharacterEncoding("utf-8");
//1.接受表单提交的数据并将其封装为一个Brand对象
String id = request.getParameter("id");
String brandName = request.getParameter("brandName");
String companyName = request.getParameter("companyName");
String ordered = request.getParameter("ordered");
String description = request.getParameter("description");
String status = request.getParameter("status");
//封装为Brand对象
Brand brand = new Brand();
brand.setId(Integer.parseInt(id));
brand.setBrandName(brandName);
brand.setCompanyName(companyName);
brand.setOrdered(Integer.parseInt(ordered));//将字符类型转为Int类型
brand.setDescription(description);
brand.setStatus(Integer.parseInt(status));
//2.调用service完成修改操作
service.update(brand);
//3.转发到查询所有Servlet
request.getRequestDispatcher("/selectAllServlet").forward(request,response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
}
brand.jsp:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>修改品牌</title>
</head>
<body>
<h3>修改品牌</h3>
<form action="/brand-demo/updateServlet" method="post">
<%--隐藏域提交id--%>
<input type="hidden" name="id" value="${brand.id}">
品牌名称:<input name="brandName" value="${brand.brandName}"><br>
企业名称:<input name="companyName" value="${brand.companyName}"><br>
排序:<input name="ordered" value="${brand.ordered}"><br>
描述信息:<textarea rows="5" cols="20" name="description" >${brand.description}</textarea><br>
状态:
<c:if test="${brand.status == 0}">
<input type="radio" name="status" value="0" checked>禁用
<input type="radio" name="status" value="1">启用<br>
</c:if>
<c:if test="${brand.status == 1}">
<input type="radio" name="status" value="0" >禁用
<input type="radio" name="status" value="1" checked>启用<br>
</c:if>
<input type="submit" value="提交">
</form>
</body>
</html>
注意:
处理"启用/禁用"状态时使用<c>标签,需要在头部引入
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
通过隐藏域将id传到Servlet中
<%--隐藏域提交id--%>
<input type="hidden" name="id" value="${brand.id}">
9.6 删除数据
Mapper接口(Dao层):
/**
* 删除
* @param id
*/
@Delete("delete from tb_brand where id = #{id}")
void deleteById(int id);
Service层:
/**
* 根据id删除
* @param id
*/
public void deleteById(int id){
//调用BrandselectAll()
//2.获取SqlSession对象
SqlSession sqlSession = factory.openSession();
//3.获取BrandMapper对象
BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
//4.调用方法
mapper.deleteById(id);
//5.提交事务
sqlSession.commit();
//6.关闭资源
sqlSession.close();
}
Web层:
@WebServlet("/deleteByIdServlet")
public class DeleteByIdServlet extends HttpServlet {
private BrandService service = new BrandService();
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//解决Post中文乱码问题
request.setCharacterEncoding("utf-8");
//1.接受表单提交的数据获取id
String id = request.getParameter("id");
//2.调用service完成修改操作
service.deleteById(Integer.parseInt(id));
//3.转发到查询所有Servlet
request.getRequestDispatcher("/selectAllServlet").forward(request,response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
}