jsp实现textarea中的文字保存换行空格存到数据库的方法

随心笔谈9个月前发布 admin
78 0


<%@page import=”java.io.PrintWriter”%>
<%@page import=”java.net.URLDecoder”%>
<%@ page language=”java” contentType=”text/html; charset=utf-8″
pageEncoding=”utf-8″ %>
<%@ page import=”java.sql.*” %>
<!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; utf-8″>
<title>上传新闻</title>
</head>
<body>
<%! // 字符处理函数 换行符变成<br>
public String turn(String str) {
while (str.indexOf(“\n”) !=-1) {
str=str.substring(0, str.indexOf(“\n”)) + “<br>”
+ str.substring(str.indexOf(“\n”) + 1);
}
while (str.indexOf(” “) !=-1) {
str=str.substring(0, str.indexOf(” “)) + ” ”
+ str.substring(str.indexOf(” “) + 1);
}
return str;
}
%>
<%
try {
request.setCharacterEncoding(“utf-8”);
String title=request.getParameter(“title”);
String author=request.getParameter(“author”);
String article=request.getParameter(“articleName”);
String articlebr=turn(article);
String date=request.getParameter(“date”);
String driverClass=”com.mysql.jdbc.Driver”;
String url=”jdbc:mysql:/****?characterEncoding=utf8″;//存到数据库不会乱码
String user=”***”;
String password=”****”;
Connection conn;
int i=0;
Class.forName(driverClass).newInstance();
conn=DriverManager.getConnection(url,user,password);
String sql=”insert into news (id,title,author,article,date) ”
+ “values(?,?,?,?,?)”;
Connection conn1=DriverManager.getConnection(url, user, password);
PreparedStatement pstmt;
pstmt=(PreparedStatement) conn1.prepareStatement(sql);
pstmt.setString(1, null);
pstmt.setString(2, title);
pstmt.setString(3, author);
pstmt.setString(4, articlebr);
pstmt.setString(5, date);
i=pstmt.executeUpdate();
conn1.close();
pstmt.close();
out.println(“<br>上传成功”);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
%>
</body>
</html>

© 版权声明

相关文章