Servlet

服务器

常用以下三种

Apache
Apache仍然是世界上用的最多的Web服务器,市场占有率达60%左右。它源于NCSAhttpd服务器,当NCSA WWW服务器项目停止后,那些使用NCSA WWW服务器的人们开始交换用于此服务器的补丁,这也是apache名称的由来(pache 补丁)。世界上很多著名的网站都是Apache的产物,它的成功之处主要在于它的源代码开放、有一支开放的开发队伍、支持跨平台的应用(可以运行在几乎所有的Unix、Windows、Linux系统平台上)以及它的可移植性等方面。
  官方网站:http://www.apache.org
  下载地址:http://www.eryin.com/Server/Soft/200808/01245.html
Tomcat
Tomcat是一个开放源代码、运行servlet和JSP Web应用软件的基于Java的Web应用软件容器。Tomcat Server是根据servlet和JSP规范进行执行的,因此我们就可以说Tomcat Server也实行了Apache-Jakarta规范且比绝大多数商业应用软件服务器要好。
Tomcat是Java Servlet 2.2和JavaServer Pages 1.1技术的标准实现,是基于Apache许可证下开发的自由软件。Tomcat是完全重写的Servlet API 2.2和JSP 1.1兼容的Servlet/JSP容器。Tomcat使用了JServ的一些代码,特别是Apache服务适配器。随着Catalina Servlet引擎的出现,Tomcat第四版号的性能得到提升,使得它成为一个值得考虑的Servlet/JSP容器,因此目前许多WEB服务器都是采用Tomcat。
  官方网站:http://tomcat.apache.org
  下载地址:http://www.eryin.com/Server/Soft/200808/02250.html 

Microsoft IIS
Microsoft的Web服务器产品为Internet Information Server (IIS),IIS 是允许在公共Intranet或Internet上发布信息的Web服务器。IIS是目前最流行的Web服务器产品之一,很多著名的网站都是建立在IIS的平台上。IIS提供了一个图形界面的管理工具,称为Internet服务管理器,可用于监视配置和控制Internet服务。
IIS是一种Web服务组件,其中包括Web服务器、FTP服务器、NNTP服务器和SMTP服务器,分别用于网页浏览、文件传输、新闻服务和邮件发送等方面,它使得在网络(包括互联网和局域网)上发布信息成了一件很容易的事。它提供ISAPI(Intranet Server API)作为扩展Web服务器功能的编程接口;同时,它还提供一个Internet数据库连接器,可以实现对数据库的查询和更新。
  官方网站:http://www.microsoft.com
  下载地址:http://www.eryin.com/Server/Soft/200808/02257.html

 

TomCat   重点

目录结构

 1. bin : binary 二进制文件 , 包含执行文件

     1. startup.bat 开启

     2. shutdown.bat 关闭

2. conf: configure 配置文件

    1. server.xml

    2. web.xml

3. lib :tomcat运行用的jar  servlet-api.jar

4. logs:日志 ->

5. temp:临时文件

6. webapps:存放web项目的7. work:存放_jsp,java  .class文件的

webapps 项目/目录结构

       META-INF

                项目配置信息

       WEB-INF(项目内层,所有放在这里的资源不能直接访问)

               jsp动态资源

                   推荐放在内层

                classes: java代码存放路径

                 lib:  存放当前项目依赖jar,类库

                         mysql.jar

                   web.xml 当前项目核心配置文件

                      一旦一行有问题

eclipse 和tomcat 关联

server视图 ,找tomcat

双击->

use tomcat installation

deploy path -> webapps

 

eclipse 发布(deploy) tomcat

1. dynamic web project

2. 目录

 

 

     

 

3.eclipse 发布web项目

新建一个文件夹(项目名)

webcontent下面所有东西全部拷贝到tomcat上

src 拷贝到了 WEB-INF/classes/ 下面

 

访问servlet

配置servlet

指定外部映射路径

  <servlet>

    <description></description>

    <display-name>avisiter</display-name>

    <servlet-name>avisiter</servlet-name>

<servlet-class>web.huaxin.com.avisiter</servlet-class>

项目全路径

  </servlet>

  <servlet-mapping>

    <servlet-name>avisiter</servlet-name>

    <url-pattern>/avisiter</url-pattern>

 </servlet-mapping>

 

 

 

获取参数:request.getParameter(name);

Name:html文件中,form标签中的name属性值

 

Servlet

接口,抽象方法

配置

抽象方法

init 初始化方法

destroy 销毁方法

service 核心方法

getServletConfig() 获取servlet配置

getServletInfo() 获取servlet信息

 

生命周期

执行者:tomcat

init :第一次创建servlet

service:每次请求

destroy:程序正常退出(tomcat停止),程序被移除

 

servlet创建

tomcat创建

先有构造,再有init

servlet构造方法不能传递参数

错误页

  <error-page>

    <error-code>404</error-code>

    <location>/html/404.html</location>

  </error-page>

转字符编码

response.setContentType("text/html;charset=utf-8");

 

 

ServletConfig

servlet配置(在web.xml里配置)

 <init-param>

       <param-name>encoding</param-name>

       <param-value>utf-8</param-value>

   </init-param>

方法

String getInitParameter(String name) 获取servlet初始化参数

getInitParameterNames() 获取初始化所有参数的名字

getServletName() 获取servlet配置名

getServletContext() 获取整个应用的app,上下文

 

ServletContext

整个项目全局配置参数

在servlet同级配置

 <!-- context 上下文-参数   -->  

   <context-param>

       <param-name>encoding</param-name>

       <param-value>utf-8</param-value>

   </context-param>

getInitParameter

四大域对象之一(最大),作用在整个应用

生命周期

什么时候创建: 服务器一启动,tomcat就会给每个项目创建ServletContext

什么时候销毁: 服务器正常关闭或者一次

作用: setAttribute getAttribute removeAttribute

获取mimeType

 String fileName = "xx.jpg"; // js -> text/javascript zip txt

 String mimeType = servletContext.getMimeType(fileName);

 System.out.println(mimeType);

 String fileName2 = "txt"; // js -> text/javascript zip txt

 String mimeType2 = servletContext.getMimeType(fileName2);

 System.out.println(mimeType2);//null

获取项目真实路径(文件上传)

上传图片,保存在tomcat下面

     String realPath = servletContext.getRealPath("/upload");

     System.out.println(realPath);

     String realPath2 = servletContext.getRealPath("upload");

     System.out.println(realPath2);

 

代码:

package com.hx.web1.web;

 

import java.io.IOException;

 

import javax.servlet.Servlet;

import javax.servlet.ServletConfig;

import javax.servlet.ServletContext;

import javax.servlet.ServletException;

import javax.servlet.ServletRequest;

import javax.servlet.ServletResponse;

 

/**

 * Servlet implementation class T03_ServletContext

 */

public class ServletContext implements Servlet {

private ServletConfig config;

 

@Override

public void init(ServletConfig config) throws ServletException {

this.config = config;

}

 

@Override

public ServletConfig getServletConfig() {

 

return config;

}

 

@Override

public void service(ServletRequest req, ServletResponse res)

throws ServletException, IOException {

ServletConfig servletConfig = getServletConfig();

ServletContext servletContext = servletConfig.getServletContext();

String initParameter = servletContext.getInitParameter("encoding");

System.out.println(initParameter);

// mimeType image/jpeg

String fileName = "xx.jpg"; // js -> text/javascript zip txt

String mimeType = servletContext.getMimeType(fileName);

System.out.println(mimeType);

String fileName2 = "txt"; // js -> text/javascript zip txt

String mimeType2 = servletContext.getMimeType(fileName2);

System.out.println(mimeType2);// null

// 获取项目真实路径

String realPath = servletContext.getRealPath("/upload");

System.out.println(realPath);

String realPath2 = servletContext.getRealPath("upload");

System.out.println(realPath2);

 

}

 

@Override

public String getServletInfo() {

 

return null;

}

 

@Override

public void destroy() {

}

 

}

servlet单实例,多线程

多线程-> 线程安全问题

最好不要用全局变量

 

三层

登录案例

1. 准备登入的界面

2. form表单收集用户输入信息,提交到代码 servlet

3. 创建一个servlet

4. 界面的action地址,servlet

5. 在service,去获取用户的账号密码

6. web三层

    1. web 界面层

        1. 接受参数

        2. 响应客户端请求

    2. service服务层

        1. 具体操作业务逻辑

        2. 比如:登入操作,密码加密

    3. dao数据库访问层

7. 三层创建

    1. com.huaxin.crm.web.servlet

    2. com.huaxin.crm.service

用户操作

    3. com.huaxin.crm.dao

数据库方法

    4. com.huaxin.crm.bean  普通java类

     用户信息

    5. com.huaxin.crm.util    工具类

        1. 加密工具类

        2. jdbc工具类

 

8. 创建数据库和表

    1. 数据库名字: 代表一个项目

        1. Hx_1706_Crm

    2. 一个表: 对应bean里面的一个类,表里面的字段对应bean的字段

        1. HxUser

 

对应关系

1. 一个数据可对应一个项目

2. 一张表对应一个bean

3. 一个bean对应一个dao

4. 一个dao对应一个service

5. 一个service一般对应一个servlet

 

dao层

1. jdbc 一套接口,实现类交给你数据生产厂商

2. 需要下载驱动 mysql.jar,放在 /WEB-INF/lib,自动关联

3. 开发步骤

    1. 注册驱动

    2. 获取连接  connection

    3. 执行者  preparedStatement

    4. 处理结果

    5. 关闭资源

        1. Connection

        2. Statement

        3. ResultSet

 

代码:package com.huaxin.crm.util;

 

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.sql.Statement;

 

public class JdbcUtil {

 

static {

 

try {

Class.forName("com.mysql.jdbc.Driver");

} catch (ClassNotFoundException e) {

e.printStackTrace();

}

}

 

static String url = "jdbc:mysql://localhost:3306/hx_1706_crm"; // 连接地址和连接数据库的名字

static String user = "root"; // 账号

static String password = "1234";//

 

public static Connection getConnection() throws SQLException {

return DriverManager.getConnection(url, user, password);

}

 

public static void close(ResultSet resultSet, Statement stmt, Connection conn) {

if (resultSet != null) {

try {

resultSet.close();

} catch (SQLException sqlex) {

// ignore, as we can't do anything about it here

}

resultSet = null;

}

/** 最后释放资源 close() **/

if (stmt != null) {

try {

stmt.close();

} catch (SQLException sqlex) {

// ignore, as we can't do anything about it here

}

stmt = null;

}

 

if (conn != null) {

try {

conn.close();

} catch (SQLException sqlex) {

// ignore, as we can't do anything about it here

}

 

conn = null;

}

}

 

}

 

 

service

1. dao可以全局

2. 加密  md5 + base64 混合

    1. byte[]

    2. 格式化 base64

        public static String md5(String str) {

            try {

                MessageDigest md = MessageDigest.getInstance("MD5");

                byte[] messageByte = str.getBytes("UTF-8");

                byte[] md5Byte = md.digest(messageByte); // 获得MD5字节数组,16*8=128位

 

                String string = new String(md5Byte);

 

                String bytesToHex = bytesToHex(md5Byte); // 最后加密结果

                return bytesToHex;

            } catch (Exception e) {

                throw new RuntimeException(e);

            }

 

        }

 

        // 二进制转十六进制

        public static String bytesToHex(byte[] bytes) {

            StringBuffer hexStr = new StringBuffer();

            int num;

            for (int i = 0; i < bytes.length; i++) {

                num = bytes[i];

                if (num < 0) {

                    num += 256;

                }

                if (num < 16) {

                    hexStr.append("0");

                }

                hexStr.append(Integer.toHexString(num));

            }

            return hexStr.toString().toUpperCase();

        }

servlet

 service 层 在代码方法里面,servlet单例有线程安全问题

 

 

反射 reflect

 

  内加载机制

加载字节码文件到内存(字节码文件当成模板)

把静态(方法,字段,代码块)初始化(公共部分准备好)

如果创建对象的时候,会从模板区域找

Servlet  (新建servlet自动生成)

  <servlet>

     <description></description>

     <display-name>LoginServlet</display-name>

     <servlet-name>LoginServlet</servlet-name>

     <servlet-class>com.huaxin.crm.web.servlet.LoginServlet</servlet-class>

   </servlet>

   <servlet-mapping>

     <servlet-name>LoginServlet</servlet-name>

     <url-pattern>/LoginServlet</url-pattern>

   </servlet-mapping>

 

可变参数

其实就是一个数组,必须放在最后面

Public int add(int...param){

Int result = 0;

For(int i :param){

Result+=i;

}

Return result;

}

 

Class

获取方法

clazz =Class.forName("全路径");

clazz = 对象.getClass(); this.getClass();

clazz = 类型.class;

重要方法

字段

Field[] getFields() ; 获取当前类的所有的字段

Field[] getDeclaredFields()

构造方法

Constructor<?>[] getConstructors()

Constructor<?>[] getDeclaredConstructors()

方法

Method[] getDeclaredMethods() private

Method[] getMethods() public

总结

添加了declared ,获取到的都是私有的

如果访问私有的必须打开权限

xx.setAccessible(true);

 

Constructor

newInstance() 创建对象

Method

invoke(obj,方法参数1,方法参数2...);

 

servlet优化

HxUser 添加,删除,修改,查询

一一对应

servlet中的doGet ,doPost 重复代码

 

代码:

CommonServlet

package com.huaxin.crm.web.servlet;

 

import java.io.IOException;

import java.lang.reflect.Method;

 

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

 

/**

 * Servlet implementation class CommonServlet

 */

public class CommonServlet extends HttpServlet {

 

protected void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

 

try {

String methodName = request.getParameter("method");

System.out.println(methodName);

Class<? extends CommonServlet> clazz = this.getClass();

Method method = clazz.getMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);

method.invoke(this, request, response);

} catch (Exception e) {

throw new RuntimeException(e);

} finally {

 

}

 

}

 

protected void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

 

doGet(request, response);

}

 

}

 

UserServlet

 

package com.huaxin.crm.web.servlet;

 

import java.io.IOException;

import java.io.PrintWriter;

import java.sql.Connection;

import java.sql.PreparedStatement;

import java.sql.ResultSet;

 

import javax.servlet.ServletException;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

 

import com.huaxin.crm.bean.HxUser;

import com.huaxin.crm.service.HxUserService;

import com.huaxin.crm.util.JdbcUtil;

 

public class UserServlet extends CommonServlet {

 

public void dologin(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

 

response.setContentType("text/html;charset=utf-8");

String username = request.getParameter("username");

String password = request.getParameter("password");

 

HxUser user = new HxUser();

user.setUsername(username);

user.setPassword(password);

 

HxUserService hxUserService = new HxUserService();

HxUser hxUser = hxUserService.login(user);

 

PrintWriter out = response.getWriter();

if (hxUser == null) {

 

out.print("登入失败");

 

} else {

out.print("登入成功,欢迎" + hxUser.getName());

}

}

 

public void doregist(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

 

response.setContentType("text/html;charset=utf-8");

String username = request.getParameter("username");

String name = request.getParameter("name");

String email = request.getParameter("emailname");

String password = request.getParameter("ispwd");

String telnumber = request.getParameter("telnumber");

 

HxUser user = new HxUser();

user.setUsername(username);

user.setPassword(password);

user.setName(name);

user.setTelnumber(telnumber);

user.setEmail(email);

 

HxUserService hxUserService = new HxUserService();

int hxUser = hxUserService.regist(user);

 

PrintWriter out = response.getWriter();

if (hxUser == 1) {

out.print("注册成功,欢迎" + user.getName());

 

} else {

out.print("注册失败");

}

}

 

public void showusers(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

 

response.setContentType("text/html;charset=utf-8");

PrintWriter out = response.getWriter();

out.println(

"<table border='0' width='80%' align='center' cellspacing='1' bgcolor='#0033CC' style='text-align: center'>");

out.println("<caption><h3>用户信息表</h3></caption>");

out.println("<tr bgcolor='#919191'>");

out.println("<th>编号</th>");

out.println("<th>用户名</th>");

out.println("<th>昵称</th>");

out.println("<th>电话号码</th>");

out.println("<th>邮箱</th>");

out.println("</tr>");

 

Connection connection = null;

PreparedStatement stmt = null;

ResultSet resultSet = null;

try {

connection = JdbcUtil.getConnection();

String sql = "select * from hxuser";

stmt = connection.prepareStatement(sql);

 

resultSet = stmt.executeQuery();

 

while (resultSet.next()) {

 

int id = resultSet.getInt("id");

String username = resultSet.getString("username");

String name = resultSet.getString("name");

String email = resultSet.getString("email");

String telnumber = resultSet.getString("tel");

 

out.println("<tr bgcolor='#CECECE'>");

 

out.println("<td>" + id + "</td>");

out.println("<td>" + username + "</td>");

out.println("<td>" + name + "</td>");

out.println("<td>" + telnumber + "</td>");

out.println("<td>" + email + "</td>");

 

out.println("</tr>");

 

}

} catch (Exception e) {

throw new RuntimeException(e);

} finally {

JdbcUtil.close(resultSet, stmt, connection);

}

 

out.println("</table>");

}

 

}

 

 

 

 

 

 

 

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值