jsp-servlet开发
STS中开发步骤
建普通jsp项目过程
1.建项目(非Maven项目)
new----project----other----Web----Dynamic Web Project
2.下载包放到LIB目录中,如果是Maven项目可以自动导包(pom.xml中设置好)
3.设置工作空间,网页的编码(我常用UTF-8)
3.分层(dao,vo,servlet…)
一个构建maven项目的过程
《1》
《2》
《3》配置maven
《4》下图中,爆红,是因为,Dynamic Web Module模式版本太低了,现在我们都3.x了,这里还是2.5,如下面第二图所示。
处理办法:
先去掉那个勾选,再点应用(apply),选勾选3.1版本,同时到下面点击’Further configuration available…',我们勾选Generate web.xml。。。,让项目自建web.xml文件。
《5》,build path,即增加jdk库,apache库
一个自已写的settings.xml,里面没有设置从远程仓库上传,下载功能,只设了阿里云下载镜像包。对IDEA 也适用,
<?xml version="1.0" encoding="UTF-8"?>
<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0 http://maven.apache.org/xsd/settings-1.0.0.xsd">
<localRepository>C:\Users\Administrator\Desktop\maven\repository</localRepository>
<pluginGroups>
<pluginGroup>org.codehaus.plugins</pluginGroup>
</pluginGroups>
<proxies>
</proxies>
<mirrors>
<mirror>
<id>aliyunmaven</id>
<name>aliyun maven</name>
<url>http://maven.aliyun.com/nexus/content/groups/public/</url>
<mirrorOf>central</mirrorOf>
</mirror>
</mirrors>
<profiles>
<!--jdk版本一劳永逸的改法,因为系统默认为1.5版,太扯了-->
<profile>
<id>jdk-1.8</id>
<activation>
<activeByDefault>true</activeByDefault>
<jdk>jdk1.8</jdk>
</activation>
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<maven.compiler.compilerVersion>1.8</maven.compiler.compilerVersion>
</properties>
</profile>
</profiles>
<!--激活下载仓库预文件-->
<activeProfiles>
<activeProfile>myProfile</activeProfile>
</activeProfiles>
</settings>
jsp-servlet验证码开发
1.index.jsp嵌入由下面的servlet生成的图片并刷新可重新获得验证码
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>登录界面</title>
<script>
function reloadCode() {
var time=new Date().getTime();
document.getElementById("imagecode").src="<%= request.getContextPath()%>/servlet/ImageServlet?date="+time;
}
/* js部分的Date相关是防止浏览器缓存后不能正常刷新,添加时间的唯一性来实现能够及时刷新和展示。
js 部分可以参阅:JavaScript 语言入门
也可以在ImageServlet中添加防止浏览器缓存的语句:
response.setHeader("Pragma", "No-cache");*/
</script>
</head>
<body>
<form action="<%= request.getContextPath()%>/servlet/ValidateServlet" method="get" >
请您输入账号:
<input type="text" name="account" />
<BR>
请您输入密码:
<input type="password" name="password" />
<BR>
验证码:<input type="text" name="checkCode"/><br/>
<img alt="验证码" id="imagecode" src="<%= request.getContextPath()%>/servlet/ImageServlet"/>
<a href="javascript:reloadCode();">看不清楚</a><br>
<br/><input type="submit" value="提交">
</form>
</body>
</html>
2.Servelt生成验证码图片
import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ImageServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
BufferedImage bi = new BufferedImage(68, 22, BufferedImage.TYPE_INT_RGB);//创建图像缓冲区
Graphics g = bi.getGraphics(); //通过缓冲区创建一个画布
Color c = new Color(200, 150, 255); //创建颜色
g.setColor(c); //为画布创建背景颜色
g.fillRect(0, 0, 68, 22); //填充矩形
char[] ch = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".toCharArray();//转化为字符型的数组
Random r = new Random();
int len = ch.length;
int index; //index用于存放随机数字
StringBuffer sb = new StringBuffer();
for (int i = 0; i < 4; i++) {
index = r.nextInt(len); //产生随机数字
g.setColor(new Color(r.nextInt(88), r.nextInt(188), r.nextInt(255))); //设置颜色
g.drawString(ch[index] + "", (i * 15) + 3, 18); //画数字以及数字的位置
sb.append(ch[index]);
}
request.getSession().setAttribute("piccode", sb.toString());
ImageIO.write(bi, "JPG", response.getOutputStream());
}
}
3.Servlet逻辑判断验证是否正确,再进行相应的跳转
public class ValidateServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setHeader("Pragma", "No-cache");
response.setContentType("text/html;charset=utf-8");//解决乱码问题
//得到提交的验证码
String code = request.getParameter("checkCode");
//获取session中的验证码
HttpSession session = request.getSession();
String randStr = (String)session.getAttribute("piccode");
response.setCharacterEncoding("utf8");
PrintWriter out = response.getWriter();
if(!code.equals(randStr)){
out.println("验证码错误!");
}
else{
out.println("验证码正确!跳转到LoginServlet......");
}
out.flush();//将流刷新
out.close();//将流关闭
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doGet(request, response);
}
}
4.测试
我首先:生成验证码图片看看
http://localhost/yanzhengma/index.jsp
然后,测试提交效果。
JFreeChart开发图片报表
在web开发过程中,经常需要将数据以比较直观的方式显示出来,此时报表能够起到很好的作用。
JAVA技术报表的代表产品有:JFreeChart,JasperReports,iReport,FineReport,iText等。
下载JFreeChart包
https://sourceforge.net/projects/jfreechart/
下载后解压:到解压的文件目录的lib下复制如下两个文件到WebContent目录WEB-INF的lib目录下
1.web.xml
<servlet>
<servlet-name>DisplayChart</servlet-name>
<servlet-class>org.jfree.chart.servlet.DisplayChart</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>DisplayChart</servlet-name>
<url-pattern>/DisplayChart</url-pattern>
</servlet-mapping>
1.1开发柱状报表
《1》。实例化数据集org.jfree.data.category.DefaultCategoryDataset类
《2》,添加数据给DefaultCategoryDatase对象,当然也可以从数据库中查询
datase.addValue(value1,value2,value3);
value1为纵坐标的值,value2是纵坐标中的各个项目的种类,value3是横坐标中各个项目的种类。实际上,value1即为人数数据,value2可以为NULL,因为纵坐标没有对人数进行细分。
《3》。通过工厂类org.jfree.chart.ChartFactory创建柱状报表。
JFreeChart chart = ChartFactory.createBarChart(value1,value2,value3,value4,value5,false,false,false);
各参数的意义如下
value1:表示柱状报表的标题,
value2:表示柱状表的横坐标名称,如“成绩”
value3:表示。。。。纵坐标的名称,如‘人数’
value4:数据集
value5:表示的是所作之图是水平还是坚直,可以用org.jfree.chart.plot.PlotOrientation的常量表示
.VERTICAL 和 .HORIZONTAL
《4》。用org.jfree.chart.servlet.ServletUtilities将chart保存为图片,确定宽,高,并确定保存的范围(一般session)然后组图片路径。
String filename = ServeltUtilities.saveChartAsPng(chart,width,height,session);
String graphUrl = "/项目名/DisplayChart?filename="+filename;
《5》设置中文体体,在jsp页面中显示图片
Font font = new Font("隶书", Font.PLAIN, 20);
StandardChartTheme stheme=new StandardChartTheme("CN");
stheme.setExtraLargeFont(font); //设置标题字体
stheme.setLargeFont(new Font("宋书",Font.PLAIN,20)); //设置轴向字体
stheme.setRegularFont(font); //设置图例字体
ChartFactory.setChartTheme(stheme); //应用字体功能
jsp页中显示图片
<img src="<%=graphURL%"></img>
案例:显示男女成绩分布报表
<%@page import="org.jfree.data.general.DatasetUtilities"%>
<%@page import="org.jfree.data.category.CategoryDataset"%>
<%@page import="org.jfree.chart.StandardChartTheme"%>
<%@page import="org.jfree.chart.servlet.ServletUtilities"%>
<%@page import="org.jfree.chart.JFreeChart"%>
<%@page import="org.jfree.chart.plot.PlotOrientation"%>
<%@page import="org.jfree.chart.ChartFactory,java.awt.*"%>
<%@page import="org.jfree.data.category.DefaultCategoryDataset"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>柱状报表2美化了</title>
</head>
<body>
<%
double[][] data = new double[][]{{1,2},{3,5},{7,5},{7,8},{2,6}};
String[] rowKeys = new String[]{"优秀","良好","中等","及格","不及格"};
String[] columnKeys = {"男","女"};
Font font = new Font("隶书", Font.PLAIN, 20);
StandardChartTheme stheme=new StandardChartTheme("CN");
stheme.setExtraLargeFont(font); //设置标题字体
stheme.setLargeFont(new Font("宋书",Font.PLAIN,20)); //设置轴向字体
stheme.setRegularFont(font); //设置图例字体
ChartFactory.setChartTheme(stheme);
CategoryDataset dataset = DatasetUtilities.createCategoryDataset(rowKeys,columnKeys,data);
JFreeChart chart =ChartFactory.createBarChart3D("考试成绩统计表(按性别)","成绩","人数",dataset,PlotOrientation.VERTICAL,true,false,false);
String filename = ServletUtilities.saveChartAsPNG(chart,600,400,session);
String graphURL = "/jfreechart/DisplayChart?filename="+filename;
%>
<img src="<%=graphURL %>">
</body>
</html>
测试 http://localhost:8080/jfreechart/barchar2.jsp
1.2开发饼状报表
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>饼状报表</title>
</head>
<body>
<%
DefaultPieDataset dataset = new DefaultPieDataset();
dataset.setValue("优秀",0.45);
dataset.setValue("良好",0.3);
dataset.setValue("中等",0.1);
dataset.setValue("及格",0.05);
dataset.setValue("不及格",0.1);
Font font = new Font("隶书", Font.PLAIN, 20);
StandardChartTheme stheme=new StandardChartTheme("CN");
stheme.setExtraLargeFont(font); //设置标题字体
stheme.setLargeFont(new Font("宋书",Font.PLAIN,20)); //设置轴向字体
stheme.setRegularFont(font); //设置图例字体
ChartFactory.setChartTheme(stheme);
JFreeChart chart = ChartFactory.createPieChart3D("考试成绩统计图",dataset,true,false,false);
String filename = ServletUtilities.saveChartAsPNG(chart,600,400,session);
String graphURL = "/jfreechart/DisplayChart?filename="+filename;
%>
<img src="<%=graphURL %>"></img>
</body>
</html>
1.3曲线报表
下面是双曲线,单曲线只要减少一个TimeSeries对象即可。
@page import="org.jfree.chart.servlet.ServletUtilities"%>
<%@page import="org.jfree.chart.title.TextTitle"%>
<%@page import="org.jfree.data.time.Month"%>
<%@page import="org.jfree.data.time.TimeSeries"%>
<%@page import="org.jfree.data.time.TimeSeriesCollection"%>
<%@page import="org.jfree.chart.ChartFactory"%>
<%@page import="java.awt.*"%>
<%@page import="org.jfree.chart.StandardChartTheme"%>
<%@page import="org.jfree.chart.JFreeChart"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<html>
<head>
<title>曲线图报表</title>
</head>
<body>
<%
TimeSeriesCollection lineDataset = new TimeSeriesCollection();
TimeSeries timeSeries = new TimeSeries("熊少文",Month.class);
timeSeries.add(new Month(1,2024),85);
timeSeries.add(new Month(2,2024),76);
timeSeries.add(new Month(3,2024),65);
timeSeries.add(new Month(4,2024),80);
timeSeries.add(new Month(5,2024),66);
timeSeries.add(new Month(6,2024),72);
timeSeries.add(new Month(7,2024),83);
timeSeries.add(new Month(8,2024),88);
timeSeries.add(new Month(9,2024),85);
timeSeries.add(new Month(10,2024),74);
timeSeries.add(new Month(11,2024),78);
timeSeries.add(new Month(12,2024),63);
lineDataset.addSeries(timeSeries);
TimeSeries timeSeries2 = new TimeSeries("徐会凤",Month.class);
timeSeries2.add(new Month(1,2024),98);
timeSeries2.add(new Month(2,2024),95);
timeSeries2.add(new Month(3,2024),89);
timeSeries2.add(new Month(4,2024),88);
timeSeries2.add(new Month(5,2024),86);
timeSeries2.add(new Month(6,2024),82);
timeSeries2.add(new Month(7,2024),93);
timeSeries2.add(new Month(8,2024),98);
timeSeries2.add(new Month(9,2024),85);
timeSeries2.add(new Month(10,2024),74);
timeSeries2.add(new Month(11,2024),78);
timeSeries2.add(new Month(12,2024),83);
lineDataset.addSeries(timeSeries2);
JFreeChart chart = ChartFactory.createTimeSeriesChart("每月考试成绩","月份","成绩",lineDataset,true,false,false);
Font font = new Font("隶书", Font.PLAIN, 20);
StandardChartTheme stheme=new StandardChartTheme("CN");
stheme.setExtraLargeFont(font); //设置标题字体
stheme.setLargeFont(new Font("宋书",Font.PLAIN,20)); //设置轴向字体
stheme.setRegularFont(font); //设置图例字体
ChartFactory.setChartTheme(stheme);
//设置子标题
TextTitle subTtitle = new TextTitle("2024年度");
chart.addSubtitle(subTtitle);
//设置主标题
chart.setTitle(new TextTitle("每月月考成绩"));
chart.setAntiAlias(true);
String filename = ServletUtilities.saveChartAsPNG(chart,600,400,session);
String graphURL =request.getContextPath()+"/DisplayChart?filename="+filename;
%>
<img src="<%=graphURL%>">
</body>
</html>
iText开发动态PDF报表
pdf是由服务器生成的,不是客户端生成的。
该应用,我用maven项目来做,因为iText pdf java包太难自主下载了,我用maven自动下载。
-
新建一个maven工程 maventest
-
导包pom.xml
<dependencies>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itext7-core</artifactId>
<version>7.1.9</version>
<type>pom</type>
</dependency>
</dependencies>
- 建一个jsp页面,创建一个空白文档
<%@page import="com.itextpdf.layout.Document"%>
<%@page import="com.itextpdf.kernel.pdf.PdfDocument"%>
<%@page import="com.itextpdf.kernel.pdf.PdfWriter"%>
<%@page import="com.itextpdf.kernel.pdf.DocumentProperties"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
String des="C:\\";
String dest = des+"sample.pdf";
PdfWriter writer = new PdfWriter(dest);
// 2、创建一个 PdfDocument,参数为PdfWriter
PdfDocument pdfDoc = new PdfDocument(writer);
// 3、用PdfDocument创建一个空白 page
pdfDoc.addNewPage();
// 4、创建一个 Document,参数为PdfDocument
Document document = new Document(pdfDoc);
// 5、关闭 document,PdfDocument
document.close();
pdfDoc.close();
%>
</body>
</html>