上回分享了第一个spring boot程序之后,相信大家对spring boot已经有了初步的认识,这次分享下在springboot中使用servlet和模板引擎freemarker
一 依赖的引入
org.springframework.boot
spring-boot-starter-freemarker
spring.freemarker.allow-request-override=false
spring.freemarker.cache=false
spring.freemarker.check-template-location=true
spring.freemarker.charset=UTF-8
spring.freemarker.content-type=text/html
spring.freemarker.expose-request-attributes=false
spring.freemarker.expose-session-attributes=false
spring.freemarker.expose-spring-macro-helpers=false
#spring.freemarker.prefix=
#spring.freemarker.request-context-attribute=
#spring.freemarker.settings.*=
#spring.freemarker.suffix=.ftl
#spring.freemarker.template-loader-path=classpath:/templates/ #comma-separated list
#spring.freemarker.view-names= # whitelist of view names that can be resolved
三 编写测试用的controller和模板文件
package com.debug;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@Controller
public class FMController {
@RequestMapping("/useFm")
public String useFm(HttpServletRequest req,HttpServletResponse res) {
String name=req.getParameter("name");
req.setAttribute("name", name);
return "/useFm";
}
}
fm测试
${name}
spring boot也提供了一个自己的模板引擎,因为我开发使用freemarker较多所以就用它来写例子,大家可以选择其他的如velocity等
四 在springboot中使用servlet
有时可能由于历史遗留问题老项目中存在很多servlet如验证码、文件上传等,重新写费时费力,这种情况下就可以保留原先的,使用注解就可以解决
1 改装之前的servlet
package com.debug.servlet;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
@WebServlet(urlPatterns="/imageCode.do",name="ImageCodeServlet")
public class ImageCodeServlet extends HttpServlet{
private static final long serialVersionUID = 1L;
private static int WIDTH = 100;
private static int HEIGHT = 44;
public char[] generateCheckCode() {
// 定义验证码的字符表
String chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
char[] rands = new char[4];
for (int i = 0; i < 4; i++) {
int rand = (int) (Math.random() * 36);
rands[i] = chars.charAt(rand);
}
return rands;
}
public void drawRands(Graphics g, char[] rands) {
g.setColor(Color.DARK_GRAY);
g.setFont(new Font(null, Font.ITALIC | Font.BOLD, 25));
// 在不同的高度上输出验证码的每个字符
g.drawString("" + rands[0], 1, 30);
g.drawString("" + rands[1], 25, 35);
g.drawString("" + rands[2], 45, 29);
g.drawString("" + rands[3], 65, 25);
}
public void drawBackground(Graphics g) {
// 画背景
g.setColor(new Color(0xDCDCDC));
g.fillRect(0, 0, WIDTH, HEIGHT);
// 随机产生120个干扰点
for (int i = 0; i < 120; i++) {
int x = (int) (Math.random() * WIDTH);
int y = (int) (Math.random() * HEIGHT);
int red = (int) (Math.random() * 255);
int green = (int) (Math.random() * 255);
int blue = (int) (Math.random() * 255);
g.setColor(new Color(red, green, blue));
g.drawOval(x, y, 1, 0);
}
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession session = request.getSession();
response.setContentType("image/jpeg");
ServletOutputStream sos = response.getOutputStream();
// 设置浏览器不缓存此图片
response.setHeader("Pragma", "No-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
// 创建内存图像并获得其图形上下文
BufferedImage image = new BufferedImage(WIDTH, HEIGHT,
BufferedImage.TYPE_INT_RGB);
Graphics g = image.getGraphics();
// 产生随机的验证码
char[] rands = generateCheckCode();
// 产生图像
drawBackground(g);
drawRands(g, rands);
// 结束图像的绘制过程,完成图像
g.dispose();
// 将图像输出到客户端
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ImageIO.write(image, "JPEG", bos);
byte[] buf = bos.toByteArray();
response.setContentLength(buf.length);
sos.write(buf);
bos.close();
sos.close();
// 将当前验证码存入到session中
session.setAttribute("checkCode", new String(rands));
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
2 注册servlet
在App.java加注解@ServletComponentScan即可,如下所示
package com.debug;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;
/**
* Hello world!
*
*/
@SpringBootApplication
@ServletComponentScan
public class App
{
public static void main( String[] args )
{
System.out.println( "Hello World!" );
SpringApplication.run(App.class, args);
}
}
下回打算接着分享spring boot整合mybatis,初学者博客可能写的不好,随意看看有问题写评论给我