用JDBC插入数据有中文乱码问题
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style type="text/css">
.input {
margin-left: 70px;
}
</style>
<script type="text/javascript">
//表单验证
function validate_form() {
//获取课程名的值
var categoryId = document.getElementById("name").value;
if (categoryId == "" || categoryId == null) {
alert("'课程名'不能为空!");
return false;
}
//获取所属方向的值
var categoryId = document.getElementById("category").value;
if (categoryId == "" || categoryId == null) {
alert("'所属方向'不能为空!");
return false;
}
//获取课程描述的值
var categoryId = document.getElementById("desp").value;
if (categoryId == "" || categoryId == null) {
alert(" '课程描述' 不能为空!");
return false;
}
}
</script>
</head>
<body>
<form action="${pageContext.request.contextPath}/AddCourseServlet" onsubmit="return validate_form()" method="post">
<div style="text-align: center; line-height: 30px">
<span style="font-weight: bold">课程添加</span><br> <span
style="width: 70px; display: inline-block">课程名</span> <input
type="text" name="name"><br> <span
style="width: 70px; display: inline-block">所属方向</span> <input
type="text" name="category"><br> <span
style="width: 70px; display: inline-block">课程描述</span> <input
type="text" name="desp"><br>
<div style="margin-left: 50px">
<input type="submit" value=提交>
</div>
</div>
</form>
</body>
</html>
package com.web.servlet;
import java.io.IOException;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.domain.Course;
import com.service.CourseService;
import com.service.impl.CourseImpl;
@WebServlet("/AddCourseServlet")
public class AddCourseServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//接收数据
String name=request.getParameter("name");
String category=request.getParameter("category");
String desp=request.getParameter("desp");
//封装数据
Course course =new Course();
course.setName(name);
course.setCategory(category);
course.setDesp(desp);
//处理数据
CourseService courseService =new CourseImpl();
int num=courseService.addCourse(course);
//显示数据
// if(num>0) {
// response.sendRedirect(request.getContextPath()+"/ShowCourseServlet");
// }
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
package com.service.impl;
import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import com.domain.Course;
import com.service.CourseService;
import com.utils.ConnectionUtil;
public class CourseImpl implements CourseService {
private static final List<Course> COURSES = new ArrayList<>();
public static List<Course> getCourses() {
return COURSES;
}
@Override
public int addCourse(Course course) {
Connection conn = null;
PreparedStatement pstmt = null;
int num = 0;
try {
// 获得连接
conn = ConnectionUtil.getConnection();
// 编写SQL
String sql = "insert into course values(null,?,?,?,?)";
// 预编译SQL
pstmt = conn.prepareStatement(sql);
// 设置参数
pstmt.setString(1, course.getName());
pstmt.setString(2, course.getCategory());
pstmt.setString(3, course.getDesp());
pstmt.setDate(4, new Date(System.currentTimeMillis()));
// 执行SQL
num = pstmt.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
} finally {
ConnectionUtil.release(pstmt, conn);
}
return num;
}
@Override
public void showCourse() {
Connection conn=null;
PreparedStatement pstmt=null;
ResultSet rs=null;
try {
//获得连接
conn=ConnectionUtil.getConnection();
//编写SQL
String sql="select * from course";
//预编译SQL
pstmt=conn.prepareStatement(sql);
//执行SQL
rs=pstmt.executeQuery();
Course course=null;
while(rs.next()) {
int id=rs.getInt("id");
String name=rs.getString("name");
String category=rs.getString("category");
String desp=rs.getString("desp");
String createTime=rs.getString("createTime");
course=new Course(id, name, category, desp, createTime);
System.out.println(course);
COURSES.add(course);
}
} catch (Exception e) {
e.printStackTrace();
}finally {
//释放资源
ConnectionUtil.release(rs, pstmt, conn);
}
}
}
<?xml version="1.0" encoding="UTF-8"?>
<c3p0-config>
<default-config>
<property name="driverClass">com.mysql.jdbc.Driver</property>
<property name="jdbcUrl">jdbc:mysql:///jdbctest?useSSL=false&useUnicode=true&characterEncoding=UTF8&serverTimezone=GMT%2B8</property>
<property name="user">root</property>
<property name="password">root1234</property>
<property name="initialPoolSize">5</property>
<property name="maxPoolSize">20</property>
</default-config>
</c3p0-config>
package com.web.filter;
import java.io.IOException;
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.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class EncodeFilter implements Filter {
public EncodeFilter() {
// TODO Auto-generated constructor stub
}
public void destroy() {
// TODO Auto-generated method stub
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
req.setCharacterEncoding("UTF-8");
HttpServletResponse res = (HttpServletResponse) response;
res.setContentType("text/html;charset=UTF-8");
chain.doFilter(request, response);
}
public void init(FilterConfig fConfig) throws ServletException {
// TODO Auto-generated method stub
}
}
正在回答
同学你好,Servlet中使用JDBC向数据库添加数据,需要先保证Servlet中获取的值是正常不乱码的,同学可以使用如下两句代码设置一下servlet中获取的值的编码:
request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8");
获取值后,同学可以在控制台输出一下,查看获取的值是否乱码。
另外同学需要在数据库中创建表时建议指定编码方式UTF8。
祝学习愉快~
- 参与学习 人
- 提交作业 357 份
- 解答问题 8016 个
本阶段将带你学习MySQL数据库,JDBC接口,MyBatis框架等,带你掌握的数据的存放和管理。
了解课程
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星