JSP入门
JSP语法
Jsp模板元素 <html>
脚本片段:<% Java代码 必须遵循java的语法规则%>
脚本表达式:<%=表达式>
S声明:<%! 声明 %>
注释: html注释 <!-- --> jsp<%-- --%>
JSP工作原理:
1.jsp----------转换成 1_jsp.java(httpServlet类)
在_jspService(request,response)中执行
//声明隐藏对象:
Final PageContext pageContext;
//final 修饰的成员变量是最终的不可改变的
//直接赋值 或在构造函数中赋值
HttpSession session;//一次会话
ServletContext application;//web应用程序共享的对象 作用于整个web程序
ServletConfig config;
JspWriter out;//字节流 response.getOurputStream(); 字符流 不能同时使用;
利用jsp向数据库里插数据
<%@ page language="java" import="java.util.*,java.sql.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'ZhuCe.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<%!
private static Connection conn;
private PreparedStatement pstmt;
private ResultSet rs;
private static final String URL="jdbc:mysql://localhost:3306/3g?user=root&password=211314&useUnicode=true&characterEncoding=UTF-8";
static{
try {
Class.forName("com.mysql.jdbc.Driver");
conn=DriverManager.getConnection(URL);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void release(ResultSet rs, PreparedStatement pstmt) {
// TODO Auto-generated method stub
if(rs!=null){
try {
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(pstmt!=null){
try {
pstmt.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public boolean insert(String name,String pass) {
boolean flag=false;
String sql="insert into user1 (name,pass) VALUE (?,?)";
try {
pstmt=conn.prepareStatement(sql);
int index=1;
pstmt.setObject(index++,name);
pstmt.setObject(index++,pass);
int i=pstmt.executeUpdate();
if(i>0){
flag=true;
}
release(rs, pstmt);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// TODO Auto-generated method stub
return flag;
}
%>
<%
String name=request.getParameter("uname");
String pass=request.getParameter("upass");
this.insert(name,pass);
%>
</body>
</html>