javaweb jdbc实现简单的数据库基本操作和servlet的作用域以及jsp标签的使用
一,工具类,分页类和连接数据库jdbc
package com.direct.util; import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException; public class ConnCreate {
private static final String DRIVER="com.mysql.jdbc.Driver";
private static final String URL="jdbc:mysql://localhost:3306/countryside_buy?userUnicode=true&characterEncoding=utf-8";
private static final String USER="root";
private static final String PWD="123456";
static{
try {
Class.forName(DRIVER);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
//创建连接对象
public Connection createConn(){
Connection conn = null;
try {
conn = DriverManager.getConnection(URL, USER, PWD);
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
} //关闭连接
public void closeJ(Connection conn,PreparedStatement ps,ResultSet rs) throws SQLException{
if(rs!=null) rs.close();
if(ps!=null) ps.close();
if(conn!=null) conn.close();
} }
package com.direct.util; import java.io.Serializable;
import java.util.ArrayList; public class JavaBeanPage<T> implements Serializable { /*
* javaBean 定义分页模型 泛型
*/
private int pagesize=3;//每页显示的条数
private int pageno=1;//当前页码
private int totalrecords;//总数据条数
private int totalpage;
private ArrayList<T> datalist = null;//当前页的数据 public int getPagesize() {
return pagesize;
}
public void setPagesize(int pagesize) {
this.pagesize = pagesize;
}
public int getPageno() {
return pageno;
}
public void setPageno(int pageno) {
this.pageno = pageno;
}
public int getTotalrecords() {
return totalrecords;
}
public void setTotalrecords(int totalrecords) {
this.totalrecords = totalrecords;
}
public int getTotalpage() {
return totalpage;
}
// 设置总页数 总数据/每页条数
public void setTotalpage() {
if (totalrecords%pagesize==0) {
this.totalpage = totalrecords/pagesize;
}else {
this.totalpage = totalrecords/pagesize+1;
}
}
public ArrayList<T> getDatalist() {
return datalist;
}
public void setDatalist(ArrayList<T> datalist) {
this.datalist = datalist;
}
public JavaBeanPage(int pagesize, int pageno, int totalrecords,
int totalpage, ArrayList<T> datalist) {
super();
this.pagesize = pagesize;
this.pageno = pageno;
this.totalrecords = totalrecords;
this.totalpage = totalpage;
this.datalist = datalist;
}
public JavaBeanPage() {
super();
} }
二,dao层对数据的连接和对数据的基本操作
package com.direct.dao; import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Map; import com.direct.entity.User;
import com.direct.util.ConnCreate;
import com.direct.util.JavaBeanPage; public class UserJdbc { //从数据中用sql语句分页,得到每页的显示数据集合对象
public JavaBeanPage<User> getlist(Map<String, Object> map){
JavaBeanPage<User> page = new JavaBeanPage<User>();
page.setPageno(Integer.parseInt((String) map.get("pageno"))); //设置当前页码
// page.setPagesize((Integer)map.get("pagesize")); //设置每页显示的数据数量 page.setTotalrecords(getCount());//设置总数据条数
page.setTotalpage();//设置总页数
/* ArrayList<User> datalist = page.getDatalist();
System.out.println(datalist.get(0)); */
ConnCreate connCreate = new ConnCreate();
Connection conn = connCreate.createConn();
PreparedStatement ps = null;
ResultSet rs =null;
// 查询起始位置 (当前页数-1)*每页显示的条数
int begin =(page.getPageno() -1)*page.getPagesize();
//查询每页显示条数
int end = page.getPagesize();
String sql = "select * from user limit "+begin+" , "+end;
ArrayList<User> list = new ArrayList<User>();//临时存放user对象,最后传入page中的集合 try {
ps = conn.prepareStatement(sql);
rs = ps.executeQuery();
while (rs.next()) {
User user= new User(rs.getInt("user_id"),
rs.getString("user_name"),
rs.getString("user_email"),
rs.getString("user_password"),
rs.getString("user_telphone"),
rs.getInt("user_status"),
rs.getString("user_sex"));
//System.out.println(user);
list.add(user);
}
page.setDatalist(list); } catch (SQLException e) {
e.printStackTrace();
}finally{
try {
connCreate.closeJ(conn, ps, rs);
} catch (SQLException e) {
e.printStackTrace();
}
} return page;
} //访问数据库得到数据的总条数
public int getCount(){
ConnCreate connCreate = new ConnCreate();
Connection conn = connCreate.createConn();
PreparedStatement ps = null;
ResultSet rs =null;
int count=0;
String sql = "select count(user_id) as count from user";
try {
ps = conn.prepareStatement(sql);
rs = ps.executeQuery();
while (rs.next()) {
count= rs.getInt("count");
}
// System.out.println("总数据条数:"+count); } catch (SQLException e) {
e.printStackTrace();
}finally{
try {
connCreate.closeJ(conn, ps, null);
} catch (SQLException e) {
e.printStackTrace();
}
} return count;
} public ArrayList<User> qurey(String name,String pwd){
ConnCreate connCreate = new ConnCreate();
Connection conn = connCreate.createConn();
StringBuffer sql=new StringBuffer("select * from user where 1=1");
ArrayList<User> uList=new ArrayList<User>();
PreparedStatement ps = null;
ResultSet rs = null;
if (name!=null&&!("").equals(name)&&pwd!=null&&!("").equals(pwd)) {
sql.append(" and user_name='"+name+"'");
sql.append(" and user_password='"+pwd+"'"); try {
ps= conn.prepareStatement(sql.toString());
rs = ps.executeQuery();
while (rs.next()) {
User user= new User(rs.getInt("user_id"),
rs.getString("user_name"),
rs.getString("user_email"),
rs.getString("user_password"),
rs.getString("user_telphone"),
rs.getInt("user_status"),
rs.getString("user_sex"));
uList.add(user);
//System.out.println("list添加一个对象");
}
} catch (SQLException e) {
e.printStackTrace();
}finally{
try {
connCreate.closeJ(conn, ps, rs);
} catch (SQLException e) {
e.printStackTrace();
}
}
}
return uList;
}
//参数列表不同,不同的调用,应该用重载
public ArrayList<User> qurey(String name,int id){
ConnCreate connCreate = new ConnCreate();
Connection conn = connCreate.createConn();
StringBuffer sql=new StringBuffer("select * from user where 1=1");
ArrayList<User> uList=new ArrayList<User>();
PreparedStatement ps = null;
ResultSet rs = null;
if(name!=null&&!("").equals(name)){
sql.append(" and user_name='"+name+"'");
}else if(id!=0){
sql.append(" and user_id='"+id+"'");
}
try {
ps= conn.prepareStatement(sql.toString());
rs = ps.executeQuery();
while (rs.next()) {
User user= new User(rs.getInt("user_id"),
rs.getString("user_name"),
rs.getString("user_email"),
rs.getString("user_password"),
rs.getString("user_telphone"),
rs.getInt("user_status"),
rs.getString("user_sex"));
uList.add(user);
System.out.println("list添加一个对象");
}
} catch (SQLException e) {
e.printStackTrace();
}finally{
try {
connCreate.closeJ(conn, ps, rs);
} catch (SQLException e) {
e.printStackTrace();
}
}
return uList;
} //增
public Boolean addUsers(User uent){
Boolean bool = false;
ConnCreate connCreate = new ConnCreate();
Connection conn = connCreate.createConn();
PreparedStatement ps = null;
String sql = "insert into user(user_name,user_email,user_password,user_telphone,user_status,user_sex) values(?,?,?,?,?,?)";
try {
ps = conn.prepareStatement(sql);
ps.setString(1, uent.getUname());
ps.setString(2, uent.getUemail());
ps.setString(3, uent.getUpwd());
ps.setString(4, uent.getUtel());
ps.setInt(5, uent.getUsatus());
ps.setString(6, uent.getUsex());
int temp = ps.executeUpdate();
if (temp>0) {
System.out.println("添加成功!!!");
bool = true;
}
} catch (SQLException e) {
e.printStackTrace();
}finally{
try {
connCreate.closeJ(conn, ps, null);
} catch (SQLException e) {
e.printStackTrace();
}
}
return bool;
}
// 改
public Boolean changeUser(int id,User uent){
Boolean bool = false;
ConnCreate connCreate = new ConnCreate();
Connection conn = connCreate.createConn();
PreparedStatement ps=null;
//update user set user_name=?,user_email=?,user_password=?,user_telphone=?,user_sex=? where name ='star'
StringBuffer sql = new StringBuffer("update user set user_name=?,user_email=?,user_password=?,user_telphone=?,user_sex=? where user_id= '"+id+"'");
try {
ps = conn.prepareStatement(sql.toString());
ps.setString(1, uent.getUname());
ps.setString(2, uent.getUemail());
ps.setString(3, uent.getUpwd());
ps.setString(4, uent.getUtel());
ps.setString(5, uent.getUsex());
int rows = ps.executeUpdate();
if(rows>0){
System.out.println("修改成功!!!");
bool=true;
}
} catch (SQLException e) {
e.printStackTrace();
}finally{
try {
connCreate.closeJ(conn, ps, null);
} catch (SQLException e) {
e.printStackTrace();
}
}
return bool;
}
//删
public Boolean deleteUser(int id){
Boolean bool = false;
ConnCreate connCreate = new ConnCreate();
Connection conn = connCreate.createConn();
PreparedStatement ps = null;
String sql = "delete from user where user_id='"+id+"'";
try {
ps = conn.prepareStatement(sql);
int rows = ps.executeUpdate();
if (rows>0) {
System.out.println("删除成功!!!");
bool = true;
}
} catch (SQLException e) {
e.printStackTrace();
}finally{
try {
connCreate.closeJ(conn, ps, null);
} catch (SQLException e) {
e.printStackTrace();
}
}
return bool;
} /* public static void main(String[] args) {
ArrayList<User> list = new UserJdbc().qurey("小白","123456");
System.out.println(list.size()); User user = new User(1, "小蓝", "nn147552384@163.com", "435256", "13996932845", 0, "女");
new UserJdbc().addUsers(user);
System.out.println(new UserJdbc().getCount());
//new UserJdbc().getlist();
}*/
}
三,service层的接受前台数据和响应
package com.direct.servlet; import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map; import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession; import com.direct.dao.UserJdbc;
import com.direct.entity.User;
import com.direct.util.JavaBeanPage; public class UserServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
} public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("utf-8");// 设置字符编码
response.setContentType("text/html;charset=utf-8");// 设置输出内容的类型及字符编码
response.setCharacterEncoding("utf-8"); /*
* 三种作用域
* request 一次请求 只能用forward转换页面
* session 一次会话 在浏览器中可以访问,关闭浏览器重开不能
* application 一直 关闭浏览器后在打开,访问得到 (一般用于网站访问人数的数据)
*/
String username = request.getParameter("username");// 获取值 表单值
String[] values = request.getParameterValues("hobby");// 获取数组 表单复选框
String hob = "";
for (int i = 0; i < values.length; i++) {
hob+=values[i]+",";
} HttpSession session = request.getSession();
session.setAttribute("sname", "dgdfhhh");
session.setAttribute("spwd", "fugfgh");
session.setMaxInactiveInterval(10);//设置最大存在时间 单位秒
session.invalidate();//销毁
session.removeAttribute("sname");//移除存放的值 ServletContext application = this.getServletContext();
application.setAttribute("aname", "fyjhjhgjfk");
application.setAttribute("apwd", "dfjgfhdf"); /*
* 内部跳转 请求转发 forward() 一次请求 外部跳转 重定向 sendRedirect() 两次请求
*/
// request.getRequestDispatcher("MyJsp.jsp").forward(request, response);
PrintWriter out = response.getWriter();// 返回PrintWriter 输出流对象
// out.print("sdfniodg");//响应给前台
// response.sendRedirect("MyJsp.jsp");// 重定向跳转页面
String op = request.getParameter("op"); if(("page").equals(op)){
//op=page&pageno=1
String pageno = request.getParameter("pageno");//当前页码
System.out.println(pageno+"pageno");
Map< String, Object> map = new HashMap<String, Object>();
map.put("pageno", pageno);
//map.put("pagesize", 3);
UserJdbc userJdbc = new UserJdbc();
JavaBeanPage<User> pagelist = userJdbc.getlist(map);
request.setAttribute("nowdate", new Date());//存入当前时间
request.setAttribute("pagelist", pagelist);//存入request属性值
//request.getRequestDispatcher("pagelist.jsp").forward(request, response);
request.getRequestDispatcher("jstl.jsp").forward(request, response);
} else {
System.out.println("--------------else----------");
} } }
四,jsp页面取数据和显示的几种方式
jstl中 c 标签和 fmt 标签的简单使用。和实现真分页。以及el表达式的简单运用
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<%
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 'jstl.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>
<table cellpadding="0" cellspacing="0" width="50%" align="center">
<tr> <th>编号</th>
<th>ID</th>
<th>用户名</th>
<th>邮件</th>
<th>电话</th>
<th>密码</th>
<th>性别</th>
</tr>
<c:forEach items="${pagelist.datalist}" var="item" varStatus="status">
<tr>
<td>${status.index }</td>
<td>${item.uid }</td>
<td>${item.uname }</td>
<td>${item.uemail }</td>
<td> ${item.utel }</td>
<td>${item.upwd }</td>
<td>${item.usex }</td>
</tr>
</c:forEach> <tr>
<td></td>
<td>当前页:${pagelist.pageno } /总页数:${pagelist.totalpage }</td>
<td><a href="UserServlet?op=page&pageno=1"> 首页</a></td>
<td><a href="UserServlet?op=page&pageno=${pagelist.pageno>1?pagelist.pageno-1:pagelist.pageno}">上一页</a></td>
<td><a href="UserServlet?op=page&pageno=${pagelist.pageno<pagelist.totalpage?pagelist.pageno+1:pagelist.totalpage}">下一页</a></td>
<td><a href="UserServlet?op=page&pageno=${pagelist.totalpage }">尾页</a></td>
</tr>
</table>
<c:set value="99" var="score"></c:set>
成绩:<c:out value="${score}"></c:out>
<c:if test="${score>80}">成绩很优秀 </c:if><br/>
<c:set value="6" var="grade" ></c:set>
<select name="grade">
<c:choose>
<c:when test="${grade==1}">
<option value="1">倔强青铜</option>
</c:when>
<c:when test="${grade==2}">
<option value="2">秩序白银</option>
</c:when>
<c:when test="${grade==3}">
<option value="3">荣耀黄金</option>
</c:when>
<c:when test="${grade==4}">
<option value="4">尊贵铂金</option>
</c:when>
<c:when test="${grade==5}">
<option value="5">永恒钻石</option>
</c:when>
<c:otherwise >
<option >王者</option>
</c:otherwise>
</c:choose>
</select>
<br/>
<c:set value="语文,数学,英语,C++,C#,JAVA,PHP" var="subject" scope="session"></c:set>
<c:forTokens items="${subject}" delims="," begin="0" end="2" var="ke">
<c:out value="${ke}"></c:out><br/>
</c:forTokens>
<br/>
当前时间:<fmt:formatDate value="${nowdate}" pattern="yyyy年MM月dd日 HH:mm:ss"/>
<br/>
<h3>数字格式化:</h3>
<c:set var="balance" value="120000.2309" />
<p>格式化数字 (1): <fmt:formatNumber value="${balance}"
type="currency"/></p>
<p>格式化数字 (2): <fmt:formatNumber type="number"
maxIntegerDigits="3" value="${balance}" /></p>
<p>格式化数字 (3): <fmt:formatNumber type="number"
maxFractionDigits="3" value="${balance}" /></p>
<p>格式化数字 (4): <fmt:formatNumber type="number"
groupingUsed="false" value="${balance}" /></p>
<p>格式化数字 (5): <fmt:formatNumber type="percent"
maxIntegerDigits="3" value="${balance}" /></p>
<p>格式化数字 (6): <fmt:formatNumber type="percent"
minFractionDigits="10" value="${balance}" /></p>
<p>格式化数字 (7): <fmt:formatNumber type="percent"
maxIntegerDigits="3" value="${balance}" /></p>
<p>格式化数字 (8): <fmt:formatNumber type="number"
pattern="###.###E0" value="${balance}" /></p>
<p>美元 :
<fmt:setLocale value="en_US"/>
<fmt:formatNumber value="${balance}" type="currency"/></p>
<hr/>
<%--el表达式的使用:
等于:== eq
不等于:!= ne
大于等于:>= ge
小于等于:<= le
小于:< lt
大于:> gt
逻辑与: && and
逻辑或: || or
逻辑非: ! not
是否为空:empty
--%>
总条数:${requestScope.pagelist.totalrecords }<br/>
等于:${pagelist.pageno eq pagelist.pagesize }<br/>
不等于:${pagelist.pageno ne pagelist.pagesize }<br/>
</body>
</html>
jstl中标签的使用,c,fmt,functions。
服务器开启后,直接访问本页面即可
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn"%>
<%
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 'jstlApply.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>
<!-- 1根据不同年龄段 判断人群类别。 少年 青年 …….. (多种方式实现)
2使用forTokens 拆分遍历数据。(blue,red,green|yellow|pink,black|white)
3获得时间:格式化输出年 月 日 时 分 秒 AM /PM
4得到一个数字 已不同的方式输出为金额格式 (美元 人民币)
-->
<c:set value="25" var="age"></c:set>
<c:out value="${age}"></c:out><br/>
<hr/>
c:choose和c:when方式:
<c:choose>
<c:when test="${age<=10}">儿童</c:when>
<c:when test="${age<=30&&age>10}">青年</c:when>
<c:when test="${age<=50&&age>30}">中年</c:when>
<c:when test="${age>50}">老年</c:when>
</c:choose><br/>
c:if方式:
<c:if test="${age<=10}">儿童</c:if>
<c:if test="${age<=30&&age>10}">青年</c:if>
<c:if test="${age<=50&&age>30}">中年</c:if>
<c:if test="${age>50}">老年</c:if><br/>
<hr/>
<c:set value="blue,red,green|yellow|pink,black|white" var="str"></c:set>
原字符串:<c:out value="${str}"></c:out><br/>
c:forTokens:
<c:forTokens items="${str}" delims="," var="color">
<c:forTokens items="${color}" delims="|" var="co">
${co}
</c:forTokens>
</c:forTokens>
<hr/>
<c:set value="<%=new Date() %>" var="nowdate"></c:set><br/>
<fmt:formatDate value="${nowdate}" pattern="yyyy年MM月dd日 HH:mm:ss a" var="date"/>
fmt:formatDate:<c:out value="${date}"></c:out><br/>
<c:set value="3568" var="num"></c:set>
fmt:formatNumber:
<fmt:formatNumber type="currency" value="${num}" ></fmt:formatNumber><br/>
<fmt:formatNumber currencySymbol="$" value="${num}"></fmt:formatNumber><br/>
<fmt:formatNumber currencyCode="$" value="${num}"></fmt:formatNumber><br/>
<!-- jstl函数:使用
5 判断字符串A中是否有存在子串B (忽略大小写/不忽略大小写);
6 集合中装有多个字符串,遍历 输出以指定字符结尾的 字符串;
7集合中装有多个字符串,输出不同字符串中指定字符出现的位置。
8将多个字符串 拼接为一个字符串。
9截取返回 字符串 指定范围、 之前、 之后的内容。
10字符串的替换操作。
-->
<% String str1 = "javascripet";
String str2 = "vAsc";
ArrayList liststr = new ArrayList();
liststr.add("bluejstl");
liststr.add("redjstld");
liststr.add("yelllowjstl");
liststr.add("blackjstla");
liststr.add("bluejstl");
request.setAttribute("liststr",liststr);
%>
jstl:function<br/>
${fn:contains(str1,str2) }<br/>
${fn:containsIgnoreCase(str1,str2) }<br/>
endsWith:
<c:forEach items="${liststr}" var="strl" varStatus="status">
${status.index}
${strl}
${fn:endsWith(strl, "jstl")} <%="," %><br/>
</c:forEach><br/>
indexOf: <c:forEach items="${liststr}" var="strof">
${strof}
${fn:indexOf(strof, 'j')}
<%="," %>
</c:forEach><br/>
<hr/>
<c:set var="string1" value="I am from google"/>
<c:set var="string2" value="${fn:replace(string1, 'google', 'runoob')}" />
<p>replace替换后的字符串 : ${string2}</p>
<hr/>
<c:set var="string1" value="www runoob com"/>
<c:set var="string2" value="${fn:split(string1, ' ')}" />
<%
String[] arr = {"This","is","array","string"};
request.setAttribute("arr",arr);
%>
<c:set value="${arr}" var="array"></c:set>
arr使用join连接: ${fn:join(array,'-') }
<c:set var="string3" value="${fn:join(string2, '-')}" /><!-- string2是字符串数组 -->
<p>字符串为 : ${string3}</p>
<c:set var="string4" value="This is first String."/>
<c:set var="string5" value="${fn:substring(string4, 5, 15)}" />
<p>生成的子字符串为 : ${string5}</p>
<c:set var="string6" value="${fn:substringAfter(string4, 'is')}" />
<p>After生成的子字符串 : ${string6}</p>
<c:set var="string7" value="${fn:substringBefore(string4, 'first')}" />
<p>Before生成的子字符串 : ${string7}</p> </body>
</html>
五,web.xml中的配置,以及使用配置文件实现初始化数据
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<servlet>
<description>This is the description of my J2EE component</description>
<display-name>This is the display name of my J2EE component</display-name>
<servlet-name>UserServlet</servlet-name>
<servlet-class>com.direct.servlet.UserServlet</servlet-class>
</servlet> <servlet-mapping>
<servlet-name>UserServlet</servlet-name>
<url-pattern>/UserServlet</url-pattern>
</servlet-mapping> <servlet>
<servlet-name>config_jsp</servlet-name>
<jsp-file>/config.jsp</jsp-file>
<init-param>
<param-name>configFile</param-name>
<param-value>confi.txt配置文件的信息</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>config_jsp</servlet-name>
<url-pattern>/conf.jsp</url-pattern>
</servlet-mapping> <welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
六,web.xml 中初始化的数据在发布服务器后可直接访问取数据
config.jsp
访问 http://localhost:8082/webProject/conf.jsp
<%@ page language="java" import="java.util.*" 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 'config.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> 配置文件名:<%=config.getInitParameter("configFile") %>
</body>
</html>
javaweb jdbc实现简单的数据库基本操作和servlet的作用域以及jsp标签的使用的更多相关文章
- springmvc学习笔记三:整合JDBC,简单案例==数据库事务配置(切面)
package cn.itcast.bean; import org.springframework.jdbc.core.PreparedStatementSetter; public class U ...
- JavaWeb -JDBC使用(数据库-javaweb连接)
使用JDBC四个大类 1. DriverManager:管理jdbc驱动 2. Connection:连接(通过DriverManager产生) 3. Statement/PreparedStatem ...
- 通过JDBC进行简单的增删改查(以MySQL为例)
目录 前言:什么是JDBC 一.准备工作(一):MySQL安装配置和基础学习 二.准备工作(二):下载数据库对应的jar包并导入 三.JDBC基本操作 (1)定义记录的类(可选) (2)连接的获取 ( ...
- 通过JDBC进行简单的增删改查
通过JDBC进行简单的增删改查(以MySQL为例) 目录 前言:什么是JDBC 一.准备工作(一):MySQL安装配置和基础学习 二.准备工作(二):下载数据库对应的jar包并导入 三.JDBC基本操 ...
- Javaweb 第5天 mysql 数据库课程
MySQL数据库课程 两日大纲 ● 数据库的概念.MySQL快速入门.SQL语言简介 ● 数据库操作.表操作.数据记录操作.数据类型和约束 ● 查询 ● 多表关系.多表连接查询 ● 视图 ● 数据备份 ...
- 通过JDBC进行简单的增删改查(以MySQL为例) 目录
通过JDBC进行简单的增删改查(以MySQL为例) 目录 前言:什么是JDBC 一.准备工作(一):MySQL安装配置和基础学习 二.准备工作(二):下载数据库对应的jar包并导入 三.JDBC基本操 ...
- Java通过JDBC进行简单的增删改查(以MySQL为例)
Java通过JDBC进行简单的增删改查(以MySQL为例) 目录: 前言:什么是JDBC 一.准备工作(一):MySQL安装配置和基础学习 二.准备工作(二):下载数据库对应的jar包并导入 三.JD ...
- JDBC进行简单的增删改查
一.准备工作(一):MySQL安装配置和基础学习 二.准备工作(二):下载数据库对应的jar包并导入 三.JDBC基本操作 (1)定义记录的类(可选) (2)连接的获取 (3)insert (4)up ...
- JAVA使用JDBC连接,修改MySQL数据库(比较乱)
原文地址1(连接MySQL图文) : http://www.cnblogs.com/GarfieldEr007/p/5746137.html 原文地址2 (修改MySQL图文): http://www ...
随机推荐
- Android多媒体整体架构图
Android多媒体整体架构图 MediaPlayer框架图 Camera框架图 SoundRecorder框架图 VideoCamera框架图 OpenCore与Skia ALSA Audio框架图 ...
- Lora通信解决方案对比
欢迎大家进群交流分享:QQ群:773082801
- JSP知识汇总
JSP知识汇总 一.简介 > HTML - HTML擅长显示一个静态的网页,但是不能调用Java程序. > Servlet - Servlet擅长调用Java程序和后台进行交互,但是它不擅 ...
- 【GDKOI2017】小队任务 莫比乌斯反演+杜教筛
题目大意:给你n,求$\sum_{i=1}^{n}\sum_{j=i}^{n}[gcd(i,j)=1](i+1)(j+1)$ 子任务一:暴力 子任务二:$T=50000,n≤10^7$ 子任务三:$T ...
- DIV居中的几种方法
1. body{ text-align:center; } 缺点:body内所有内容一并居中 2. .center{ position: fixed; left: 50%; } 缺点:需要设置posi ...
- syslog之一:Linux syslog日志系统详解
目录: <syslog之一:Linux syslog日志系统详解> <syslog之二:syslog协议及rsyslog服务全解析> <syslog之三:建立Window ...
- Hadoop HDFS概念学习系列之HDFS升级和回滚机制(十二)
不多说,直接上干货! HDFS升级和回滚机制 作为一个大型的分布式系统,Hadoop内部实现了一套升级机制,当在一个集群上升级Hadoop时,像其他的软件升级一样,可能会有新的bug或一些会影响现有应 ...
- pycharm的python console报错CE.app/Contents/helpers/pydev/_pydev_bundle/pydev_ipython_console_011.py", line 87, in init self.matchers.remove(self.python_matches) ValueError: list.remove(x): x not in list
卸载ipython pip uninstall ipython 安装ipython6.2.0 pip install ipython==6.2.0
- 自然语言处理--TF-IDF(关键词提取)
TF-IDF算法 TF-IDF(词频-逆文档频率)算法是一种统计方法,用以评估一字词对于一个文件集或一个语料库中的其中一份文件的重要程度.字词的重要性随着它在文件中出现的次数成正比增加,但同时会随着它 ...
- ThreadPool线程池的关注点
public class TestThreadPool { //线程池维护线程的最少数量 private static final int COREPOOLSIZE = 2; //线程池维护线程的最大 ...