自定义MVC增删改查

目录

一、搭建自定义MVC框架环境

1.将框架导成jar包,然后导入新工程,并且将框架的依赖jar包导入

 2.将分页标签相关文件、以及相关助手类导入,框架的配置文件添加以及web.xml的配置

二、基础的增删改

 三、通用的增删改

 四、查询删除及重复表单提交问题

五、新增修改的前端实现


一、搭建自定义MVC框架环境

1.将框架导成jar包,然后导入新工程,并且将框架的依赖jar包导入

如图:导出自己的jar包

 

 

 取个名字

 找到该jar包,放入新建项目的lib下,该包为核心包

再导入其他依赖包

 

 2.将分页标签相关文件、以及相关助手类导入,框架的配置文件添加以及web.xml的配置

 配置中央控制器的.xml的坏境

web.xml的源码

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
  <display-name>T280_mvc_crud</display-name>
  <servlet>
  	<servlet-name>mvc</servlet-name>
  	<servlet-class>com.cdl.framework.DispatcherServlet</servlet-class>
 	<init-param>
 		<param-name>configLocation</param-name>
 		<param-value>/wuyanzu</param-value>
 	</init-param>
  </servlet>
  <servlet-mapping>
  	<servlet-name>mvc</servlet-name>
  	<url-pattern>*.action</url-pattern>
  </servlet-mapping>
</web-app>

将助手类一级tld的配置文件拿过来,如图结构

 注意:目前所有的包的内容均再通用分页的博客中有

以后的开元框架都从这一步开始

二、基础的增删改

建一个com.cdl.entity的包,里面放实体类

Book

package com.cdl.entity;

public class Book {
	private int bid;
	private String bname;
	private float price;

	@Override
	public String toString() {
		return "Book [bid=" + bid + ", bname=" + bname + ", price=" + price + "]";
	}

	public int getBid() {
		return bid;
	}

	public void setBid(int bid) {
		this.bid = bid;
	}

	public String getBname() {
		return bname;
	}

	public void setBname(String bname) {
		this.bname = bname;
	}

	public float getPrice() {
		return price;
	}

	public void setPrice(float price) {
		this.price = price;
	}
	
	public Book() {
		// TODO Auto-generated constructor stub
	}

	public Book(int bid, String bname, float price) {
		this.bid = bid;
		this.bname = bname;
		this.price = price;
	}

	
	
}

在com.cdl.dao中写一个bookdao

package com.cdl.dao;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.cdl.entity.Book;
import com.cdl.util.BaseDao;
import com.cdl.util.CallBack;
import com.cdl.util.DBAccess;
import com.cdl.util.PageBean;
import com.cdl.util.StringUtils;
import com.mysql.jdbc.PreparedStatement;

public class BookDao extends BaseDao<Book>{
	
	//查询
	public List<Book> list(Book book,PageBean pageBean) throws Exception{
		String sql  = "select * from t_mvc_book where 1=1 ";
		String bname = book.getBname();
		if(StringUtils.isNotBlank(bname)) {
			sql += " and bname like '%"+bname+"%' ";
		}
		int bid = book.getBid();
//		前台jsp传递到后台,只要传了就有值,没传就是默认值,默认值就是0
		if(bid != 0) {
			sql += " and bid = "+bid;
		}
		return super.executeQuery(sql, pageBean, rs -> {
			List<Book> list = new ArrayList<Book>();
			try {
				while(rs.next()) {
					list.add(new Book(rs.getInt("bid"), rs.getString("bname"), rs.getFloat("price")));
				}
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return list;
		});
	}
	
//	增
	public int add(Book book) throws Exception {
		Connection con = DBAccess.getConnection();
		String sql = "insert into t_mvc_book values(?,?,?)";
		java.sql.PreparedStatement pst = con.prepareStatement(sql);
		pst.setObject(1, book.getBid());
		pst.setObject(2, book.getBname());
		pst.setObject(3, book.getPrice());
		return pst.executeUpdate();
	}
	
//	删
	public int del(Book book) throws Exception {
		Connection con = DBAccess.getConnection();
		String sql = "delete from t_mvc_book where bid=?";
		java.sql.PreparedStatement pst = con.prepareStatement(sql);
		pst.setObject(1, book.getBid());
		return pst.executeUpdate();
	}
	
//	改
	public int edit(Book book) throws Exception {
		Connection con = DBAccess.getConnection();
		String sql = "update t_mvc_book set bname=?,price=?  where bid=?";
		java.sql.PreparedStatement pst = con.prepareStatement(sql);
		pst.setObject(3, book.getBid());
		pst.setObject(1, book.getBname());
		pst.setObject(2, book.getPrice());
		return pst.executeUpdate();
	}
	
	
	
}

在当前类,快捷键ctrl+n,输入junit,建立一个测试类

package com.cdl.dao;

import static org.junit.Assert.*;

import java.util.List;

import org.junit.Test;

import com.cdl.entity.Book;
import com.cdl.util.PageBean;

public class BookDaoTest {
	
	private BookDao  bookDao = new BookDao();
	
	
	@Test
	public void testList() {
		try {
			List<Book> list = bookDao.list(new Book(), new PageBean());
			for (Book book : list) {
				System.out.println(book);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Test
	public void testAdd() {
		new Book(123,"asdf",4567);
	}

	@Test
	public void testDel() {
		Book book2 = new Book(123,"8989",4567);
		try {
			bookDao.del(book2);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Test
	public void testEdit() {
		Book book2 = new Book(123,"8989",4567);
		try {
			bookDao.edit(book2);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}

运行结果:

 三、通用的增删改

BaseDao

package com.cdl.util;

import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import com.cdl.entity.Book;

/**
 * T代表是实体类,可以是book user goods...
 * 
 * @author 陈冬丽
 *
 * @param <T>
 */
public class BaseDao<T> {
	/*public List<T> executeQuery(String sql,PageBean pageBean,CallBack<T> callBack) throws Exception{
		//**
		 * 1.拿到数据库连接
		 * 2.拿到域定义对象(preparestatement)
		 * 3.执行SQL语句
		 *//*
		Connection con = DBAccess.getConnection();//连接对象 //重复代码1
		java.sql.PreparedStatement pst = con.prepareStatement(sql );//执行对象 //重复代码2
		ResultSet rs = pst.executeQuery();//重复代码3
		while(rs.next()){
			//实例化并且赋值加入集合中去
			list.add(new Book(rs.getInt("bid"), rs.getString("bname"), rs.getFloat("price")));
		}
		return list;
		//查询不同的表,必然要处理不同的结果集
//		接口是调用放来实现
		return callBack.foreach(rs);
	}*/
	
	
	public List<T> executeQuery(String sql,PageBean pageBean,CallBack<T> callBack) throws Exception{
//		select * from t_mvc_book where bname like '%圣墟%';
//		从上面得到  select count(1) as n from (select * from t_mvc_book where bname like '%圣墟%') t;
//		目的是为了得到总记录数->得到总页数
//		select * from t_mvc_book where bname like '%圣墟%' limit 10,10;
		/*
		  1.拿到数据库连接
		  2.拿到域定义对象(preparestatement)
		  3.执行SQL语句*/
			 
		Connection con = null;//连接对象 //重复代码1
		java.sql.PreparedStatement pst = null;//执行对象 //重复代码2
		ResultSet rs = null;//重复代码3
		
		if(pageBean !=null && pageBean.isPagination()) {//分页
			String countSQL = getCountSQL(sql);
			con = DBAccess.getConnection();//连接对象 //重复代码1
			 pst = con.prepareStatement(countSQL);//执行对象 //重复代码2
			 rs = pst.executeQuery();//重复代码3
			 if(rs.next()) {
//				 pageBean包含了当前实体类的总记录数
				 pageBean.setTotal(rs.getString("n"));
			 }
			 String pageSQL = getPageSQL(sql,pageBean);
			 con = DBAccess.getConnection();//连接对象 //重复代码1
			 pst = con.prepareStatement(pageSQL);//执行对象 //重复代码2
			 rs = pst.executeQuery();//重复代码3
		}
		else {//不分页
			con = DBAccess.getConnection();//连接对象 //重复代码1
			pst = con.prepareStatement(sql);//执行对象 //重复代码2
			rs = pst.executeQuery();//重复代码3
		}
		
		return callBack.foreach(rs);
		}

	/**
	 * 拼装第n页的数据
	 * 
	 * @param sql
	 * @param pageBean
	 * @return
	 */
	private String getPageSQL(String sql, PageBean pageBean) {
		return sql+" limit "+pageBean.getStartIndex()+","+pageBean.getRows();
	}
	
	/**
	 * 拼装符合条件总记录数的SQL
	 * @param sql
	 * @return
	 */
	private String getCountSQL(String sql) {
//		select * from t_mvc_book where bname like '%圣墟%';
//		从上面得到  select count(1) as n from (select * from t_mvc_book where bname like '%圣墟%') t;
		return "select count(1) as n from ("+sql+") t";
	}
	
	public int executeUpdate(String sql,T t,String[] attrs) throws Exception {
		Connection con = DBAccess.getConnection();
		java.sql.PreparedStatement pst = con.prepareStatement(sql);
//		将t 的某一个属性对应的值加到pst 对象中
		for (int i = 0; i < attrs.length; i++) {
			Field f = t.getClass().getDeclaredField(attrs[i]);
			f.setAccessible(true);
			pst.setObject(i + 1,f.get(t));
		}
		return pst.executeUpdate();
	}
	
}

BookDao

package com.cdl.dao;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.cdl.entity.Book;
import com.cdl.util.BaseDao;
import com.cdl.util.CallBack;
import com.cdl.util.DBAccess;
import com.cdl.util.PageBean;
import com.cdl.util.StringUtils;
import com.mysql.jdbc.PreparedStatement;

public class BookDao extends BaseDao<Book>{
	
	//查询
	public List<Book> list(Book book,PageBean pageBean) throws Exception{
		String sql  = "select * from t_mvc_book where 1=1 ";
		String bname = book.getBname();
		if(StringUtils.isNotBlank(bname)) {
			sql += " and bname like '%"+bname+"%' ";
		}
		int bid = book.getBid();
//		前台jsp传递到后台,只要传了就有值,没传就是默认值,默认值就是0
		if(bid != 0) {
			sql += " and bid = "+bid;
		}
		return super.executeQuery(sql, pageBean, rs -> {
			List<Book> list = new ArrayList<Book>();
			try {
				while(rs.next()) {
					list.add(new Book(rs.getInt("bid"), rs.getString("bname"), rs.getFloat("price")));
				}
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return list;
		});
	}
	
//	增
//	public int add(Book book) throws Exception {
//		Connection con = DBAccess.getConnection();
//		String sql = "insert into t_mvc_book values(?,?,?)";
//		java.sql.PreparedStatement pst = con.prepareStatement(sql);
//		pst.setObject(1, book.getBid());
//		pst.setObject(2, book.getBname());
//		pst.setObject(3, book.getPrice());
//		return pst.executeUpdate();
//	}
	public int add(Book book) throws Exception {
		String sql = "insert into t_mvc_book values(?,?,?)";
		return super.executeUpdate(sql, book, new String[] {"bid","bname","price"});
	}
	
	
//	删
//	public int del(Book book) throws Exception {
//		Connection con = DBAccess.getConnection();
//		String sql = "delete from t_mvc_book where bid=?";
//		java.sql.PreparedStatement pst = con.prepareStatement(sql);
//		pst.setObject(1, book.getBid());
//		return pst.executeUpdate();
//	}
	public int del(Book book) throws Exception {
		String sql = "delete from t_mvc_book where bid=?";
		return super.executeUpdate(sql, book, new String[] {"bid"});
	}
	
	
//	改
//	public int edit(Book book) throws Exception {
//		Connection con = DBAccess.getConnection();
//		String sql = "update t_mvc_book set bname=?,price=?  where bid=?";
//		java.sql.PreparedStatement pst = con.prepareStatement(sql);
//		pst.setObject(3, book.getBid());
//		pst.setObject(1, book.getBname());
//		pst.setObject(2, book.getPrice());
//		return pst.executeUpdate();
//	}
	public int edit(Book book) throws Exception {
		String sql = "update t_mvc_book set bname=?,price=?  where bid=?";
		return super.executeUpdate(sql, book, new String[] {"bname","price","bid"});
	}
	
	
	
}

BookDaoTest

package com.cdl.dao;

import static org.junit.Assert.*;

import java.util.List;

import org.junit.Test;

import com.cdl.entity.Book;
import com.cdl.util.PageBean;

public class BookDaoTest {
	
	private BookDao  bookDao = new BookDao();
	
	
	@Test
	public void testList() {
		try {
			List<Book> list = bookDao.list(new Book(), new PageBean());
			for (Book book : list) {
				System.out.println(book);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Test
	public void testAdd() {
		Book book = new Book(123,"asdf",4567);
		try {
			bookDao.add(book);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Test
	public void testDel() {
		Book book2 = new Book(123,"8989",4567);
		try {
			bookDao.del(book2);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Test
	public void testEdit() {
		Book book2 = new Book(123,"8989",4567);
		try {
			bookDao.edit(book2);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}

运行增加

 四、查询删除及重复表单提交问题

建一个com.cdl.web

BookAction

package com.cdl.web;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.cdl.dao.BookDao;
import com.cdl.entity.Book;
import com.cdl.framework.ActionSupport;
import com.cdl.framework.ModelDriven;
import com.cdl.util.PageBean;

public class BookAction extends ActionSupport implements ModelDriven<Book>{

	private Book book = new Book();
	private BookDao bookDao = new BookDao();
	
	
	@Override
	public Book getModel() {
		// TODO Auto-generated method stub
		return book;
	}
	
//	增
	public String add(HttpServletRequest req,HttpServletResponse resp) {
		try {
			bookDao.add(book);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
//		代表跳到查询界面
		return "toList";
	}
	
//	删
	public String del(HttpServletRequest req,HttpServletResponse resp) {
		try {
			bookDao.del(book);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
//		代表跳到查询界面
		return "toList";
	}
	
//	改
	public String edit(HttpServletRequest req,HttpServletResponse resp) {
		try {
			bookDao.edit(book);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
//		代表跳到查询界面
		return "toList";
	}
	
//	查
	public String list(HttpServletRequest req,HttpServletResponse resp) {
		try {
			PageBean pageBean = new PageBean();
			pageBean.setRequest(req);
			List<Book> list = bookDao.list(book, pageBean);
			req.setAttribute("list", list);
			req.setAttribute("pageBean", pageBean);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
//		执行查询
		return "list";
	}
	
//	跳转到新增/修改界面
	public String preEdit(HttpServletRequest req,HttpServletResponse resp) {
		try {
			int bid = book.getBid();
			if(bid != 0) {
//				传递bid到后台,有且只能查出一条数据,意味着list集合中也只有一条
				List<Book> list = bookDao.list(book, null);
				req.setAttribute("b", list.get(0));
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
//		代表跳到编辑界面
		return "toEdit";
	}
	
}

wuyanzu.xml

<?xml version="1.0" encoding="UTF-8"?>
<config>
	<action path="/book" type="com.cdl.web.BookAction">
		<forward name="list" path="/bookList.jsp" redirect="false" />
		<forward name="toEdit" path="/bookEdit.jsp" redirect="false" />
		<forward name="toList" path="/book.action?methodName=list" redirect="false" />
	</action>
	
</config>

bookList.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link
	href="css/bootstrap.css"
	rel="stylesheet"> 
<script  src="js/bootstrap.js"></script>
<title>书籍列表</title>
<style type="text/css">
.page-item input {
	padding: 0;
	width: 40px;
	height: 100%;
	text-align: center;
	margin: 0 6px;
}

.page-item input, .page-item b {
	line-height: 38px;
	float: left;
	font-weight: 400;
}

.page-item.go-input {
	margin: 0 10px;
}
</style>
</head>
<body>
	 <form class="form-inline"
		action="${pageContext.request.contextPath }/book.action?methodName=list" method="post">
		<div class="form-group mb-2">
			<input type="text" class="form-control-plaintext" name="bname"
				placeholder="请输入书籍名称">
		</div>
		<button type="submit" class="btn btn-primary mb-2">查询</button>
	</form>

	<table class="table table-striped">
		<thead>
			<tr>
				<th scope="col">书籍ID</th>
				<th scope="col">书籍名</th>
				<th scope="col">价格</th>
			</tr>
		</thead>
		<tbody>
		<c:forEach items="${list}" var="book">
			<tr>
				<td>${book.bid}</td>
				<td>${book.bname}</td>
				<td>${book.price}</td>
			</tr>
		</c:forEach>

		</tbody>
	</table>
	
	<z:page pageBean="${pageBen}"></z:page> 

</body>
</html>

 bookList.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link
	href="css/bootstrap.css"
	rel="stylesheet"> 
<script  src="js/bootstrap.js"></script>
<title>书籍列表</title>
<style type="text/css">
.page-item input {
	padding: 0;
	width: 40px;
	height: 100%;
	text-align: center;
	margin: 0 6px;
}

.page-item input, .page-item b {
	line-height: 38px;
	float: left;
	font-weight: 400;
}

.page-item.go-input {
	margin: 0 10px;
}
</style>
</head>
<body>
	 <form class="form-inline"
		action="${pageContext.request.contextPath }/book.action?methodName=list" method="post">
		<div class="form-group mb-2">
			<input type="text" class="form-control-plaintext" name="bname"
				placeholder="请输入书籍名称">
		</div>
		<button type="submit" class="btn btn-primary mb-2">查询</button>
	</form>

	<table class="table table-striped">
		<thead>
			<tr>
				<th scope="col">书籍ID</th>
				<th scope="col">书籍名</th>
				<th scope="col">价格</th>
				<th scope="col">操作</th>
			</tr>
		</thead>
		<tbody>
		<c:forEach items="${list}" var="book">
			<tr>
				<td>${book.bid}</td>
				<td>${book.bname}</td>
				<td>${book.price}</td>
				<td>
					<a href="${pageContext.request.contextPath}/book.action?methodName=preEdit?bid=${book.bid}">编辑</a>
					<a href="${pageContext.request.contextPath}/book.action?methodName=del?bid=${book.bid}">删除</a>
				</td>
			</tr>
		</c:forEach>

		</tbody>
	</table>
	
	<z:page pageBean="${pageBean}"></z:page> 

</body>
</html>

效果图:

 当点击删除后

 因为地址栏将参数又带回去了

将wuyanzu.xml的配置的提交方式改变

<?xml version="1.0" encoding="UTF-8"?>
<config>
	<action path="/book" type="com.cdl.web.BookAction">
		<forward name="list" path="/bookList.jsp" redirect="false" />
		<forward name="toEdit" path="/bookEdit.jsp" redirect="false" />
		<forward name="toList" path="/book.action?methodName=list" redirect="true" />
	</action>
	
</config>

五、新增修改的前端实现

新增界面

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
	<form action="${pageContext.request.contextPath }/book.action?methodName=${empty b ? 'add' : 'edit'}" method="post">
		bid:<input type="text" name="bid" value="${b.bid}">
		bname:<input type="text" name="bname" value="${b.bname}">
		price:<input type="text" name="price" value="${b.price}">
		<input type="submit" vaule="提交">
	</form>
</body>
</html>

效果:

此时的bookList.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link
	href="css/bootstrap.css"
	rel="stylesheet"> 
<script  src="js/bootstrap.js"></script>
<title>书籍列表</title>
<style type="text/css">
.page-item input {
	padding: 0;
	width: 40px;
	height: 100%;
	text-align: center;
	margin: 0 6px;
}

.page-item input, .page-item b {
	line-height: 38px;
	float: left;
	font-weight: 400;
}

.page-item.go-input {
	margin: 0 10px;
}
</style>
</head>
<body>
	 <form class="form-inline"
		action="${pageContext.request.contextPath }/book.action?methodName=list" method="post">
		<div class="form-group mb-2">
			<input type="text" class="form-control-plaintext" name="bname"
				placeholder="请输入书籍名称">
		</div>
		<button type="submit" class="btn btn-primary mb-2">查询</button>
		<a class="btn btn-primary mb-2"  href="${pageContext.request.contextPath}/book.action?methodName=preEdit">新增</a>
	</form>

	<table class="table table-striped">
		<thead>
			<tr>
				<th scope="col">书籍ID</th>
				<th scope="col">书籍名</th>
				<th scope="col">价格</th>
				<th scope="col">操作</th>
			</tr>
		</thead>
		<tbody>
		<c:forEach items="${list}" var="book">
			<tr>
				<td>${book.bid}</td>
				<td>${book.bname}</td>
				<td>${book.price}</td>
				<td>
					<a href="${pageContext.request.contextPath}/book.action?methodName=preEdit?bid=${book.bid}">编辑</a>
					<a href="${pageContext.request.contextPath}/book.action?methodName=del?bid=${book.bid}">删除</a>
				</td>
			</tr>
		</c:forEach>

		</tbody>
	</table>
	
	<z:page pageBean="${pageBean}"></z:page> 

</body>
</html>

 注意:过滤器

package com.cdl.util;
 
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
 
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
/**
 * 中文乱码处理
 * 
 */
@WebFilter("*.action")
public class EncodingFiter implements Filter {
 
	private String encoding = "UTF-8";// 默认字符集
 
	public EncodingFiter() {
		super();
	}
 
	public void destroy() {
	}
 
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse res = (HttpServletResponse) response;
 
		// 中文处理必须放到 chain.doFilter(request, response)方法前面
		res.setContentType("text/html;charset=" + this.encoding);
		if (req.getMethod().equalsIgnoreCase("post")) {
			req.setCharacterEncoding(this.encoding);
		} else {
			Map map = req.getParameterMap();// 保存所有参数名=参数值(数组)的Map集合
			Set set = map.keySet();// 取出所有参数名
			Iterator it = set.iterator();
			while (it.hasNext()) {
				String name = (String) it.next();
				String[] values = (String[]) map.get(name);// 取出参数值[注:参数值为一个数组]
				for (int i = 0; i < values.length; i++) {
					values[i] = new String(values[i].getBytes("ISO-8859-1"),
							this.encoding);
				}
			}
		}
 
		chain.doFilter(request, response);
	}
 
	public void init(FilterConfig filterConfig) throws ServletException {
		String s = filterConfig.getInitParameter("encoding");// 读取web.xml文件中配置的字符集
		if (null != s && !s.trim().equals("")) {
			this.encoding = s.trim();
		}
	}
 
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值