jspservlet,jspservlet增删改查

将乐信息网 http://www.jianglexinxi.cn 2020-07-15 09:44 出处:网络
jspservlet,jspservlet增删改查,jsp/servlet入门 编辑tomcat/conf/server.xml 在 Host 和 /Host 间添加如下: Context path=\"/myapp\" docBase=\"d:/myapp\" debug=\"0\" reloadable=\"true\" /Context

jspservlet,jspservlet增删改查,jsp/servlet入门

编辑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"% 
 !DOCTYPE html 
 html 
 head 
 title 连接数据库脚本测试 /title 
 /head 
 body 
 table bgcolor="yellow" border="1" width="300px" 
 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()) {
 td %=rs.getString(1)% /td 
 td %=rs.getString(2)% /td 
 td %=rs.getString(3)% /td 
 /tr 
 /table 
 /body 
 /html 

编译指令: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"% 
 !DOCTYPE html 
 html 
 head 
 title BeanTest /title 
 /head 
 body 
 jsp:useBean id="beanTest1" scope="page" /jsp:useBean 
 jsp:setProperty property="name" name="beanTest1" value="lcy" / 
 jsp:setProperty property="age" name="beanTest1" value="34" / 
 jsp:getProperty property="name" name="beanTest1" / 
 jsp:getProperty property="age" name="beanTest1" / 
 /body 
 /html 

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

参考:http://www.cnblogs.com/jbelial/archive/2012/03/20/2396585.html

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

jspservlet,jspservlet增删改查

jspservlet,jspservlet增删改查

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

数据库连接

jspservlet,jspservlet增删改查

jspservlet,jspservlet增删改查

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

jspservlet,jspservlet增删改查

jspservlet,jspservlet增删改查

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

jspservlet,jspservlet增删改查

jspservlet,jspservlet增删改查

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

jspservlet,jspservlet增删改查

jspservlet,jspservlet增删改查

 %@ 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 Article atcList = atc_dao.getAll();
 !DOCTYPE html 
 html 
 body 
 %=session.getAttribute("username") % 
 table 
 tr th 标题 /th th 发布者 /th th 时间 /th /tr 
for (int i = 0; i atcList.size(); i++) {
 Article atc = atcList.get(i);
 td a href="content.jsp?id= %=atc.getId() % " %=atc.getTitle() % /a /td 
 td %=atc.getUsr_id() % /td 
 td %=atc.getDate() % /td 
 /tr 
 /table 
 a href="../publish.html" 发文章 /a 
 /body 
 /html 
View Code

result.jsp

jspservlet,jspservlet增删改查

jspservlet,jspservlet增删改查

 %@ page language="java" pageEncoding="UTF-8"% 
 !DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
 html 
 body 
 form name="result_form" action="${requestScope.page}" method="post" 
 ${requestScope.info} input type="submit" value="确定" 
 /form 
 /body 
 /html 
View Code

login.html

jspservlet,jspservlet增删改查

jspservlet,jspservlet增删改查

 !DOCTYPE html 
 html 
 head 
 meta http-equiv="Content-Type" content="text/html; charset=utf-8" / 
 title 用户登录 /title 
 /head 
 body 
 form action="servlet/Login" method="post" 
用户名 input type="text" name="username" / 
密码 input type="password" name="password" / 
 input type="submit" value="登录" / 
 a href="regist.html" 注册 /a 
 /form 
 /body 
 /html 
View Code  jsp+servlet+javabean实现mvc

jspservlet,jspservlet增删改查

jspservlet,jspservlet增删改查

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

jspservlet,jspservlet增删改查

jspservlet,jspservlet增删改查

public interface Action {
 String execute(HttpServletRequest req, HttpServletResponse res);
}
View Code

jspservlet,jspservlet增删改查

jspservlet,jspservlet增删改查

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

jspservlet,jspservlet增删改查

jspservlet,jspservlet增删改查

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

jspservlet,jspservlet增删改查

jspservlet,jspservlet增删改查

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的配置参数

jspservlet,jspservlet增删改查

jspservlet,jspservlet增删改查

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

jspservlet,jspservlet增删改查

jspservlet,jspservlet增删改查

 servlet 
 servlet-name dbtest /servlet-name 
 servlet-class zzz.lcy.servlet.DbTestServlet /servlet-class 
 init-param 
 param-name driver /param-name 
 param-value com.mysql.jdbc.Driver /param-value 
 /init-param 
 init-param 
 param-name url /param-name 
 param-value jdbc:mysql://localhost:3306/test1 /param-value 
 /init-param 
 init-param 
 param-name user /param-name 
 param-value root /param-value 
 /init-param 
 init-param 
 param-name pass /param-name 
 param-value 123456 /param-value 
 /init-param 
 /servlet 
 servlet-mapping 
 servlet-name dbtest /servlet-name 
 url-pattern /dbtest /url-pattern 
 /servlet-mapping 
View Code 过滤器Filter

jspservlet,jspservlet增删改查

jspservlet,jspservlet增删改查

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

 

本文标题:jspservlet,jspservlet增删改查
http://www.jianglexinxi.cn/yanergaozhi/418511.html

0

精彩评论

暂无评论...
验证码 换一张
取 消