博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
jsp/servlet入门
阅读量:4939 次
发布时间:2019-06-11

本文共 15486 字,大约阅读时间需要 51 分钟。

tomcat发布目录设置

编辑tomcat/conf/server.xml

在<Host>和</Host>间添加如下:<Context path="/myapp" docBase="d:/myapp" debug="0" reloadable="true"></Context>

启动tomcat后即可访问:http://localhost:8080/myapp

web应用目录结构

d:/myapp/*.jsp

d:/myapp/WEB-INF/web.xml

d:/myapp/WEB-INF/classes/  保存*.class文件

d:/myapp/WEB-INF/lib/  保存*.jar文件

jsp基础知识

原理:jsp由系统编译成servlet,servlet负责相应用户请求。

注释:<%--注释--%>

声明:<%!声明变量和函数%>

输出表达式:<%=输出表达式%>

连接数据库jsp实例:test.jsp

<%@ page import="java.sql.*"%><%@ page language="java" contentType="text/html; charset=utf-8"%>连接数据库脚本测试
<% Class.forName("com.mysql.jdbc.Driver"); Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "123456"); Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery("select * from user"); while (rs.next()) { %>
<% } %>
<%=rs.getString(1)%> <%=rs.getString(2)%> <%=rs.getString(3)%>

编译指令:page、include、taglib <%@ 编译指令名 属性名="属性值"... %>

动作指令:jsp:forward/jsp:param/jsp:include/jsp:plugin/jsp:useBean/jsp:setProperty/jsp:getProperty

package com.zzz.lcy;public class Person {    String name;    int age;    public Person() {    }    public Person(String name, int age) {        this.name = name;        this.age = age;    }    public void setName(String name) {        this.name = name;    }    public String getName() {        return name;    }    public void setAge(int age) {        this.age = age;    }    public int getAge() {        return age;    }}

默认构造函数不能少,编译javac Person -d d:/myapp/WEB-INF/classes/

<%@page language="java" contentType="text/html; charset=utf-8"%>BeanTest

 内置对象:application/config/exception/out/pageContext/request/response/session

参考:

servlet配置

编辑d:/myapp/WEB-INF/web.xml

在<webapp></webapp>间添加如下:

  <servlet>

      <servlet-name>hello</servlet-name>
      <servlet-class>zzz.lcy.servlet.HelloWorld</servlet-class>
  </servlet>
  <servlet-mapping>
      <servlet-name>hello</servlet-name>
      <url-pattern>/servlet/HelloWorldDemo</url-pattern>
  </servlet-mapping>

注意:<servlet-name>必须对应上

访问网址:http://localhost:8080/myapp/servlet/HelloWorldDemo

package zzz.lcy.servlet;import java.io.IOException;import java.io.PrintWriter;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;public class HelloWorld extends HttpServlet {    public void doGet(HttpServletRequest request, HttpServletResponse response) {        response.setContentType("text/html;charset=utf-8");        try {            PrintWriter out = response.getWriter();            out.println("hello, world.");            out.close();        } catch (IOException e) {            e.printStackTrace();        }    }    public void doPost(HttpServletRequest request, HttpServletResponse response) {        doGet(request, response);    }}

 jsp论坛实例(部分代码)

javabean

public class User {    private int id;    private String name;    private String password;    private String nickname;    public User() {    }    public User(String name, String password, String nickname) {        this.name = name;        this.password = password;        this.nickname = nickname;    }    public int getId() {        return id;    }    public void setId(int id) {        this.id = id;    }    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public String getPassword() {        return password;    }    public void setPassword(String password) {        this.password = password;    }    public String getNickname() {        return nickname;    }    public void setNickname(String nickname) {        this.nickname = nickname;    }}
View Code

数据库连接

import java.sql.*;public class DB {    private Connection conn;    private static final String DRIVER = "com.mysql.jdbc.Driver";    private static final String URL = "jdbc:mysql://localhost:3306/bbs";    private static final String USR = "root";    private static final String PASSWD = "123456";    private static DB db = new DB();    private DB() {        try {            Class.forName(DRIVER);            conn = DriverManager.getConnection(URL, USR, PASSWD);        } catch (Exception e) {            e.printStackTrace();        }    }    public static DB getInstance() {        return db;    }    public Connection getConn() throws Exception {        return conn;    }    public ResultSet execSql(String sql, Object...objs) throws Exception {        PreparedStatement pstmt = conn.prepareStatement(sql);        for (int i = 0; i < objs.length; i++) {            pstmt.setObject(i + 1, objs[i]);        }        pstmt.execute();        return pstmt.getResultSet();    }    public void close() throws Exception {        conn.close();    }    public static void main(String[] args) throws Exception {        DB db = new DB();        db.execSql("insert into t_user(name,password,nickname) values(?,?,?)", "aaa", "123", "hellokity");    }}
View Code

dao

public class UserDAO {    public void add(User user) {        try {            DB.getInstance().execSql("insert into t_user(name,password,nickname) values(?,?,?)", user.getName(), user.getPassword(), user.getNickname());        } catch (Exception e) {            e.printStackTrace();        }    }    public User getByName(String name) {        try {            ResultSet rs = DB.getInstance().execSql("select * from t_user where name=?", name);            User user = new User();            while (rs.next()) {                user.setId(rs.getInt("id"));                user.setName(rs.getString("name"));                user.setPassword(rs.getString("password"));                user.setNickname(rs.getString("nickname"));                return user;            }        } catch (Exception e) {            e.printStackTrace();        }        return null;    }    public User getById(int id) {        try {            ResultSet rs = DB.getInstance().execSql("select * from t_user where id=?", id);            User user = new User();            while (rs.next()) {                user.setId(rs.getInt("id"));                user.setName(rs.getString("name"));                user.setPassword(rs.getString("password"));                user.setNickname(rs.getString("nickname"));                return user;            }        } catch (Exception e) {            e.printStackTrace();        }        return null;    }    public static void main(String[] args) {        UserDAO dao = new UserDAO();        User user = dao.getByName("aaa");        if (user != null) {            System.out.println(user.getNickname());        }    }}
View Code

servlet

public class Login extends HttpServlet {    public void doPost(HttpServletRequest req, HttpServletResponse res) {        try {            req.setCharacterEncoding("UTF-8");        } catch (UnsupportedEncodingException e) {            e.printStackTrace();        }        res.setContentType("UTF-8");        String username = req.getParameter("username");        String password = req.getParameter("password");        UserDAO user_dao = new UserDAO();        User user = user_dao.getByName(username);        if (user == null) {            req.setAttribute("info", "登录失败");            req.setAttribute("page", "../login.html");        } else {            if (password.equals(user.getPassword())) {                req.setAttribute("info", "登录成功");                HttpSession session = req.getSession(true);                session.setAttribute("username", username);                session.setAttribute("usr_id", user.getId());                try {                    res.sendRedirect("../jsp/main.jsp");                } catch (IOException e) {                    e.printStackTrace();                }            } else {                req.setAttribute("info", "密码错误");                req.setAttribute("page", "../login.html");            }        }        RequestDispatcher rd = req.getRequestDispatcher("/jsp/result.jsp");        try {            rd.forward(req, res);        } catch (Exception e) {            e.printStackTrace();        }    }    public void doGet(HttpServletRequest req, HttpServletResponse res) {        doPost(req, res);    }}
View Code

main.jsp

<%@ page language="java" pageEncoding="UTF-8" %><%@page import="zzz.lcy.bbs.dao.ArticleDAO"%><%@page import="zzz.lcy.bbs.bean.Article"%><%@page import="java.util.*" %><%String username = (String)session.getAttribute("username");if (username == null || username.equals("")) {    response.sendRedirect("../login.html");}ArticleDAO atc_dao = new ArticleDAO();List
atcList = atc_dao.getAll();%><%=session.getAttribute("username") %>
<%for (int i = 0; i < atcList.size(); i++) { Article atc = atcList.get(i);%>
<%}%>
标题 发布者 时间
<%=atc.getTitle() %> <%=atc.getUsr_id() %> <%=atc.getDate() %>
发文章
View Code

result.jsp

<%@ page language="java" pageEncoding="UTF-8"%>    
${requestScope.info}
View Code

login.html

用户登录
用户名
密码
注册
View Code

 jsp+servlet+javabean实现mvc

import java.io.*;import javax.servlet.*;import javax.servlet.http.*;public class ControlServlet extends HttpServlet {    public void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {        String pathName = req.getServletPath();        System.out.println("pathName= " + pathName);        int i = pathName.indexOf(".");        String actionName = pathName.substring(1, i);        System.out.println("actionName= " + actionName);        String actionClassName = this.getInitParameter(actionName);        Action action = ActionFactory.getActionFactory().getAction(actionClassName);        String url = action.execute(req, res);        if (url == null) {            req.getRequestDispatcher("error.jsp").forward(req, res);        } else {            req.getRequestDispatcher(url).forward(req, res);        }    }}
View Code
public interface Action {    String execute(HttpServletRequest req, HttpServletResponse res);}
View Code
public class LoginAction implements Action {    public String execute(HttpServletRequest req, HttpServletResponse res) {        String username = req.getParameter("username");        String password = req.getParameter("password");        if (username.equals("aaa") && password.equals("123")) {            req.setAttribute("username", username);            return "main.jsp";        }        return "login.jsp";    }}
View Code
public class ActionFactory {    private static ActionFactory af = new ActionFactory();    private ActionFactory() {}    public static ActionFactory getActionFactory() {        return af;    }    public Action getAction(String actionClassName) {        Action action = null;        try {            action = (Action) Class.forName(actionClassName).newInstance();        } catch (Exception e) {            e.printStackTrace();        }        return action;    }}
View Code

 应用启动时启动servlet

import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.util.Date;import javax.servlet.ServletConfig;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.swing.Timer;public class TimerServlet extends HttpServlet {    private static final long serialVersionUID = 1L;    public void init(ServletConfig config) {        try {            super.init(config);        } catch (ServletException e) {            e.printStackTrace();        }        Timer t = new Timer(1000, new ActionListener() {            public void actionPerformed(ActionEvent e) {                System.out.println(new Date());            }        });        t.start();    }}
View Code

    <servlet>

        <servlet-name>timer</servlet-name>
        <servlet-class>xx.yy.TimerServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

访问servlet的配置参数

import java.sql.Connection;import java.sql.DriverManager;import javax.servlet.ServletConfig;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;public class DbTestServlet extends HttpServlet {    private static final long serialVersionUID = 1L;    public void init(ServletConfig config) {        try {            super.init(config);        } catch (ServletException e) {            e.printStackTrace();        }    }    public void service(HttpServletRequest req, HttpServletResponse res) {        ServletConfig config = this.getServletConfig();        String driver = config.getInitParameter("driver");        String url = config.getInitParameter("url");        String user = config.getInitParameter("user");        String pass = config.getInitParameter("pass");        try {            Class.forName(driver);            Connection conn = DriverManager.getConnection(url, user, pass);        } catch (Exception e) {            e.printStackTrace();        }    }}
View Code
dbtest
zzz.lcy.servlet.DbTestServlet
driver
com.mysql.jdbc.Driver
url
jdbc:mysql://localhost:3306/test1
user
root
pass
123456
dbtest
/dbtest
View Code

过滤器Filter

import java.io.IOException;import javax.servlet.Filter;import javax.servlet.FilterChain;import javax.servlet.FilterConfig;import javax.servlet.ServletContext;import javax.servlet.ServletException;import javax.servlet.ServletRequest;import javax.servlet.ServletResponse;import javax.servlet.http.HttpServletRequest;public class FilterTest implements Filter {    private FilterConfig config;    public void destroy() {        config = null;    }    public void doFilter(ServletRequest arg0, ServletResponse arg1,            FilterChain arg2) throws IOException, ServletException {        ServletContext context = this.config.getServletContext();        long before = System.currentTimeMillis();        System.out.println("开始过滤");        HttpServletRequest req = (HttpServletRequest) arg0;        context.log("已经获得请求地址: " + req.getServletPath());        arg2.doFilter(arg0, arg1);        long after = System.currentTimeMillis();        context.log("过滤结束");        context.log("请求被定位到: " + req.getRequestURI() + ", 花费时间: " + (after - before));    }    public void init(FilterConfig arg0) throws ServletException {        config = arg0;    }}
View Code

    <filter>

        <filter-name>log</filter-name>
        <filter-class>xx.yy.FilterTest</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>log</filter-name>
        <servlet-name>*</servlet-name>
    </filter-mapping>

监听器Listener

Listener的作用类似于load-on-startup,用于在web应用启动时,启动某些后台程序,这些后台程序负责为系统运行提供支持。使用Listener需要两步:

1) 创建Listener实现类。需要实现ServletContextListener接口;

2) 在web.xml中配置Listener。<listener><listener-class>xx.yy.TestListener</listener-class></listener>

 

转载于:https://www.cnblogs.com/feilv/p/4424887.html

你可能感兴趣的文章
MySQL之多表查询练习
查看>>
数据仓库专题23-原则!原则!原则!
查看>>
Linux下载安装mysql5.7教程
查看>>
iOS开发经验总结(一)
查看>>
数量关系练习题
查看>>
当inline-block和text-indent遇到IE6,IE7
查看>>
mysql处理警告 Warning: Using a password on the command line interface can be insecure.
查看>>
博客样式
查看>>
Linux服务器调优
查看>>
设计模式(十)——模板方法模式
查看>>
PHP封装curl的调用接口及常用函数
查看>>
两年前的一份项目总结
查看>>
[.net 面向对象编程基础] (16) 接口
查看>>
C#读物
查看>>
3.UiObejct API 详细介绍
查看>>
Windows Azure 社区新闻综述(#71 版)
查看>>
Windows XP 的最高版本 .net framework 安装
查看>>
本机不装Oracle,使用plsql连接远程Oracle的方法
查看>>
先说一下JS的获取方法,其要比JQUERY的方法麻烦很多,后面以JQUERY的方法作对比。...
查看>>
mysql中间件研究(Atlas,cobar,TDDL)
查看>>