Spring mvc 实现新闻查询,分类查询
一:分页
导入包
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!--1)spring 以及spring mvc-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.14.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.0.14.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.0.14.RELEASE</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.0.14.RELEASE</version>
</dependency>
<!--2)mysql驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.48</version>
</dependency>
<!-- 3) mybatis-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.4</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.2</version>
</dependency>
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.1.2</version>
</dependency>
<!-- 4) servlet -->
<!-- servlet -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<scope>provided</scope>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jsp-api</artifactId>
<scope>provided</scope>
<version>2.0</version>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
<!-- 5) mbg-->
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.4.0</version>
</dependency>
<!-- 6)log4j-->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.12</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
</dependencies>
在beans-datasoure.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
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx
https://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd
">
<!--1、加载数据库的配置信息 -->
<context:property-placeholder
location="classpath:jdbc.properties" />
<!--2、datasource数据源 -->
<bean id="dataSource"
class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="${driver}" />
<property name="url" value="${url}" />
<property name="username" value="${uName}" />
<property name="password" value="${password}" />
</bean>
<!-- 3、sqlSessionFactory -->
<!-- 3、sqlSessionFactory -->
<bean id="sqlSessionFactory"
class="org.mybatis.spring.SqlSessionFactoryBean">
<!--分页-->
<!-- 别名 -->
<property name="typeAliasesPackage" value="cc.entity"></property>
<!-- mapper XML映射 -->
<property name="mapperLocations" value="classpath*:cc.mapper/*Mapper.xml"></property>
<!-- 数据源 -->
<property name="dataSource" ref="dataSource"></property>
<property name="plugins">
<array>
<bean class="com.github.pagehelper.PageInterceptor">
<!-- 这里的几个配置主要演示如何使用,如果不理解,一定要去掉下面的配置 -->
<property name="properties">
<value>
helperDialect=mysql
reasonable=true
supportMethodsArguments=true
params=count=countSql
autoRuntimeDialect=true
</value>
</property>
</bean>
</array>
</property>
</bean>
<!--4、mapper接口的位置 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="cc.mapper"></property>
</bean>
</beans>
加入beans.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
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx
https://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd
">
<!-- 1、注解扫描 -->
<!-- 2、datasource:mybatis -->
<import resource="beans-datasource.xml"/>
</beans>
加入spring-mvc.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:p="http://www.springframework.org/schema/p"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
https://www.springframework.org/schema/mvc/spring-mvc.xsd
">
<!-- 开启注解扫描 .** 所有所有包以及子包-->
<context:component-scan base-package="cc.**"/>
<!-- 1.处理器映射器 -->
<!--<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"></bean>-->
<!-- 2.处理器适配器 -->
<!--<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"></bean>-->
<!-- 3.试图解析器 -->
<mvc:annotation-driven/>
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- 解析jstl标签 -->
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<!-- 动态页面的前缀 -->
<property name="prefix" value="/WEB-INF/jsp/" />
<!-- 动态页面的后缀 -->
<property name="suffix" value=".jsp" />
</bean>
</beans>
使用generator.xml生成mapper和实体类
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
<context id="testTables" targetRuntime="MyBatis3">
<commentGenerator>
<!-- 是否去除自动生成的注释 true:是 : false:否 -->
<property name="suppressAllComments" value="true" />
</commentGenerator>
<!--数据库连接的信息:驱动类、连接地址、用户名、密码 -->
<jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/t142" userId="root"
password="123456">
</jdbcConnection>
<!-- <jdbcConnection driverClass="oracle.jdbc.OracleDriver"
connectionURL="jdbc:oracle:thin:@127.0.0.1:1521:yycg"
userId="yycg"
password="yycg">
</jdbcConnection> -->
<!-- 默认false,把JDBC DECIMAL 和 NUMERIC 类型解析为 Integer,为 true时把JDBC DECIMAL 和
NUMERIC 类型解析为java.math.BigDecimal -->
<javaTypeResolver>
<property name="forceBigDecimals" value="false" />
</javaTypeResolver>
<!-- targetProject:生成PO类的位置 -->
<javaModelGenerator targetPackage="pojo"
targetProject=".\src">
<!-- enableSubPackages:是否让schema作为包的后缀 -->
<property name="enableSubPackages" value="false" />
<!-- 从数据库返回的值被清理前后的空格 -->
<property name="trimStrings" value="true" />
</javaModelGenerator>
<!-- targetProject:mapper映射文件生成的位置 -->
<sqlMapGenerator targetPackage="cc.mapper"
targetProject=".\src">
<!-- enableSubPackages:是否让schema作为包的后缀 -->
<property name="enableSubPackages" value="false" />
</sqlMapGenerator>
<!-- targetPackage:mapper接口生成的位置 -->
<javaClientGenerator type="XMLMAPPER"
targetPackage="cc.mapper"
targetProject=".\src">
<!-- enableSubPackages:是否让schema作为包的后缀 -->
<property name="enableSubPackages" value="false" />
</javaClientGenerator>
<!--指定数据库表-->
<table tableName="edoc_category"
domainObjectName="Edoc_category"
enableCountByExample="true"
enableDeleteByExample="false"
enableSelectByExample="false"
enableUpdateByExample="false"></table>
<table tableName="edoc_entry"
domainObjectName="Edoc_entry"
enableCountByExample="true"
enableDeleteByExample="false"
enableSelectByExample="false"
enableUpdateByExample="false"></table>
<!--<table tableName="test" domainObjectName="Test" enableCountByExample="false" enableDeleteByExample="false"-->
<!--enableSelectByExample="false" enableUpdateByExample="false"></table>-->
</context>
</generatorConfiguration>
建立service和实现类
package cc.service;
import cc.entity.Edoc_entry;
import java.util.List;
public interface Edoc_entryService {
/**
*
* @Title: list
* @Description: 获取所有用户的所有信息
* @param @return
* @return List<Users>
* @throws
*/
List<Edoc_entry> list();
Edoc_entry selectById(int id);
int update(Edoc_entry edoc_entry);
/*
* 添加用户
* */
int save(Edoc_entry edoc_entry);
/*
* 删除数据
* */
int delete(int id);
List<Edoc_entry> findEntryByCate(int cateId);
}
package cc.service;
import cc.entity.Edoc_category;
import java.util.List;
public interface Edoc_categoryService {
List<Edoc_category> list();
}
package cc.service.impl;
import cc.entity.Edoc_categoryExample;
import cc.entity.Edoc_entry;
import cc.entity.Edoc_entryExample;
import cc.mapper.Edoc_entryMapper;
import cc.service.Edoc_entryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class Edoc_entryServiceImpl implements Edoc_entryService {
@Autowired
private Edoc_entryMapper edoc_entryMapper;
@Override
public List<Edoc_entry> list() {
return edoc_entryMapper.selectByExample(null);
}
@Override
public Edoc_entry selectById(int id) {
return edoc_entryMapper.selectByPrimaryKey(id);
}
@Override
public int update(Edoc_entry edoc_entry) {
return edoc_entryMapper.updateByPrimaryKey(edoc_entry);
}
@Override
public int save(Edoc_entry edoc_entry) {
return edoc_entryMapper.insert(edoc_entry);
}
@Override
public int delete(int id) {
return edoc_entryMapper.deleteByPrimaryKey(id);
}
@Override
public List<Edoc_entry> findEntryByCate(int cateId) {
//1.构建Example
Edoc_entryExample example = new Edoc_entryExample();
//2.根据example构建criteria(条件对象)
Edoc_entryExample.Criteria criteria = example.createCriteria();
//3.设置条件 :categoryId=3
criteria.andCategoryidEqualTo(cateId);
return edoc_entryMapper.selectByExample(example);
}
}
package cc.service.impl;
import cc.entity.Edoc_category;
import cc.mapper.Edoc_categoryMapper;
import cc.service.Edoc_categoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class Edoc_categoryServiceImpl implements Edoc_categoryService{
@Autowired
private Edoc_categoryMapper edoc_categoryMapper;
@Override
public List<Edoc_category> list() {
return edoc_categoryMapper.selectByExample(null);
}
}
Mapper文件中,加入查询集合的方法
package cc.mapper;
import cc.entity.Edoc_entry;
import cc.entity.Edoc_entryExample;
import java.util.List;
public interface Edoc_entryMapper {
int deleteByPrimaryKey(Integer id);
int insert(Edoc_entry record);
int insertSelective(Edoc_entry record);
Edoc_entry selectByPrimaryKey(Integer id);
int updateByPrimaryKeySelective(Edoc_entry record);
int updateByPrimaryKey(Edoc_entry record);
List<Edoc_entry> selectByExample(Edoc_entryExample example);
}
package cc.mapper;
import cc.entity.Edoc_category;
import cc.entity.Edoc_categoryExample;
import java.util.List;
public interface Edoc_categoryMapper {
int deleteByPrimaryKey(Integer id);
int insert(Edoc_category record);
int insertSelective(Edoc_category record);
Edoc_category selectByPrimaryKey(Integer id);
int updateByPrimaryKeySelective(Edoc_category record);
int updateByPrimaryKey(Edoc_category record);
List<Edoc_category> selectByExample(Edoc_categoryExample example);
}
并修改mapper.xml
<select id="selectByExample" parameterType="cc.entity.Edoc_entryExample" resultMap="BaseResultMap">
select
<if test="distinct">
distinct
</if>
<include refid="Base_Column_List" />
from edoc_entry
<if test="_parameter != null">
<include refid="Example_Where_Clause" />
</if>
<if test="orderByClause != null">
order by ${orderByClause}
</if>
</select>
<select id="selectByExample" parameterType="cc.entity.Edoc_categoryExample" resultMap="BaseResultMap">
select
<if test="distinct">
distinct
</if>
<include refid="Base_Column_List" />
from edoc_category
<if test="_parameter != null">
<include refid="Example_Where_Clause" />
</if>
<if test="orderByClause != null">
order by ${orderByClause}
</if>
</select>
写入Controller
package cc.web;
import cc.entity.Edoc_category;
import cc.entity.Edoc_entry;
import cc.service.Edoc_categoryService;
import cc.service.Edoc_entryService;
import com.github.pagehelper.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import java.util.List;
@Controller
@RequestMapping("/edoc_entry")
public class Edoc_entryController {
@Autowired
private Edoc_entryService edoc_entryService;
@Autowired
private Edoc_categoryService edoc_categoryService;
@ModelAttribute(value = "categories")
public List<Edoc_category> getCategories(){
List<Edoc_category> categories = edoc_categoryService.list();
return categories;
}
@RequestMapping(value = "/list")
public ModelAndView list() {
// public ModelAndView list() {
ModelAndView mv = new ModelAndView();
//1.调用用户的service层的方法获取所有用户所有数据
List<Edoc_entry> edoc_entries = edoc_entryService.list();
//2.将数据绑定mv上
mv.addObject("edoc_entries", edoc_entries);
//3.设置视图
mv.setViewName("edoc_entry/list");
//4.放回mv
return mv;
}
@RequestMapping("/to_edit")
public ModelAndView toUpdate(int id) {
System.out.println("====进入toUpdate===id=>" + id);
ModelAndView mv = new ModelAndView();
//1.查询该用户的所有信息 web--servcice-maper-数据
Edoc_entry edoc_entry = edoc_entryService.selectById(id);
//2.将该用户数据绑定到mv
mv.addObject("edoc_entry", edoc_entry);
//3.将修改页面的jsp名称绑定到mv中
mv.setViewName("edoc_entry/edit");
//4.返回mv
return mv;
}
@RequestMapping(value = "/update", method = RequestMethod.POST)
public ModelAndView update(Edoc_entry edoc_entry) {
System.out.println("====进入update===user=" + edoc_entry);
ModelAndView mv = new ModelAndView();
//1.调用service更新用户信息
int result = edoc_entryService.update(edoc_entry);
//2.绑定视图
if (result > 0) {//更新成功
//重定向 ,edoc_entry/list的映射的list()方法,再由list()跳转到edoc_entry/list.jsp
mv.setViewName("redirect:../edoc_entry/list");
} else {//更新失败
}
//3.返回mv
return mv;
}
@RequestMapping("/to_add")
public String toAdd() {
return "edoc_entry/add";
}
@RequestMapping(value = "/add", method = RequestMethod.POST)
public String add(Edoc_entry edoc_entry) {
System.out.println("====进入add===edoc_entry=" + edoc_entry);
//1.调用service添加用户信息方法
int result = edoc_entryService.save(edoc_entry);
//2.绑定视图
if (result > 0) {//更新成功
//重定向 ,edoc_entry/list的映射的list()方法,再由list()跳转到edoc_entry/list.jsp
return "redirect:../edoc_entry/list";
} else {//更新失败
return "error";
}
}
@RequestMapping("/delete")
public String delete(@RequestParam("tid") int tid) {
System.out.println("====进入delete===userId=" + tid);
//1.调用service添加用户信息方法
int result = edoc_entryService.delete(tid);
//2.绑定视图
if (result > 0) {//更新成功
//重定向 ,user/list的映射的list()方法,再由list()跳转到user/list.jsp
return "redirect:../edoc_entry/list";
} else {//更新失败
return "error";
}
}
//根据分类id获取对应的所有电子文档
@RequestMapping("/entrys")
public String entrysByCate(Model model , int cateId){
//1.调用service获取该分类的电子文档
List<Edoc_entry> edoc_entries = edoc_entryService.findEntryByCate(cateId);
//2.绑定到model
model.addAttribute("edoc_entries",edoc_entries);
//3.跳转到页面
return "edoc_entry/template";
}
}
最后将jsp页面写好
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" %>
<%@taglib uri="http://java.sun.com/jstl/fmt_rt" prefix="fmt" %>
<%@taglib uri="http://java.sun.com/jstl/core_rt" prefix="c" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/edoc_entry/add" method="post">
<table border="1" align="center" width="50%" height="100px">
<tr>
<th>文档类型</th>
<th>文档名称</th>
<th>文档摘要</th>
<th>上传人</th>
<th>上传人时间</th>
</tr>
<tr align="center">
<tr align="center">
<td><div style="width:400px;margin: 0px auto;">
<p>
<select name="categoryid">
<c:forEach items="${categories}" var="categories1">
<option value="${categories1.id}">${categories1.name}</option>
</c:forEach>
</select>
</p>
</div></td>
<td><input type="text" name="title"/> </td>
<td><input type="text" name="summary"/> </td>
<td><input type="text" name="uploaduser"/> </td>
<td>
<!-- html5 中新增的标签:日期标签 -->
<input type="date" name="createdate"
value="<fmt:formatDate value='' pattern='yyyy-MM-dd'/>"/>
</td>
</tr>
</tr>
<tr>
<td colspan="4" align="center">
<input type="submit" value="增加"/>
</td>
</tr>
</table>
</form>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@taglib uri="http://java.sun.com/jstl/fmt_rt" prefix="fmt"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/edoc_entry/update" method="post">
<table border="1" align="center" width="50%" height="100px">
<tr>
<th>文档编号</th>
<th>文档名称</th>
<th>文档摘要</th>
<th>上传人</th>
<th>上传人时间</th>
</tr>
<tr align="center">
<td><input value="${edoc_entry.id}" name="id" readonly="readonly"/></td>
<td><input type="text" name="title" value="${edoc_entry.title }"/> </td>
<td><input type="text" name="summary" value="${edoc_entry.summary }"/> </td>
<td><input type="text" name="uploaduser" value="${edoc_entry.uploaduser }"/> </td>
<td>
<!-- html5 中新增的标签:日期标签 -->
<input type="date" name="createdate"
value="<fmt:formatDate value='${edoc_entry.createdate}' pattern='yyyy-MM-dd'/>"/>
</td>
</tr>
<tr>
<td colspan="5" align="center">
<input type="submit" value="更新"/>
</td>
</tr>
</table>
</form>
</body>
</html>
<%--
Created by IntelliJ IDEA.
User: Administrator
Date: 2020/12/23 0023
Time: 11:13
To change this template use File | Settings | File Templates.
--%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" %>
<%@page isELIgnored="false" %>
<%@taglib uri="http://java.sun.com/jstl/core_rt" prefix="c" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%@taglib uri="http://java.sun.com/jstl/fmt_rt" prefix="fmt" %>
<html>
<head>
<title>Title</title>
<script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
$("#searchBtn").click(function(){
// alert(1);
//1.获取用户选择的分类
var cateId = $("#name1").val();
//2.根据id获取所有分类电子文档
$.ajax({
type: "GET",
url: "http://localhost:8080/edoc_entry/entrys",
data: "cateId="+cateId,
success: function(bookList){
//alert( "Data Saved: " + bookList );
$("#book_list").html(bookList);
}
});
});
})
</script>
</head>
<body>
<div style="width:400px;margin: 0px auto;">
<p>文档分类
<select id="name1">
<c:forEach items="${categories}" var="categories1">
<option value="${categories1.id}">${categories1.name}</option>
</c:forEach>
</select>
<button id="searchBtn">查询</button>
</p>
</div>
<%--<form action="${pageContext.request. contextPath}/user/delBatch">--%>
<table width="80%" border="1">
<thead>
<tr>
<%--<th><input type="checkbox" id="totalCheck" /> </th>--%>
<th>文档编号</th>
<th>文档名称</th>
<th>文档摘要</th>
<th>上传人</th>
<th>上传人时间</th>
<th>操作</th>
</tr>
</thead>
<tbody id="book_list">
<c:forEach items="${edoc_entries}" var="entries">
<tr>
<th>${entries.id}</th>
<th>${entries.title}</th>
<th>${entries.summary }</th>
<th>${entries.uploaduser}</th>
<th><fmt:formatDate value='${entries.createdate}' pattern='yyyy-MM-dd'/></th>
<th>
<a href="${pageContext.request. contextPath}/edoc_entry/to_edit?id=${entries.id}">修改</a>
<a href="${pageContext.request. contextPath}/edoc_entry/to_add">增加</a>
<a href="javascript:doDel('http://localhost:8080/edoc_entry/delete?tid=${entries.id}')">删除</a>
<%--<a href="javascript:remove('http://localhost:8080/user/delete/${user.id}')">删除(rest)</a>--%>
</th>
</tr>
</c:forEach>
</tbody>
</table>
<%--</form>--%>
<script type="text/javascript">
function doDel(url) {
if (confirm("确定删除吗?")) {
location.href = url;
}
}
</script>
</body>
</html>
<%--
Created by IntelliJ IDEA.
User: mr.chan
Date: 2020-12-24
Time: 14:30
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@page isELIgnored="false" %>
<%@taglib prefix="c" uri="http://java.sun.com/jstl/core_rt" %>
<%@taglib uri="http://java.sun.com/jstl/fmt_rt" prefix="fmt" %>
<html>
<head>
<title>异步加载模板</title>
</head>
<body>
<c:forEach items="${edoc_entries}" var="entries">
<tr>
<th>${entries.id}</th>
<th>${entries.title}</th>
<th>${entries.summary }</th>
<th>${entries.uploaduser}</th>
<th><fmt:formatDate value='${entries.createdate}' pattern='yyyy-MM-dd'/></th>
<th>
<a href="${pageContext.request. contextPath}/edoc_entry/to_edit?id=${entries.id}">修改</a>
<a href="${pageContext.request. contextPath}/edoc_entry/to_add">增加</a>
<a href="javascript:doDel('http://localhost:8080/edoc_entry/delete?tid=${entries.id}')">删除</a>
<%--<a href="javascript:remove('http://localhost:8080/user/delete/${user.id}')">删除(rest)</a>--%>
</th>
</tr>
</c:forEach>
</body>
</html>
注意:web.xml文件是最开始就执行的,所以要记得写
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">
<!--一、spring的ioc容器配置 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:beans.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 三、spring的编码过滤器 -->
<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>
<!-- 二、中央处理器(DispatcherServlet):映射器、适配器、视图解析器 -->
<servlet>
<servlet-name>app</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-mvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>app</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
</web-app>
还要,实体类里面有Date类型的要加入注释
@DateTimeFormat(pattern = "yyyy-MM-dd")
private Date createdate;
并加入DateHandlerMethodArgumentResolver和MyDate接口
package cc.annotation;
import java.lang.annotation.*;
//该注解只能在哪里使用 (方法参数上)
//Type注解只能使用在类上
//Method注解只能能用方法上
//PARAMETER 只能用在方法参数上
@Target(ElementType.PARAMETER)
//运行策略 (一般RUNTIME)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface MyDate {
String[] params() default ""; /*从网页中获取到的日期绑定哪个参数属性上*/
String pattern() default "yyyy-MM-dd HH:mm:ss";/*默认的日期格式*/
}
package cc.annotation.support;
import cc.annotation.MyDate;
import org.springframework.beans.BeanUtils;
import org.springframework.core.MethodParameter;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
import javax.servlet.http.HttpServletRequest;
import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.text.SimpleDateFormat;
/**
* jsp(表单---string)==========>servlet(request.getParameter()--手动将jsp获取的string实体类中属性参数类型)
* @ClassName: DateHandlerMethodArgumentResolver
* @Description: TODO
* @author 新梦想IT学院.陈超
* @date 2020年12月22日
*
*/
public class DateHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver {
private String[] params; /*属性*/
private String pattern; /*日期的格式*/
/**
* MethodParameter:controller的方法参数对象
*/
@Override
public boolean supportsParameter(MethodParameter parameter) {
//1、判断controller方法上是否有MyDate注解
boolean hasParameterAnnotation = parameter.hasParameterAnnotation(MyDate.class);
if (!hasParameterAnnotation) {
//不会进入下面的resolveArgument方法进行参数的解析
return false;
}
//2、获取Date注解对象
MyDate parameterAnnotations = parameter.getParameterAnnotation(MyDate.class);
//3、获取Date注解的params参数
String[] parameters = parameterAnnotations.params();
if (!StringUtils.isEmpty(parameters)) {
params = parameters;
//4.获取Date注解的pattern参数
pattern = parameterAnnotations.pattern();
//进入下面的resolveArgument方法进行参数的解析
return true;
}
return false;
}
@Override
public Object resolveArgument(MethodParameter methodParam, ModelAndViewContainer mavContainer,
NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
//1.获取controller方法参数Users user的类型对象
Object object = BeanUtils.instantiateClass(methodParam.getParameterType());
//2.获取参数类型对象的类信息(Users类的属性和方法)
BeanInfo beanInfo = Introspector.getBeanInfo(object.getClass());
//3.获取请求对象Request
HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);
//4.获取Users类类型对象的所有属性描述(获取Users类的所有属性)
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
//5.得到每个属性的名字(Users类的属性名),并根据属性名称得到请求参数的值
String value = request.getParameter(propertyDescriptor.getName());
//6.判断非空
if (!StringUtils.isEmpty(value)) {
//5.得到属性的set方法
Method writeMethod = propertyDescriptor.getWriteMethod();
//6.如果set方法为非公有方法,暴力破解
if (!Modifier.isPublic(writeMethod.getModifiers())) {
writeMethod.setAccessible(true);
}
//7.判断属性名是否为Date指定的params值,如果是params指定值 则进行日期转换
if (propertyDescriptor.getName().equals(params[0])) {//日期属性
SimpleDateFormat sdf = new SimpleDateFormat(this.pattern);
java.util.Date date = sdf.parse(value);
//调用setBirthday(date)
writeMethod.invoke(object, date);
} else {//非日期的属性
//属性类型为Integer
if(propertyDescriptor.getPropertyType().equals(Integer.class)) {
writeMethod.invoke(object, Integer.parseInt(value));
//属性类型为字符串
}else {
writeMethod.invoke(object, value);
}
}
}
}
return object;
}
}
浙公网安备 33010602011771号