//存入数据
response.setCharacterEncoding("UTF-8");
ServletContext context = this.getServletContext();
String username="清水河";
context.setAttribute("name",username);
response.getWriter().print("设置name成功:"+username);
//读取数据
response.setCharacterEncoding("UTF-8");
ServletContext context = this.getServletContext();
String name = (String) context.getAttribute("name");
response.getWriter().print("我们获取的信息为:"+name);
driver=com.mysql.jdbc.Driver
username=root
password=123456
url=jdbc:mysql://localhost:3306/smbms
//获取配置文件的路径
String realPath = this.getServletContext().getRealPath(
"WEB-INF/classes/resources/database.properties");
System.out.println("获取的路径:"+realPath);
Properties properties = new Properties();
FileInputStream is = new FileInputStream(realPath);
//把文件流加载到配置文件对象中
properties.load(is);
String driver = properties.getProperty("driver");
String username = properties.getProperty("username");
String password = properties.getProperty("password");
String url = properties.getProperty("url");
<servlet>
<servlet-name>ServletTest03</servlet-name>
<servlet-class>com.kuang.servlet.ServletTest03</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ServletTest03</servlet-name>
<url-pattern>/s3</url-pattern>
</servlet-mapping>
localhost:8080/demo02/s3
//自动刷新网页
response.setHeader("refresh","2");
<span class="hljs-comment">//验证码是一个图片 , 我们需要制作一个图片</span>
BufferedImage image = <span class="hljs-keyword">new</span> BufferedImage(<span class="hljs-number">100</span>,<span class="hljs-number">30</span>,BufferedImage.TYPE_3BYTE_BGR);
<span class="hljs-comment">//图片写入一些东西</span>
Graphics2D graphics = image.createGraphics();
graphics.setColor(Color.red);
<span class="hljs-built_in">String</span> <span class="hljs-built_in">num</span> = <span class="hljs-built_in">String</span>.valueOf(newRandom());
graphics.drawString(<span class="hljs-built_in">num</span>,<span class="hljs-number">10</span>,<span class="hljs-number">10</span>);
<span class="hljs-comment">//想办法让浏览器知道我们给的是一张图片</span>
response.setContentType(<span class="hljs-string">"image/jpg"</span>);
<span class="hljs-comment">//让网站去打开图片</span>
ImageIO.write(image,<span class="hljs-string">"jpg"</span>,response.getOutputStream());
}
<span class="hljs-comment">//生成随机数</span>
public <span class="hljs-built_in">int</span> newRandom(){
<span class="hljs-built_in">int</span> <span class="hljs-built_in">num</span> = (<span class="hljs-built_in">int</span>)(Math.random()*<span class="hljs-number">9</span>+<span class="hljs-number">1</span>)*<span class="hljs-number">100000</span>;
<span class="hljs-keyword">return</span> <span class="hljs-built_in">num</span>;
}
手机扫一扫
移动阅读更方便
你可能感兴趣的文章