spring boot 配置servlet

因为项目的需求需要在,spring mvc中添加一个servlet,感觉怪怪的整了好久整了出来。

首先创建一个类,继承httpservlet 实现其中的方法 就跟在平常项目中创建servlet差不多。
public class UploadServlet extends HttpServlet {
private static final long serialVersionUID = -8848851525451098142L;

@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException {
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
Uploader up = new Uploader(request);
up.setSavePath("upload");
String[] fileType = { ".gif", ".png", ".jpg", ".jpeg", ".bmp" };
up.setAllowFiles(fileType);
up.setMaxSize(10000); // 单位KB
try {
up.upload();
} catch (Exception e) {
e.printStackTrace();
}
String callback = request.getParameter("callback");
String result = "{\"name\":\"" + up.getFileName() + "\", \"originalName\": \"" + up.getOriginalName()
+ "\", \"size\": " + up.getSize() + ", \"state\": \"" + up.getState() + "\", \"type\": \""
+ up.getType() + "\", \"url\": \"" + up.getUrl() + "\"}";
result = result.replaceAll("\\\\", "\\\\");
if (callback == null) {
response.getWriter().print(result);
} else {
response.getWriter().print("");
}

}


然后呢将这个类加载进spring中执行servlet的功能

@Bean
public ServletRegistrationBean uploadServletRegistrationBean() {
return new ServletRegistrationBean(new UploadServlet(), "/www/ueditor");
}
在spring中注册一个bean
new ServletRegistrationBean(new UploadServlet(), "/www/ueditor");
ServletRegistrationBean 的构造函数有两个参数一个是你的servlet 另外一个是你的servlet的访问路径

你可能感兴趣的:(java,前端,spring,mvc)