一、ServletContext的学习
1.ServletContext对象获取方式
ServletContext servletContext = getServletContext();
ServletContext servletContext = request.getServletContext();
2.ServletContext对象概述
Context--上下文,当前这件事件所处的环境
ServletContext代表当前Servlet运行的上下文信息(环境信息),也代表当前项目所处的环境信息
3.ServletContext的功能
3.1 //获取当前项目的虚拟路径
String path = servletContext.getContextPath(); //download
response.sendRedirect(request.getServletContext().getContextPath()+"/downloadServlet");
3.2 //获取当前项目发布到tomcat中的磁盘路径
String realPath = servletContext.getRealPath("/"); //D:\学习专用代码库\JavaWeb01\out\artifacts\download_war_exploded\
3.3 //获取src下面的资源在磁盘下面的路径
String realPath1 = servletContext.getRealPath("/WEB-INF/classes");
response.getWriter().println(realPath1);
3.4 //通过类加载器只能加载类路径下面的资源,ServletContext能够加载整个web项目的任何资源
DownloadServlet.class.getClassLoader().getResource("").getPath();
3.5 //获取文件所对应的流
InputStream resourceAsStream = servletContext.getResourceAsStream("img/1.jpg");
3.6 //通过输入流读取文件内容
InputStream fis = request.getServletContext().getResourceAsStream("/img/"+filename);
4.获取文件的MIME类型
4.1 MIME类型:互联网上传输文件的一种标准类型表示 jpg/html/txt/png
//通过文件扩展名可以得到文件对应的MIME类型
//要查找文件的mime类型可以到tomcat/web.xml中可以查看所有文件的mime类型
String mimeType = request.getServletContext().getMimeType("1.jpg");
System.out.println(mimeType);
4.2 //实例演示--接收请求参数,返回文件名
String filename = request.getParameter("filename");
String mimeType = request.getServletContext().getMimeType(filename);
response.setContentType(filename);
5.ServletContext作为域对象共享数据
5.1 域对象的作用范围:可以在整个项目的任何位置共享数据
servletContext.setAttribut("username",12345);
5.2 ServletContext对象的生命周期(重点)
创建:项目启动的时候服务器会为每一个项目创建一个ServletContext对象
销毁:服务器关闭的时候销毁ServletContext
5.3 一个项目唯一对应一个ServletContext
5.4 注意细节:
1.很容易导致内存泄漏
ServletContext作为域对象存储数据作用范围是整个web项目,所以以后在通过ServletContext共享数据的时候,一定要保证数据使用完毕之后及时清除
2.一般存储一些单例对象或者全局的数据
二、注册界面案例代码
1.创建数据库表
2.导入jar包
3.导入配置文件和工具类
package com.bianyiit.util;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import javax.sql.DataSource;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;
//Druid连接池的工具类
/*
* 1.获取连接池对象
* 2.获取连接对象
* 3.归还连接对象的方法
* 4.静态代码块(因为在创建连接池对象之前就需要加载好配置文件中的所有信息)
* */
public class DruidUtils {
private static DataSource ds;
//用来加载配置文件并创建好一个连接池对象
static {
Properties ps=new Properties();
try {
ps.load(DruidUtils.class.getClassLoader().getResourceAsStream("druid.properties"));
ds = DruidDataSourceFactory.createDataSource(ps);
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
//获取连接对象的方法
public static Connection getConnection() throws SQLException {
return ds.getConnection();
}
//有没有必要提供一个获取连接池对象的方法??---框架中可能只需要连接池对象,不需要连接对象
public static DataSource getDataSource(){
return ds;
}
//归还连接对象的方法
//有一种是有结果集的连接(查询),
public static void close(PreparedStatement psmt, Connection con, ResultSet rs){
try {
if(psmt!=null){
psmt.close();
psmt=null;
}
if(con!=null){
con.close();
con=null;
}
if(rs!=null){
rs.close();
rs=null;
}
} catch (SQLException e) {
e.printStackTrace();
}
}
//有一种没有结果集的连接(增删改)
public static void close(PreparedStatement psmt, Connection con){
try {
if(psmt!=null){
psmt.close();
psmt=null;
}
if(con!=null){
con.close();
con=null;
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
druid.properties
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/login
username=root
password=123
#初始化时连接池中连接对象的个数
initialSize=5
#最大的连接对象的个数
maxActive=10
#超时时间(延迟三秒报错)
maxWait=3000
4.创建实体类User
package com.bianyiit.domian;
import java.util.Date;
public class User {
private Integer id;
private String username;
private String password;
private String repassword;
private String sex;
private Date birthday;
private String email;
public User() {
}
public User(Integer id, String username, String password, String repassword, String sex, Date birthday, String email) {
this.id = id;
this.username = username;
this.password = password;
this.repassword = repassword;
this.sex = sex;
this.birthday = birthday;
this.email = email;
}
public String getRepassword() {
return repassword;
}
public void setRepassword(String repassword) {
this.repassword = repassword;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
", repassword='" + repassword + '\'' +
", sex='" + sex + '\'' +
", birthday=" + birthday +
", email='" + email + '\'' +
'}';
}
}
5.创建注册界面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>注册界面</title>
</head>
<style>
.submit01{
width: 250px;
}
</style>
<body>
<form action="/web1/registerServlet" method="post">
请输入用户名:<input type="text" name="username" placeholder="请输入用户名"><br>
请输入密码:<input type="password" name="password" placeholder="请输入密码"><br>
请输入确认密码:<input type="password" name="repassword" placeholder="请确认密码"><br>
请选择性别:<input type="radio" value="male" name="sex">男
<input type="radio" value="female" name="sex">女<br>
请输入出生日期:<input type="date" name="birthday" placeholder="请输入出生日期"><br>
请输入邮箱:<input type="email" name="email" placeholder="请输入邮箱"><br>
<input class="submit01" type="submit" value="注册">
</form>
</body>
</html>
6.创建RegisterServlet类
package com.bianyiit.web;
import com.bianyiit.dao.UserDao;
import com.bianyiit.domian.User;
import com.bianyiit.util.DateConverter;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
@WebServlet("/registerServlet")
public class RegisterServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1.设置编码
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
//2.接收客户端的数据
Map<String, String[]> parameterMap = request.getParameterMap();
ConvertUtils.register(new DateConverter(),Date.class);
User user = new User();
try {
BeanUtils.populate(user,parameterMap);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
UserDao dao = new UserDao();
if(user.getPassword()==null||!user.getPassword().equals(user.getRepassword())){
response.getWriter().println("用户注册失败01");
return;
}
int result = dao.addUser(user);
//4.根据业务处理结果响应数据到浏览器
if(result>0){
response.getWriter().println("用户注册成功");
}else {
response.getWriter().println("用户注册失败02");
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
7.创建注册业务处理类Userdao类
package com.bianyiit.dao;
import com.bianyiit.domian.User;
import com.bianyiit.util.DruidUtils;
import org.springframework.jdbc.core.JdbcTemplate;
public class UserDao {
public int addUser(User user){
JdbcTemplate jdbcTemplate = new JdbcTemplate(DruidUtils.getDataSource());
String sql="INSERT INTO usermsg VALUES(NULL,?,?,?,?,?)";
int update=jdbcTemplate.update(sql,user.getUsername(),user.getPassword(),user.getSex(),user.getBirthday(),user.getEmail());
return update;
}
}
8.创建日期转换器--DateConverter类
package com.bianyiit.util;
import org.apache.commons.beanutils.Converter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateConverter implements Converter {
@Override
public Object convert(Class aClass, Object o) {
if (aClass == Date.class) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
try {
Date parse = simpleDateFormat.parse((String) o);
return parse;
} catch (ParseException e) {
e.printStackTrace();
}
}
return 0;
}
}
9.结果演示之注册成功界面
10.结果演示之注册成功的数据库表