html(doPost/doGet)--->servlet(导航逻辑)--->bean(表示逻辑)--->业务类--->数据库;
数据库--->业务类--->bean(表示逻辑)--->servlet(导航逻辑)--->jsp.
jsp,一种页面技术,
javabean,一种可以利用反射的技术
servlet,一种接收处理请求的技术
jsp在运行的时候是先编译成servlet再执行的,servlet根javabean都是先要编译成class字节码文件才能执行的。jsp是将 script根html混合在一起的,适合做小型的或者扩展要求不高的系统,大一点的要求有扩展性的系统可以将javabean结合起来,将一些常用的功 能封装在里面,可以节省劳力,而且将来扩展相对容易,再大一些的系统就需要将servlet结合起来用了,servlet侧重在流程控制,jsp里面由于 可以直接用html,故侧重表示,javabean就侧重封装逻辑功能,比如数据库访问等。
executeQuery的返回值是一个数据的结果集 ResultSet
executeUpdate的返回值是成功更新数据的行数
1.当要执行的sql语句为select语句,则应该用executeQuery
2.当要执行的sql语句是insert,update,delete和dll语句,则应该用executeUpdate
//跳转到servlet
response.sendRedirect("list"); //http://localhost:8080/Shop/admin/list
//跳转到jsp
response.sendRedirect("test.jsp"); //http://localhost:8080/Shop/admin/list
//转发
request.setAttribute("pagediv", pagediv);
RequestDispatcher dispatcher=request.getRequestDispatcher("goodsList.jsp");
dispatcher.forward(request, response);
--------------------------------------------JDBC实例 Statement,PreparedStatement,CallableStatement三个方法的实例
Statement
|
PreparedStatement
|
CallableStatement
Statement用于执行一条普通的动态SQL语句,PreparedStatement用于执行预编译好的SQL语句,CallableStatement用于调用数据库的存储过程。他们的继承关系如上。
---- 1 Statement
stmt = conn.createStatement();
rs = stmt.executeQuery("select * from goods LIMIT "+fpage+" , "+pageSize+" ");
while(rs.next()){
Good good = new Good(rs.getString("id"),rs.getString("nnn"));
result.add(good);
}
stmt = conn.createStatement();
stmt.executeUpdate("delete from goods where id="+id);
---- 2 CallableStatement
pstm=con.prepareStatement("select * from Goods where GoodsID=?");
pstm.setString(1, goodsID);
rs=pstm.executeQuery();
while(rs.next()){
Goods goods=new Goods(rs.getString("goodsID"),rs.getString("goodsName"));
destroy();
return goods;
}
pstm=con.prepareStatement("delete from ShoppingCarDetails where carID=? and goodsID=?");
pstm.setString(1, carID);
pstm.setString(2, goodsID);
pstm.executeUpdate();
---- 3 PreparedStatement
csmt=con.prepareCall("{call getAllCustomer()}");
rs=csmt.executeQuery();
while (rs.next()) {
Customer customer=new Customer(rs.getInt("customerID"),rs.getString("customerName"),rs.getString("customerPassword"),rs.getString("customerAddress"));
result.add(customer);
}
-------------------------建立静态方法类,可当函数一样直接调用,不用实例化对象
package soyo.shopping.lib;
/*
* customerName=ChangeEncoding.changeToGBK(customerName);
*/
public class ChangEncoding {
public static String changeToGBK(String value){
String result = "";
try {
if (value != null&&!value.equals("")) {
result = new String(value.getBytes("ISO-8859-1"), "GB2312");
}
} catch (Exception e) {
System.err.println("ChangeEncoding.changeToGBK Error ## "
+ e.getMessage());
}
return result;
}
}
---------------------------------------- session
if(customer!=null){ //成功插入记录
page="success.jsp";
HttpSession session=request.getSession();
session.setAttribute("customer", customer); //把用户添加到会话
request.setAttribute("message", "注册成功!欢迎您 "+customerName);
}
else {
request.setAttribute("message", "注册失败,请重新注册");
}
RequestDispatcher dispatcher=request.getRequestDispatcher(page);
dispatcher.forward(request, response);
HttpSession session=request.getSession();
Customer customer=(Customer)session.getAttribute("customer");
CustomerServices customerServices=new CustomerServices();
boolean result;
result=customerServices.buyGoods(customer.getCustomerID(), goodsID, 1);
-------------------------------------------Servlet中doGet(),doPost(),service()函数的关系
1,三者之间的关系:doGet()和doPost()是由函数service()调用才执行的。也就是说,当从HttpServlet类继承时可 以绕过doGet()和doPost()直接override service()函数,也可以override doGet()和doPost()
2,service() 该函数使用起来不像duPost()与duGet()那样有约束,但几乎失去了HttpServlet的意义。很类似于GeneratServlet
3,doGet() 超链接或直接在浏览器地址栏访问时起作用
4,doPost() form提交时起作用
如果两者均有,则可用service() 或者
protected void doGet(HttpServletRequest rst, HttpServletResponse resp) throws ServletException , java.io.IOException {
doPost(req,resp);
}
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class GoodListServlet extends HttpServlet {
public GoodListServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=GBK");
String id=request.getParameter("id");
}
}
---------------------------------------- java.util.List ,LinkedList和ArrayList
java.util.List 是个接口,LinkedList和ArrayList是实现了List这个接口的类。
LinkedList和ArrayList 分别是list最常用的两个子类,
LinkedList善于频繁的增,删操作
ArrayList 善于快速查找
import java.util.LinkedList;
import java.util.List;
List<Good> result=new LinkedList<Good>();
while(rs.next()){
Good good = new Good(rs.getString("id"),rs.getString("nnn"));
result.add(good);
}
import java.util.ArrayList;
ArrayList arrayList = new ArrayList();
-----linkedList 应用实例
servlet:
List<Good> result=goodServices.getRecordAll();
goodServices.java
public List<Good> getRecordAll(){
List<Good> result=goodDAO.getRecordAll();
return result;
}
goodDAO.java
public List<Good> getRecordAll(){
List<Good> result=new LinkedList<Good>();
try {
stmt = conn.createStatement();
rs = stmt.executeQuery("select * from goods");
while(rs.next()){
Good good = new Good(rs.getString("id"),rs.getString("nnn"));
result.add(good);
}
destroy();
} catch (Exception e) {
System.err.println("PaginationDAO.getRecordNumber ERROR ## "+e.getMessage());
}
return result;
}
-----------------------------------建立自己的bean
TestBean.java
package test;
public class TestBean{
private String name = null;
public TestBean(String strName_p){
this.name=strName_p;
}
public void setName(String strName_p){
this.name=strName_p;
}
public String getName(){
return this.name;
}
}
jsp页面
<%@ page import="test.TestBean" %>
<%
TestBean testBean=new TestBean("This is a test java bean.");
%>
Java bean name is: <%=testBean.getName()%>
------------------------------------手动编译 第一个servlet
HelloWorld.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class HelloWorld extends HttpServlet
{
public void doGet(HttpServletRequest request,HttpServletResponse response)throws ServletException,IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html><head><title>");
out.println("This is my first Servlet");
out.println("</title></head><body>");
out.println("<h1>Hello,World!</h1>");
out.println("</body></html>");
}
}
用javac HelloWorld.java来编译这个文件,如果出现无法import javax.servlet.*
那么就是应该把C:\Tomcat\common\lib里面的servlet.jar文件拷贝到C:\JDK\jre\lib\ext中,再次编译,就没有问题了!
然后在Tomcat目录里面的C:\Tomcat\webapps\ROOT里面按如下的文件结构:
ROOT\index.html
ROOT\welcom.jsp
ROOT\WEB-INF\lib\MyServlet.jar(如果你的servlet的.class打成了.jar文件,则放在
lib下面)
ROOT\WEB-INF\classes\HelloWorld.class(把上面生成的HelloWorld.class文件放在这个
里面)
然后在浏览器中输入http://localhost:8080/servlet/HelloWorld,于是Server众望所归的报错了:Error 404--Not Found
怎么回事呢?
Servlet必须使用C:\Tomcat\webapps\ROOT\WEB-INF这个目录下面的web.xml文件进行注册,
用EP打开这个web.xml文件,
把下面这段程序
<servlet>
<servlet-name>org.apache.jsp.index_jsp</servlet-name>
<servlet-class>org.apache.jsp.index_jsp</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>org.apache.jsp.index_jsp</servlet-name>
<url-pattern>/index.jsp</url-pattern>
</servlet-mapping>
替换成
<servlet>
<servlet-name>HelloWorld</servlet-name>
<servlet-class>HelloWorld</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloWorld</servlet-name>
<url-pattern>/servlet/HelloWorld</url-pattern>
</servlet-mapping>
如果没有的话,就直接加那段代码
为什么呢?
因为 这样的结构
<servlet>
<servlet-name>HelloWorld</servlet-name>
<servlet-class>HelloWorld</servlet-class>
</servlet>
表示指定包含的servlet类.
而以下的结构
<servlet-mapping>
<servlet-name>HelloWorld</servlet-name>
<url-pattern>/servlet/HelloWorld</url-pattern>
</servlet-mapping>
表示指定HelloServlet应当映射到哪一种URL模式。
在修改web.xml完毕过后,重新启动Server,然后再输入http://localhost:8080/servlet/HelloWorld,那么偌大一个Hello,World!等
------------------------------------eclipse 第一个servlet 【附实例下载1.rar】
新建web-Dynamic Web Project 项目名为Test
eclipse:WebContent/web.xml
<servlet>
<servlet-name>HelloWorld</servlet-name>
<servlet-class>HelloWorld</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloWorld</servlet-name>
<url-pattern>/servlet/HelloWorld </url-pattern>
</servlet-mapping>
在eclipse src下创建HelloWorld.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class HelloWorld extends HttpServlet
{
public void doGet(HttpServletRequest
request,HttpServletResponse response)throws
ServletException,IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html><head><title>");
out.println("This is my first Servlet");
out.println("</title></head><body>");
out.println("<h1>Hello,World!</h1>");
out.println("</body></html>");
}
}
再将servlet-api.jar拷贝到eclipse WebConent/lib下
关闭tomcat,导出Test项目到webapp下,开启tomcat访问
http://localhost:81/Test/servlet/HelloWorld
------------------------------------ 连接mysql
--------JSP实例
<%@page language="java" %>
<%@page import="com.mysql.jdbc.*" %>
<%@page import="java.sql.*" %>
<%
String driverName="com.mysql.jdbc.Driver";
String username="root";
String psw="****";
String dbName="test";
String tableName="user";
String url="jdbc:mysql://localhost/"+dbName+"?user="+username+"&password="+psw;
try
{
Class.forName("com.mysql.jdbc.Driver").newInstance();
java.sql.Connection conn=DriverManager.getConnection(url);
out.print("ok");
java.sql.Statement statement = conn.createStatement();
String sql = "select * from "+tableName;
java.sql.ResultSet rs= statement.executeQuery(sql);
while(rs.next())
{
out.print(rs.getString(1)+"-");//rs.getInt("AdminID");
out.print(rs.getString(2)+"-");
out.print(rs.getString(3));
out.print("<br>");
}
rs.close();
statement.close();
conn.close();
}
catch(SQLException ex)
{
out.print("error");
}
%>
----------------------------------------------------------------【附完整eclipse项目实例下载Shop.rar】servlet 连接mysql
共6个文件 ,目录结构如下:
1 web.xml 文件
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>Shop</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<description></description>
<display-name>GoodListServlet</display-name>
<servlet-name>GoodListServlet</servlet-name>
<servlet-class>soyo.shopping.servlet.admin.GoodListServlet </servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>GoodListServlet</servlet-name>
<url-pattern>/admin/list </url-pattern>
</servlet-mapping>
</web-app>
2 GoodListServlet.java
package soyo.shopping.servlet.admin;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import soyo.shopping.services.*;
public class GoodListServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
int result;
/**
* @see HttpServlet#HttpServlet()
*/
public GoodListServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
GoodServices goodServices=new GoodServices();
result = goodServices.getRecordNumber();
response.setHeader("Pragma","No-cache");
response.setDateHeader("Expires",0);
response.setHeader("Cache-Control","no-cache");
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<h1>Hello,World!</h1>");
out.println(result);
out.println("<h1>Hello,World2!</h1>");
}
}
3 GoodServices.java
package soyo.shopping.services;
import soyo.shopping.dao.GoodDAO;
import soyo.shopping.entity.Good;
public class GoodServices {
GoodDAO goodDAO;
public GoodServices() {
goodDAO=new GoodDAO();
}
public int getRecordNumber(){
return goodDAO.getRecordNumber();
}
}
4 Good.java
package soyo.shopping.entity;
public class Good {
private String nnn;
public Good(){
}
public Good(String nnn)
{
setGoodsNNN(nnn);
}
public String getGoodsNNN() {
return nnn;
}
public void setGoodsNNN(String nnn) {
this.nnn = nnn;
}
}
5 GoodDAO.java
package soyo.shopping.dao;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.LinkedList;
import java.util.List;
public class GoodDAO {
Connection conn;
public GoodDAO(){
Init init=new Init();
conn=init.connent();
}
public int getRecordNumber(){
int count=0;
try {
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("select count(*) from goods");
System.out.println("PaginationDAO.getRecordNumber 12");
while(rs.next()){
count=rs.getInt(1);
break;
}
//destroy();
} catch (Exception e) {
System.err.println("PaginationDAO.getRecordNumber ERROR ## "+e.getMessage());
}
return count;
}
}
6 Init.java
package soyo.shopping.dao;
import java.sql.Connection;
import java.sql.DriverManager;
public class Init {
private Connection conn;
public Init(){
conn=null;
}
public Connection connent(){
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/shoppingDB", "root", "123456");
} catch (Exception e) {
System.out.println("DAO.init ERROR ## "+e.getMessage());
}
return conn;
}
}
----------------------------------------------------------------【附完整eclipse项目实例下载Shop2.rar】servlet 连接mysql,然后转发到JSP 页面 jstl显示
提问参考地址:http://www.iteye.com/problems/25219
list 类起到了关键作用
结构图如上图
--------1 web.xm
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>Shop</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<description></description>
<display-name>GoodListServlet</display-name>
<servlet-name>GoodListServlet</servlet-name>
<servlet-class>soyo.shopping.servlet.admin.GoodListServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>GoodListServlet</servlet-name>
<url-pattern>/admin/list</url-pattern>
</servlet-mapping>
</web-app>
---------2 GoodListServlet.java
package soyo.shopping.servlet.admin;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import soyo.shopping.services.*;
import soyo.shopping.entity.Good;
public class GoodListServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
int numbers;
/**
* @see HttpServlet#HttpServlet()
*/
public GoodListServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
GoodServices goodServices=new GoodServices();
List<Good> result=goodServices.getRecordAll();
numbers = goodServices.getRecordNumber();
//1 直接输出
// if(result.size()>0){
// PrintWriter out = response.getWriter();
// out.println(result.size());
// for(int i=0;i<result.size();i++){
// out.println(result.get(i));
// }
//
// }
//2 转发
request.setAttribute("goodsList", result);
request.setAttribute("numbers", numbers);
RequestDispatcher dispatcher=request.getRequestDispatcher("goodsList.jsp");
dispatcher.forward(request, response);
}
}
---------------------3 GoodServices
package soyo.shopping.services;
import java.util.List;
import soyo.shopping.dao.GoodDAO;
import soyo.shopping.entity.Good;
public class GoodServices {
GoodDAO goodDAO;
public GoodServices() {
goodDAO=new GoodDAO();
}
public int getRecordNumber(){
return goodDAO.getRecordNumber();
}
public List<Good> getRecordAll(){
List<Good> result=goodDAO.getRecordAll();
return result;
}
}
----------------------------4 GoodDAO
package soyo.shopping.dao;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.LinkedList;
import java.util.List;
import soyo.shopping.entity.Good;
public class GoodDAO {
Connection conn;
public GoodDAO(){
Init init=new Init();
conn=init.connent();
}
public int getRecordNumber(){
int count=0;
try {
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("select count(*) from goods");
System.out.println("PaginationDAO.getRecordNumber 12");
while(rs.next()){
count=rs.getInt(1);
break;
}
//destroy();
} catch (Exception e) {
System.err.println("PaginationDAO.getRecordNumber ERROR ## "+e.getMessage());
}
return count;
}
public List<Good> getRecordAll(){
List<Good> result=new LinkedList<Good>();
try {
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("select * from goods");
while(rs.next()){
Good good = new Good(rs.getString("nnn"));
result.add(good);
}
//destroy();
} catch (Exception e) {
System.err.println("PaginationDAO.getRecordNumber ERROR ## "+e.getMessage());
}
return result;
}
}
-----------------------5 Init
package soyo.shopping.dao;
import java.sql.Connection;
import java.sql.DriverManager;
public class Init {
private Connection conn;
public Init(){
conn=null;
}
public Connection connent(){
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/shoppingDB", "root", "123456");
} catch (Exception e) {
System.out.println("DAO.init ERROR ## "+e.getMessage());
}
return conn;
}
}
------------------6 goodlist.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
page Size : ${numbers}
<c:forEach items="${goodsList}" var="good">
${good.nnn}
</c:forEach>
----------jsp显示
<%
<%@ page language="java" import="java.util.*,java.sql.*,soyo.shopping.*,java.io.*,javax.*" pageEncoding="GBK"%>
List rss=(List)request.getAttribute("goodsList");
int numbers=(Integer)request.getAttribute("numbers");
%>
<%=numbers %>
-------------------------------------------增加分页功能 shop3.rar
-------------------------------------------增加分页功能,增加修改删除 shop4.rar