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

The following examples show how to use javax.servlet.ServletResponse#setContentType() . These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.
Example 1
/**
 * 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 2
/**
 * 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 3
Source Project: JARVIS   File: JARVIS.java    License: 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 Project: onlineTest   File: ListUserServlet.java    License: 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 5
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 6
Source Project: onlineTest   File: RegServlet.java    License: 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 7
@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 8
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 9
Source Project: bamboobsc   File: CharsetFilter.java    License: 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 10
Source Project: spring-cloud-yes   File: JsonUtil.java    License: 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 11
Source Project: onlineTest   File: LoginServlet.java    License: 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 12
Source Project: easyweb-shiro   File: MyLoginFilter.java    License: 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 13
Source Project: qmq   File: SendServlet.java    License: 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 14
Source Project: spiracle   File: XSSWebAppSRPWDelay.java    License: 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 15
Source Project: gocd   File: BackupFilter.java    License: 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 16
Source Project: Tomcat8-Source-Read   File: RequestFilter.java    License: 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();
}
 
Example 17
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 18
Source Project: tomcatsrc   File: RequestFilter.java    License: 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 Project: spiracle   File: XSSWebAppSRSOS.java    License: 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 20
Source Project: qmq   File: MessageRecordsServlet.java    License: 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));
}