JSP入门
JSP语法
Jsp模板元素<html>
脚本片段:<%Java代码必须遵循java的语法规则%>
脚本表达式:<%=表达式>
S声明:<%!声明%>
注释:html注释<!---->jsp<%----%>
JSP工作原理:
1.jsp----------转换成1_jsp.java(httpServlet类)
在_jspService(request,response)中执行
//声明隐藏对象:
FinalPageContextpageContext;
//final修饰的成员变量是最终的不可改变的
//直接赋值或在构造函数中赋值
HttpSessionsession;//一次会话
ServletContextapplication;//web应用程序共享的对象作用于整个web程序
ServletConfigconfig;
JspWriterout;//字节流response.getOurputStream();字符流不能同时使用;
利用jsp向数据库里插数据
<%@pagelanguage="java"import="java.util.*,java.sql.*"pageEncoding="UTF-8"%>
<%
Stringpath=request.getContextPath();
StringbasePath=request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPEHTMLPUBLIC"-//W3C//DTDHTML4.01Transitional//EN">
<html>
<head>
<basehref="<%=basePath%>">
<title>MyJSP'ZhuCe.jsp'startingpage</title>
<metahttp-equiv="pragma"content="no-cache">
<metahttp-equiv="cache-control"content="no-cache">
<metahttp-equiv="expires"content="0">
<metahttp-equiv="keywords"content="keyword1,keyword2,keyword3">
<metahttp-equiv="description"content="Thisismypage">
<!--
<linkrel="stylesheet"type="text/css"href="styles.css">
-->
</head>
<body>
<%!
privatestaticConnectionconn;
privatePreparedStatementpstmt;
privateResultSetrs;
privatestaticfinalStringURL="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(ClassNotFoundExceptione){
//TODOAuto-generatedcatchblock
e.printStackTrace();
}catch(SQLExceptione){
//TODOAuto-generatedcatchblock
e.printStackTrace();
}
}
privatevoidrelease(ResultSetrs,PreparedStatementpstmt){
//TODOAuto-generatedmethodstub
if(rs!=null){
try{
rs.close();
}catch(SQLExceptione){
//TODOAuto-generatedcatchblock
e.printStackTrace();
}
}
if(pstmt!=null){
try{
pstmt.close();
}catch(SQLExceptione){
//TODOAuto-generatedcatchblock
e.printStackTrace();
}
}
}
publicbooleaninsert(Stringname,Stringpass){
booleanflag=false;
Stringsql="insertintouser1(name,pass)VALUE(?,?)";
try{
pstmt=conn.prepareStatement(sql);
intindex=1;
pstmt.setObject(index++,name);
pstmt.setObject(index++,pass);
inti=pstmt.executeUpdate();
if(i>0){
flag=true;
}
release(rs,pstmt);
}catch(SQLExceptione){
//TODOAuto-generatedcatchblock
e.printStackTrace();
}
//TODOAuto-generatedmethodstub
returnflag;
}
%>
<%
Stringname=request.getParameter("uname");
Stringpass=request.getParameter("upass");
this.insert(name,pass);
%>
</body>
</html>