Java Code Examples for javax.servlet.ServletResponse#setContentType()

The following examples show how to use javax.servlet.ServletResponse#setContentType() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: CharsetFilter.java    From rice with Educational Community License v2.0 6 votes vote down vote up
public void doFilter(ServletRequest request, ServletResponse response,
        FilterChain next) throws IOException, ServletException {
    // Respect the client-specified character encoding
    // (see HTTP specification section 3.4.1)
    if (null == request.getCharacterEncoding()) {
        request.setCharacterEncoding(encoding);
    }

    /**
     * Set the default response content type and encoding
     */
    response.setContentType("text/html; charset=UTF-8");
    response.setCharacterEncoding("UTF-8");

    next.doFilter(request, response);
}
 
Example 2
Source File: ListUserServlet.java    From onlineTest with Apache License 2.0 6 votes vote down vote up
@Override
public void service(ServletRequest request, ServletResponse response)
		throws ServletException, IOException {
	request.setCharacterEncoding("utf-8");
	response.setContentType("text/html;charset=utf-8");
	UserDAO userDAO = new UserDAO();
	List<User> users = null;
	try {
		users = userDAO.list();
	} catch (Exception e) {
		e.printStackTrace();
	}
	request.setAttribute("users", users);
	request.getRequestDispatcher("/WEB-INF/view/list-user.jsp").forward(request, response);

}
 
Example 3
Source File: JARVIS.java    From JARVIS with MIT License 6 votes vote down vote up
@Override
public void service(ServletRequest req, ServletResponse res)
		throws ServletException, IOException {
	//��ȡ����
	String order = req.getParameter("order");
	OutputStream os = s.getOutputStream();
	//������Server
	os.write(order.getBytes());
	os.flush();
	//����Serverת�����ķ�����Ϣ
	InputStream is = s.getInputStream();
	byte[] buf = new byte[1024];
	int Len = is.read(buf);
	String result = new String(buf,0,Len);
	res.setContentType("text/html;charset=GBK");
	PrintWriter PW = res.getWriter();
	
	PW.write("<html>");
	PW.write("<title>");
	PW.write("</title>");
	PW.write("<body align=\"center\">");
	PW.write("<font size=70px>"+result+"<br><br><font>");
	PW.write("</body>");
	PW.write("</html>");
}
 
Example 4
Source File: SetCharacterEncodingFilter.java    From spacewalk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Select and set (if specified) the character encoding to be used to
 * interpret request parameters for this request.
 *
 * @param request The servlet request we are processing
 * @param response The servlet response we are creating
 * @param chain The filter chain we are processing
 *
 * @exception IOException if an input/output error occurs
 * @exception ServletException if a servlet error occurs
 */
public void doFilter(ServletRequest request, ServletResponse response,
                     FilterChain chain)
       throws IOException, ServletException {

    // Conditionally select and set the character encoding to be used
    if ((request.getCharacterEncoding() == null)) {
        String encodingIn = selectEncoding(request);
        if (encoding != null) {
            request.setCharacterEncoding(encodingIn);
            response.setContentType("text/html; charset=" + encodingIn);
            response.setCharacterEncoding(encodingIn);
        }
    }

    // Pass control on to the next filter
    chain.doFilter(request, response);

}
 
Example 5
Source File: SetCharacterEncodingFilter.java    From uyuni with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Select and set (if specified) the character encoding to be used to
 * interpret request parameters for this request.
 *
 * @param request The servlet request we are processing
 * @param response The servlet response we are creating
 * @param chain The filter chain we are processing
 *
 * @exception IOException if an input/output error occurs
 * @exception ServletException if a servlet error occurs
 */
public void doFilter(ServletRequest request, ServletResponse response,
                     FilterChain chain)
       throws IOException, ServletException {

    // Conditionally select and set the character encoding to be used
    if ((request.getCharacterEncoding() == null)) {
        String encodingIn = selectEncoding(request);
        if (encoding != null) {
            request.setCharacterEncoding(encodingIn);
            response.setContentType("text/html; charset=" + encodingIn);
            response.setCharacterEncoding(encodingIn);
        }
    }

    // Pass control on to the next filter
    chain.doFilter(request, response);

}
 
Example 6
Source File: LoginServlet.java    From onlineTest with Apache License 2.0 5 votes vote down vote up
@Override
public void service(ServletRequest request, ServletResponse response)
		throws ServletException, IOException {
	response.setContentType("text/html;charset=utf-8");
	
	String loginname = request.getParameter("loginname");
	String password = request.getParameter("password");
	UserDAO userDAO = new UserDAO();
	User user = userDAO.login(loginname, password);
	PrintWriter out = response.getWriter();
	out.println("<!DOCTYPE html>");
	out.println("<html>");
	out.println("	<head>");
	out.println("	</head>");
	out.println("	<body>");
	if(user != null){			
		((HttpServletRequest)request).getSession().setAttribute("user", user);
		if("1".equals(user.getUlevel())){
			out.println("<div align=\"center\">欢迎 " + user.getUname() + ", 登录成功!<a href=\"/user/list.action\">点击进入管理员页面</a></div>");
		}else{
			out.println("<div align=\"center\">欢迎 " + user.getUname() + ", 登录成功!<a href=\"/test.action\">点击开始考试</a></div>");
		}
	}else{
		out.println("<div align=\"center\">登录失败,请重新登录<a href=\"/login.html\">登录</a></div>");
	}         
	out.println("	</body>");
	out.println("</html>");
	out.flush();
	out.close();
}
 
Example 7
Source File: BackupFilter.java    From gocd with Apache License 2.0 5 votes vote down vote up
private void generateResponseForIsBackupFinishedAPI(ServletResponse response) {
    response.setContentType("application/json");
    JsonObject json = new JsonObject();
    json.addProperty("is_backing_up", backupService.isBackingUp());
    try {
        response.getWriter().print(json);
    } catch (IOException e) {
        LOGGER.error("General IOException: {}", e.getMessage());
    }
}
 
Example 8
Source File: XSSWebAppSRPWDelay.java    From spiracle with Apache License 2.0 5 votes vote down vote up
@Override
public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
    try {
        Thread.sleep(10000);
    } catch (Exception e) {
        e.printStackTrace();
    }
    res.setContentType("text/html");
    PrintWriter out = res.getWriter();
    ReadHTML.readHTML(out, req.getParameter("taintedtext"), req);
}
 
Example 9
Source File: SendServlet.java    From qmq with Apache License 2.0 5 votes vote down vote up
private void asyncError(AsyncContext asyncContext, Message message) {
    try {
        Map<String, Object> result = new HashMap<>();
        result.put("status", -1);
        result.put("error", message.getMessageId());
        ServletResponse response = asyncContext.getResponse();
        response.setContentType("application/json");
        MAPPER.writeValue(response.getWriter(), result);
    } catch (Exception e) {
        logger.error("return message error {} - {}", message.getSubject(), message.getMessageId());
    } finally {
        asyncContext.complete();
    }
}
 
Example 10
Source File: MyLoginFilter.java    From easyweb-shiro with MIT License 5 votes vote down vote up
@Override
protected boolean onAccessDenied(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {
    Subject subject = getSubject(servletRequest, servletResponse);
    if (!subject.isAuthenticated() && !subject.isRemembered()) {
        if (isAjax((HttpServletRequest) servletRequest)) {
            servletResponse.setContentType("application/json;charset=UTF-8");
            PrintWriter out = servletResponse.getWriter();
            out.write("{\"msg\":\"登录过期,请重新登录\",\"code\":401}");
            out.flush();
            return false;
        }
    }
    return true;
}
 
Example 11
Source File: RegServlet.java    From onlineTest with Apache License 2.0 5 votes vote down vote up
@Override
public void service(ServletRequest request, ServletResponse response)
		throws ServletException, IOException {
	    
	request.setCharacterEncoding("utf-8");
	response.setContentType("text/html;charset=utf-8");
	String loginname = request.getParameter("loginname");
	String password = request.getParameter("password");
	String email = request.getParameter("email");
	String phone = request.getParameter("phone");
	String sex = request.getParameter("sex");
	String birth = request.getParameter("birth");
	String uname = request.getParameter("uname");
	
	User user = new User(0, loginname, password, email, phone, sex, birth, uname, "0");
	UserDAO userDAO = new UserDAO();
	PrintWriter out = response.getWriter();
	out.println("<!DOCTYPE html>");
	out.println("<html>");
	out.println("	<head>");
	out.println("	</head>");
	out.println("	<body>");
	if(userDAO.add(user)){
		out.println("	恭喜,注册成功!<a href=\"/login.html\">进入登录页面</a>");
	}else{
		out.println("	抱歉,注册失败!<a href=\"/reg.html\">回到首页</a>");
	}
	out.println("	</body>");
	out.println("</html>");
	out.flush();
	out.close();
}
 
Example 12
Source File: JsonUtil.java    From spring-cloud-yes with Apache License 2.0 5 votes vote down vote up
public static void writeJson(ServletResponse response, AjaxResult ajaxResult) {
    try {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        PrintWriter out = response.getWriter();
        out.write(
                JsonMapper.defaultMapper()
                        .toJson(ajaxResult)
        );
        out.flush();
        out.close();
    } catch (IOException e) {
        log.error("发生异常。", e);
    }
}
 
Example 13
Source File: CharsetFilter.java    From bamboobsc with Apache License 2.0 5 votes vote down vote up
/**
 * BUG FIX, run on newer than Tomcat 8.5.35 or Tomcat-9 version, will error :
 * Resource interpreted as Stylesheet but transferred with MIME type text/html
 */
private void resetCssAndJavascriptContentType(ServletRequest request, ServletResponse response, String requestUrl) {
	if (requestUrl.contains(".css")) {
		response.setContentType("text/css; charset=" + Constants.BASE_ENCODING);
	}
	if (requestUrl.contains(".js")) {
		response.setContentType("application/javascript; charset=" + Constants.BASE_ENCODING);
	}
}
 
Example 14
Source File: GreenStepBaseFormAuthenticationFilter.java    From bamboobsc with Apache License 2.0 5 votes vote down vote up
protected void redirectToLogin(ServletRequest request, ServletResponse response) throws IOException {
 	if ( !Constants.getSystem().equals( Constants.getMainSystem() ) && !isAjaxRequest((HttpServletRequest)request) ) { // 非 core-web
 		try {
	if ( this.loginUseCurrentCookieForGeneralPackage(request, response) ) { // no need to login-page
		String url = SimpleUtils.getHttpRequestUrl( (HttpServletRequest)request );
		logger.warn("URL = " + url );					
		WebUtils.issueRedirect(request, response, url);
		return;
	}
} catch (Exception e) {
	e.printStackTrace();
}
 	}    	
 	if (isAjaxRequest((HttpServletRequest)request)) {
 		response.setCharacterEncoding( Constants.BASE_ENCODING );
 		response.setContentType("application/json");
 		response.getWriter().write(Constants.NO_LOGIN_JSON_DATA);
 		return;
 	}
 	if (this.isIframeMode((HttpServletRequest)request)) { // iframe 不要導向 login.action 因為畫面會怪怪的    		
 		WebUtils.issueRedirect(request, response, "/pages/system/error_static.jsp");
 		return;
 	}    	
 	if (this.isDojoxContentPane((HttpServletRequest)request)) { // 在 dojox.layout.ContentPane 不要出現 login.action 頁面    		
 		WebUtils.issueRedirect(request, response, Constants.DOJOX_CONTENT_PANE_XHR_RE_LOGIN_PAGE);
 		return;
 	}
 	WebUtils.issueRedirect(request, response, getLoginUrl());
 }
 
Example 15
Source File: TestStandardContext.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
@Override
public void doFilter(ServletRequest request, ServletResponse response,
        FilterChain chain) throws IOException, ServletException {
    response.setContentType("text/plain");
    response.getWriter().print("Filter");
    chain.doFilter(request, response);
}
 
Example 16
Source File: XSSWebAppSRSOS.java    From spiracle with Apache License 2.0 4 votes vote down vote up
@Override
public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
    res.setContentType("text/html");
    ServletOutputStream out = res.getOutputStream();
    ReadHTML.readHTML(out, req.getParameter("taintedtext"), req);
}
 
Example 17
Source File: MessageRecordsServlet.java    From qmq with Apache License 2.0 4 votes vote down vote up
private void response(ServletResponse resp) throws IOException {
    resp.setContentType("application/json");
    RecordQueryResult result = new RecordQueryResult(Collections.emptyList());
    resp.getWriter().println(serializer.serialize(result));
}
 
Example 18
Source File: RequestFilter.java    From tomcatsrc with Apache License 2.0 4 votes vote down vote up
private void sendErrorWhenNotHttp(ServletResponse response)
        throws IOException {
    response.setContentType(PLAIN_TEXT_MIME_TYPE);
    response.getWriter().write(sm.getString("http.403"));
    response.getWriter().flush();
}
 
Example 19
Source File: CharacterEncodingFilter.java    From MediaPlayer with GNU General Public License v2.0 4 votes vote down vote up
public void doFilter(ServletRequest request, ServletResponse response,
		FilterChain chain) throws IOException, ServletException {
	request.setCharacterEncoding(encoding);
	response.setContentType("text/html;charset=" + encoding);
	chain.doFilter(request, response);
}
 
Example 20
Source File: RequestFilter.java    From Tomcat8-Source-Read with MIT License 4 votes vote down vote up
private void sendErrorWhenNotHttp(ServletResponse response)
        throws IOException {
    response.setContentType(PLAIN_TEXT_MIME_TYPE);
    response.getWriter().write(sm.getString("http.403"));
    response.getWriter().flush();
}