初次使用JSP->建立一个cate表,通过jsp上传信息到数据库
- 新建一个Dynamic Web Application,命名为mvcexample,项目结构大致如***意由于采用Servlet3.0标准,所以web.xml可以没有):
- 新建一个JSP页面,命名为mvc1.jsp:
- 在<body>里面写上如下form表单的代码:
- 由于action为空,表示将表单提交给自己进行处理,那么该JSP代码改为:
- 修改if后面的代码,使用JDBC完成分类名称和分类介绍的存储。
几个注意点:
在工程的lib目录下面加入jar包:mysql-connector-java-5.1.5-bin.jar
- 在最上面添加:<%@ page import="java.sql.*"%>
- 数据库可以命名为photo,表名为cate,其表结构为:
mysql> create database photo;
mysql> use photo
mysql> create table cate(id int primary key auto_increment,name varchar(20) not
null,memo varchar(50) not null);
- 参考代码
详情代码:
<%@ page import="java.sql.*"%>
<%@ 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>
<% request.setCharacterEncoding("utf-8");
String categoryName=request.getParameter("categoryName");
String categoryIntroduce=request.getParameter("categoryIntroduce");
if(categoryName!=null && !categoryName.equals("")){
out.print("分类名字是"+categoryName+"<br>");
out.print("分类介绍是"+categoryIntroduce+"<br>");
if(request.getParameter("submit")!=null){
Connection connection=null;
try{
Class.forName("com.mysql.jdbc.Driver");
String url="jdbc:mysql://localhost:3306/photo?user=root&password=123456";
connection=DriverManager.getConnection(url);}
catch(ClassNotFoundException e){
System.out.println("jdbc driver error");
}
catch(SQLException e){
System.out.println("jdbc connection error");
}
PreparedStatement preStmt=null;
String sql="insert into cate(name,memo) values(?,?)";
preStmt =connection.prepareStatement(sql);
preStmt.setString(1,categoryName);
preStmt.setString(2,categoryIntroduce);
preStmt.executeUpdate();
//connection.close();
}
}else{
%>
<form action="" method="post">
<table>
<tr><td>分类名字</td><td><input type="text" name="categoryName" title="分类名字"/></td></tr>
<tr><td>分类介绍</td><td><textarea cols="40" rows="5" name="categoryIntroduce"></textarea></td></tr>
<tr><td colspan="2"><input type="submit"value="添加" name="submit"/> <input type="reset" value="重置" /></td></tr>
</table>
</form>
<% }%>
</body>
</html>