Java Code Examples for javax.servlet.http.HttpServletRequest#setCharacterEncoding()

The following examples show how to use javax.servlet.http.HttpServletRequest#setCharacterEncoding() . 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
Source Project: hasor   File: RuntimeFilter.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    //
    // .设置编码
    HttpServletRequest httpReq = (HttpServletRequest) request;
    HttpServletResponse httpRes = (HttpServletResponse) response;
    if (StringUtils.isNotBlank(this.httpRequestEncoding)) {
        httpReq.setCharacterEncoding(this.httpRequestEncoding);
    }
    if (StringUtils.isNotBlank(this.httpResponseEncoding)) {
        httpRes.setCharacterEncoding(this.httpResponseEncoding);
    }
    //
    // .执行
    Object result = null;
    try {
        this.beforeRequest(this.appContext, httpReq, httpRes);
        result = doFilter(chain, httpReq, httpRes);
    } finally {
        this.afterResponse(this.appContext, httpReq, httpRes, result);
    }
}
 
Example 2
Source Project: rank   File: GetRank.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {        
    long start = System.currentTimeMillis();
    request.setCharacterEncoding("UTF-8");
    response.setContentType("application/json;charset=UTF-8");
    String url = request.getParameter("url");
    String keyword = request.getParameter("keyword");
    LOGGER.info("url:"+url);
    LOGGER.info("keyword:"+keyword);
    Rank rank = new Rank();
    rank.setUrl(url);
    rank.setKeyword(keyword);
    RANKER.rank(rank);
    
    try (PrintWriter out = response.getWriter()) {
        String json = MAPPER.writeValueAsString(rank);
        out.println(json);
    }
    long cost = System.currentTimeMillis() - start;
    LOGGER.info("GetRank 耗时 "+cost+" 毫秒");
}
 
Example 3
Source Project: MovieManager   File: MovieAction.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	request.setCharacterEncoding("utf-8");
	response.setContentType("text/html;charset=utf-8");
	String update = request.getParameter("update");
	HttpSession session = request.getSession();
	
	MovieService movieService = new MovieServiceImpl();

	List<Movie> allMovies = movieService.queryAllMovies();
	
	session.setAttribute("movie", allMovies);
	
	if("manager".equals(update)) {
		response.sendRedirect("/MovieManager/manager.jsp");
	} else {
		response.sendRedirect("/MovieManager/mainPage.jsp");
	}
	
	
}
 
Example 4
@Test
public void forceEncodingAlwaysSetsEncoding() throws Exception {
	HttpServletRequest request = mock(HttpServletRequest.class);
	request.setCharacterEncoding(ENCODING);
	given(request.getAttribute(WebUtils.ERROR_REQUEST_URI_ATTRIBUTE)).willReturn(null);
	given(request.getAttribute(filteredName(FILTER_NAME))).willReturn(null);

	HttpServletResponse response = mock(HttpServletResponse.class);
	FilterChain filterChain = mock(FilterChain.class);

	CharacterEncodingFilter filter = new CharacterEncodingFilter(ENCODING, true);
	filter.init(new MockFilterConfig(FILTER_NAME));
	filter.doFilter(request, response, filterChain);

	verify(request).setAttribute(filteredName(FILTER_NAME), Boolean.TRUE);
	verify(request).removeAttribute(filteredName(FILTER_NAME));
	verify(response).setCharacterEncoding(ENCODING);
	verify(filterChain).doFilter(request, response);
}
 
Example 5
Source Project: birt   File: ParameterAccessor.java    License: Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Gets a named parameter from the http request. The given parameter name
 * must be in UTF-8.
 * 
 * @param request
 *            incoming http request
 * @param parameterName
 *            parameter name
 * @return
 */

public static String getParameter( HttpServletRequest request,
		String parameterName )
{

	if ( request.getCharacterEncoding( ) == null )
	{
		try
		{
			request.setCharacterEncoding( UTF_8_ENCODE );
		}
		catch ( UnsupportedEncodingException e )
		{
		}
	}
	return htmlEncode( request.getParameter( parameterName ) );
}
 
Example 6
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {

        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();

        // 调用service
        LoginService service = new LoginServiceImpl();

        // 对于此功能,就直接从session中取值
        HttpSession session = request.getSession();
        String loginName = (String) session.getAttribute("LoginName");

        try {
            Login login = service.queryLogin(loginName);
            Gson gson = new Gson();
            out.print(gson.toJson(login));
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
 
Example 7
protected void doPost(HttpServletRequest request, HttpServletResponse response)
		throws ServletException, IOException {
	request.setCharacterEncoding("UTF-8");
	response.setCharacterEncoding("UTF-8");
	HttpSession session = request.getSession();
	PrintWriter out = response.getWriter();
	Librarian librarian = (Librarian) session.getAttribute("librarianEntity");
	LibrarianDAO librarianDAO = new LibrarianDAO();
	// 获取表单数据
	String oldPw = SecurityUtil.md5(request.getParameter("old"));
	String newPw = SecurityUtil.md5(request.getParameter("new"));
	String confirm = SecurityUtil.md5(request.getParameter("confirm"));
	// 检查“新密码”和“确认密码”是否相同
	if (newPw.equals(confirm)) {
		if (librarianDAO.changePasswordByOldPassword_NewPassword(librarian.getName(), oldPw, newPw)) {
			System.out.println("--Librarian--, 修改密码成功");
			out.print("<script language='javascript'>"
					+ "alert('Congratulation! You have modify password Successfully!');"
					+ "window.location.href='librarianHomepage.jsp';" + "</script>");
		} else {
			System.out.println("旧密码错误");
			out.print("<script language='javascript'>" + "alert('Old Password is error, please input again!');"
					+ "window.location.href='librarianModifyInfo.jsp';" + "</script>");

		}
	} else {
		System.out.println("新密码和确认密码不相同");
		out.print("<script language='javascript'>" + "alert('Comfirm password is different from new Password');"
				+ "window.location.href='librarianModifyInfo.jsp';" + "</script>");
	}

}
 
Example 8
Source Project: xfshxzs   File: WxServlet.java    License: MIT License 5 votes vote down vote up
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // 设置编码格式为utf-8,防止中文乱码
    request.setCharacterEncoding("utf-8");
    response.setCharacterEncoding("utf-8");
    PrintWriter out = null;
    try {
        out = response.getWriter();
        WxXmlMessage wx = XStreamTransformer.fromXml(WxXmlMessage.class, request.getInputStream());
        wx.setContent(wx.getContent().trim());// 过滤两边空格
        System.out.println("消息:\n " + wx.toString());
        // 订阅事件
        router.rule().async(false).msgType(WxConsts.XML_MSG_EVENT).event(WxConsts.EVT_SUBSCRIBE)
                .handler(new SubscribeEventHandler()).end();
        // 文本消息
        router.rule().async(false).msgType(WxConsts.XML_MSG_TEXT).handler(new TextMessageHandler()).next();
        // 电影消息
        router.rule().async(false).msgType(WxConsts.XML_MSG_TEXT).rContent("电影|更多")
                .handler(new MovieMessageHandler()).end();
        // ONE消息
        router.rule().async(false).msgType(WxConsts.XML_MSG_TEXT).rContent("来一发").handler(new OneMessageHandler())
                .end();
        // 天气消息
        router.rule().async(false).msgType(WxConsts.XML_MSG_TEXT).rContent("(.+?天气)")
                .handler(new WeatherMessageHandler()).end();
        // 快递消息
        router.rule().async(false).msgType(WxConsts.XML_MSG_TEXT).matcher(new ExpressMatcher())
                .handler(new ExpressMessageHandler()).end();
        WxXmlOutMessage xmlOutMsg = router.route(wx);
        if (xmlOutMsg != null)
            out.print(xmlOutMsg.toXml());
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        out.close();
    }
}
 
Example 9
Source Project: PeonyFramwork   File: GmServlet.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * gm http消息入口
 * @param req
 * @param resp
 * @throws ServletException
 * @throws IOException
 */
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
    try {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=utf-8");
        doGm(req, resp);
    }catch (Throwable e){
        resp.getWriter().write("error:"+e.getMessage());
    }
}
 
Example 10
Source Project: my-site   File: AttAchController.java    License: Apache License 2.0 5 votes vote down vote up
@ApiOperation("markdown文件上传")
@PostMapping("/uploadfile")
public void fileUpLoadToTencentCloud(HttpServletRequest request,
                                            HttpServletResponse response,
                                            @ApiParam(name = "editormd-image-file", value = "文件数组", required = true)
                                            @RequestParam(name = "editormd-image-file", required = true)
                                            MultipartFile file){
    //文件上传
    try {
        request.setCharacterEncoding( "utf-8" );
        response.setHeader( "Content-Type" , "text/html" );

        String fileName = TaleUtils.getFileKey(file.getOriginalFilename()).replaceFirst("/","");

        qiniuCloudService.upload(file, fileName);
        AttAchDomain attAch = new AttAchDomain();
        HttpSession session = request.getSession();
        UserDomain sessionUser = (UserDomain) session.getAttribute(WebConst.LOGIN_SESSION_KEY);
        attAch.setAuthorId(sessionUser.getUid());
        attAch.setFtype(TaleUtils.isImage(file.getInputStream()) ? Types.IMAGE.getType() : Types.FILE.getType());
        attAch.setFname(fileName);
        attAch.setFkey(qiniuCloudService.QINIU_UPLOAD_SITE + fileName);
        attAchService.addAttAch(attAch);
        response.getWriter().write( "{\"success\": 1, \"message\":\"上传成功\",\"url\":\"" + attAch.getFkey() + "\"}" );
    } catch (IOException e) {
        e.printStackTrace();
        try {
            response.getWriter().write( "{\"success\":0}" );
        } catch (IOException e1) {
            throw BusinessException.withErrorCode(ErrorConstant.Att.UPLOAD_FILE_FAIL)
                    .withErrorMessageArguments(e.getMessage());
        }
        throw BusinessException.withErrorCode(ErrorConstant.Att.UPLOAD_FILE_FAIL)
                .withErrorMessageArguments(e.getMessage());
    }
}
 
Example 11
Source Project: rank   File: GetListRank.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    request.setCharacterEncoding("UTF-8");
    response.setContentType("application/json;charset=UTF-8");
    long start = System.currentTimeMillis();
    //获取栏目文章和链接
    String url = request.getParameter("url");
    String nextPageCssQuery = request.getParameter("nextPageCssQuery");
    String nextPageText = request.getParameter("nextPageText");
    String titleCssQuery = request.getParameter("titleCssQuery");
    String lastTime = request.getParameter("lastTime");
    String proxyHost = request.getParameter("proxyHost");
    String proxyPort = request.getParameter("proxyPort");
    LOGGER.info("url:"+url);
    LOGGER.info("nextPageCssQuery:"+nextPageCssQuery);
    LOGGER.info("nextPageText:"+nextPageText);
    LOGGER.info("titleCssQuery:"+titleCssQuery);
    List<Article> articles = PARSER.parse(url, nextPageCssQuery, nextPageText, titleCssQuery);
    LOGGER.info("文章数目:"+articles.size());
    //将栏目文章和链接转换为排名对象
    List<Rank> ranks = new ArrayList<>();
    for(Article article : articles){
        Rank rank = new Rank();
        rank.setKeyword(article.getTitle());
        rank.setUrl(article.getUrl());
        ranks.add(rank);
    }
    //获取排名
    RANKER.rank(ranks);
    LOGGER.info("排名数目:"+ranks.size());
    try (PrintWriter out = response.getWriter()) {
        String json = MAPPER.writeValueAsString(ranks);
        out.println(json);
    }
    long cost = System.currentTimeMillis() - start;
    LOGGER.info("GetListRank 耗时 "+cost+" 毫秒");
}
 
Example 12
Source Project: BotLibre   File: WebServlet.java    License: Eclipse Public License 1.0 5 votes vote down vote up
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	PageStats.page(request);
	request.setCharacterEncoding("utf-8");
	response.setCharacterEncoding("utf-8");
	
	LoginBean loginBean = (LoginBean)request.getSession().getAttribute("loginBean");
	if (loginBean == null) {
		response.sendRedirect("index.jsp");
		return;
	}
	BotBean botBean = loginBean.getBotBean();
	MemoryBean memoryBean = loginBean.getBean(MemoryBean.class);

	try {
		String postToken = (String)request.getParameter("postToken");
		loginBean.verifyPostToken(postToken);
		String instance = (String)request.getParameter("instance");
		if (instance != null) {
			if (botBean.getInstance() == null || !String.valueOf(botBean.getInstanceId()).equals(instance)) {
				botBean.validateInstance(instance);
			}
		}
		if (!botBean.isConnected()) {
			response.sendRedirect("import.jsp");
			return;
		}
		botBean.checkAdmin();
		String submit = (String)request.getParameter("submit");
		String input = (String)request.getParameter("input");
		String web = (String)request.getParameter("web");
		String xpath = (String)request.getParameter("xpath");
		String mode = (String)request.getParameter("mode");
		if (submit != null) {
			memoryBean.processWebImport(input, web, mode, xpath);
		}
	} catch (Throwable failed) {
		loginBean.error(failed);
	}
	response.sendRedirect("import.jsp");
}
 
Example 13
Source Project: Films   File: NewPasswordAction.java    License: Apache License 2.0 5 votes vote down vote up
public ActionForward setPassword(ActionMapping mapping, ActionForm form,
		HttpServletRequest request, HttpServletResponse response) throws IOException {
	// TODO Auto-generated method stub
	request.setCharacterEncoding("utf-8");
	response.setContentType("text/html;charset=utf-8");
	PrintWriter out = response.getWriter();
	NewPasswordForm newPasswordForm = (NewPasswordForm) form;
	String newPwd = newPasswordForm.getNewPassWord();
	user.setUpassword(MyTools.MD5(newPwd));
	userService.update(user);
	request.getSession().invalidate();
	//window.history.back(-1);
	out.print("<script language='javascript'>alert('Change password success!Please relogin!');window.history.back(-1);</script>");
	return null;
}
 
Example 14
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
    req.setCharacterEncoding("UTF-8");
    resp.setContentType("text/plain");
    resp.setCharacterEncoding("UTF-8");
    PrintWriter w = resp.getWriter();
    Map<String,String[]> actual = req.getParameterMap();

    boolean ok = true;
    for (Entry<String,String[]> entry : actual.entrySet()) {
        String[] expectedValue = expected.get(entry.getKey());
        if (expectedValue == null ||
                expectedValue.length != entry.getValue().length) {
            ok = false;
            break;
        }
        for (int i = 0; i < expectedValue.length; i++) {
            if (!expectedValue[i].equals(entry.getValue()[i])) {
                ok = false;
                break;
            }
        }
        if (!ok) {
            break;
        }
    }

    if (ok) {
        w.print("OK");
        return;
    }
    boolean firstParam = true;
    for (Entry<String,String[]> param : actual.entrySet()) {
        if (firstParam) {
            firstParam = false;
        } else {
            w.print(';');
        }
        w.print(param.getKey());
        w.print(':');
        boolean firstValue = true;
        for (String value : param.getValue()) {
            if (firstValue) {
                firstValue = false;
            } else {
                w.print(',');
            }
            w.print('(');
            w.print(value);
            w.print(')');
        }
    }
}
 
Example 15
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	PageStats.page(request);
	request.setCharacterEncoding("utf-8");
	response.setCharacterEncoding("utf-8");
	
	LoginBean loginBean = (LoginBean)request.getSession().getAttribute("loginBean");
	if (loginBean == null) {
		response.sendRedirect("index.jsp");
		return;
	}
	BotBean botBean = loginBean.getBotBean();
	LearningBean bean = loginBean.getBean(LearningBean.class);

	String save = (String)request.getParameter("save");
	String learn = request.getParameter("learningMode");
	String nlp = request.getParameter("nlpVersion");
	String correct = request.getParameter("correctionMode");
	String scriptTimeout = request.getParameter("scriptTimeout");
	String responseMatchTimeout = request.getParameter("responseMatchTimeout");
	String conversationMatchPercentage = request.getParameter("conversationMatchPercentage");
	String discussionMatchPercentage = request.getParameter("discussionMatchPercentage");
	String fragmentMatchPercentage = request.getParameter("fragmentMatchPercentage");
	String learningRate = request.getParameter("learningRate");
	String extraWordPenalty = request.getParameter("extraWordPenalty");
	String lang = request.getParameter("lang");
	boolean emote = "on".equals(request.getParameter("emote"));
	boolean emotions = "on".equals(request.getParameter("emotions"));
	boolean comprehension = "on".equals(request.getParameter("comprehension"));
	boolean consciousness = "on".equals(request.getParameter("consciousness"));
	boolean wiktionary = "on".equals(request.getParameter("wiktionary"));
	boolean responsMatch = "on".equals(request.getParameter("responsMatch"));
	boolean exactMatchFirst = "on".equals(request.getParameter("exactMatchFirst"));
	boolean checkSynonyms = "on".equals(request.getParameter("checkSynonyms"));
	boolean learnGrammar = "on".equals(request.getParameter("learnGrammar"));
	boolean splitParagraphs = "on".equals(request.getParameter("splitParagraphs"));
	boolean synthesize = "on".equals(request.getParameter("synthesizeResponse"));
	boolean fixFormulaCase = "on".equals(request.getParameter("fixFormulaCase"));
	boolean reduceQuestions = "on".equals(request.getParameter("reduceQuestions"));
	boolean trackCase = "on".equals(request.getParameter("trackCase"));
	boolean aimlCompatibility = "on".equals(request.getParameter("aimlCompatibility"));
	boolean disableFlag = "on".equals(request.getParameter("disableFlag"));
	boolean allowJavaScript = "on".equals(request.getParameter("allowJavaScript"));
	boolean penalizeExtraWords = "on".equals(request.getParameter("penalizeExtraWords"));
	try {
		String postToken = (String)request.getParameter("postToken");
		loginBean.verifyPostToken(postToken);
		String instance = (String)request.getParameter("instance");
		if (instance != null) {
			if (botBean.getInstance() == null || !String.valueOf(botBean.getInstanceId()).equals(instance)) {
				botBean.validateInstance(instance);
			}
		}
		if (!botBean.isConnected()) {
			response.sendRedirect("learning.jsp");
			return;
		}
		botBean.checkAdmin();
		if (save != null) {
			bean.save(learn, correct, scriptTimeout, responseMatchTimeout, conversationMatchPercentage, discussionMatchPercentage,
							emote, emotions, disableFlag, allowJavaScript, comprehension, consciousness, wiktionary, responsMatch, exactMatchFirst, checkSynonyms,
							fixFormulaCase, reduceQuestions, trackCase, aimlCompatibility, learnGrammar, splitParagraphs, synthesize, learningRate,
							nlp, lang, fragmentMatchPercentage, penalizeExtraWords, extraWordPenalty);
		}
	} catch (Throwable failed) {
		loginBean.error(failed);
	}
	response.sendRedirect("learning.jsp");
}
 
Example 16
Source Project: StudentManagement   File: AdminDao.java    License: MIT License 4 votes vote down vote up
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	request.setCharacterEncoding("utf-8");
	action = request.getParameter("action");
	//判断所执行操作
	switch (action) {
	//用户操作
	case "query_all_user":
		query_all_user(request, response);break;
	case "insert_user":
		insert_user(request,response);break;
	case "delete_user":
		delete_user(request, response);break;
	case "alter_user":
		alter_user(request, response);break;
	//院系操作
	case "query_all_department":
		query_all_department(request, response);break;
	case "insert_department":
		insert_department(request, response);break;
	case "delete_department":
		delete_department(request, response);break;
	case "alter_department":
		alter_department(request, response);break;
	//班级操作
	case "query_all_class":
		query_all_class(request, response);break;
	case "insert_class":
		insert_class(request, response);break;	
	case "delete_class":
		delete_class(request, response);break;
	case "alter_class":
		alter_class(request, response);break;
	//学生操作
	case "query_all_student":
		query_all_student(request, response);break;
	case "insert_student":
		insert_student(request, response);break;	
	case "delete_student":
		delete_student(request, response);break;
	case "alter_student":
		alter_student(request, response);break;
	//课程操作
	case "course_avg":
		course_avg(request, response);break;
	case "fail_rate":
		fail_rate(request, response);break;
	case "course_ranking":
		course_ranking(request, response);break;
	case "query_all_course":
		query_all_course(request, response);break;
	case "insert_course":
		insert_course(request, response);break;
	case "delete_course":
		delete_course(request, response);break;
	case "alter_course":
		alter_course(request, response);break;
	//成绩操作
	case "query_all_sc":
		query_all_sc(request, response);break;
	case "insert_sc":
		insert_sc(request, response);break;
	case "delete_sc":
		delete_sc(request, response);break;
	case "alter_sc":
		alter_sc(request, response);break;
	default:
		break;
	}
}
 
Example 17
Source Project: OnlineFriend   File: HandleRegister.java    License: Apache License 2.0 4 votes vote down vote up
public void doPost(HttpServletRequest request,HttpServletResponse response)throws ServletException,IOException{
	Register registerBean = new Register();
	request.setAttribute("register", registerBean);
	request.setCharacterEncoding("utf-8");
	response.setCharacterEncoding("utf-8");
	
	//获取注册信息
	String id = StringUtil.xssEncode(request.getParameter("id").trim());
	String password = StringUtil.xssEncode(request.getParameter("password").trim());
	String email = StringUtil.xssEncode(request.getParameter("email").trim());
	String phone = StringUtil.xssEncode(request.getParameter("phone").trim());
	String message = StringUtil.xssEncode(request.getParameter("message"));
	
	boolean isSuccess = false;  //判断注册信息是否符合规定
	if(StringUtil.isNotEmpty(id) &&StringUtil.isNotEmpty(password)){
		isSuccess = true;
		//判断id是否符合标准
		for(int i=0;i<id.length();i++){
			char c = id.charAt(i);
			if(!((c>='a'&&c<='z') || (c>='A'&&c<='Z') || (c>='0'&&c<='9'))){
				isSuccess = false;
				break;
			}
		}
	}
			
	//向 mysql 中注册用户			
	try {	
		if(isSuccess){
			Connection conn = DbConn.getConnection();
			PreparedStatement preparedStatement = conn.prepareStatement("insert into member(id,password,email,phone,message,pic) values(?,?,?,?,?,?)");
			preparedStatement.setString(1, id);
			preparedStatement.setString(2, password);
			preparedStatement.setString(3, email);
			preparedStatement.setString(4, phone);
			preparedStatement.setString(5, message);
			preparedStatement.setString(6, pic);
			
			//执行成功返回行数大于0
			int num = preparedStatement.executeUpdate();
			if(num != 0){
				backNews = "注册成功";
				registerBean.setBackNews(backNews);
				registerBean.setId(id);
				registerBean.setPassword(password);
				registerBean.setEmail(email);
				registerBean.setPhone(phone);
				registerBean.setMessage(message);
				registerBean.setRegisterSuccess(true);
			}
			preparedStatement.close();
			conn.close();
		}
		else{
			backNews = "信息填写不完整或者名字中有非法字符";
			registerBean.setBackNews(backNews);
		}			
	} catch (SQLException e) {
		backNews = "该ID已被使用,请更换ID";
		registerBean.setBackNews(backNews);
	}
			
	RequestDispatcher dispatcher = request.getRequestDispatcher("showRegisterMess.jsp");
	dispatcher.forward(request, response);	
}
 
Example 18
@Override
protected void doGet(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException
{
  log.debug("Start doPost");
  // https://projectforge.micromata.de/secure/SMSReceiver?key=<key>&date=20101105171233&sender=01701891142&msg=Hallo...
  req.setCharacterEncoding("UTF-8");
  final String key = req.getParameter("key");
  final String expectedKey = ConfigXml.getInstance().getReceiveSmsKey();
  if (StringUtils.isBlank(expectedKey) == true) {
    log.warn("Servlet call for receiving sms ignored because receiveSmsKey is not given in config.xml file.");
    response(resp, "NOT YET CONFIGURED");
    return;
  }
  if (expectedKey.equals(key) == false) {
    log.warn("Servlet call for receiving sms ignored because receiveSmsKey does not match given key: " + key);
    response(resp, "DENIED");
    return;
  }
  final String dateString = req.getParameter("date");
  if (StringUtils.isBlank(dateString) == true) {
    log.warn("Servlet call for receiving sms ignored because parameter 'date' is not given.");
    response(resp, "Missing parameter 'date'.");
    return;
  }
  final String sender = req.getParameter("sender");
  if (StringUtils.isBlank(sender) == true) {
    log.warn("Servlet call for receiving sms ignored because parameter 'sender' is not given.");
    response(resp, "Missing parameter 'sender'.");
    return;
  }
  final String msg = req.getParameter("msg");
  if (StringUtils.isBlank(msg) == true) {
    log.warn("Servlet call for receiving sms ignored because parameter 'msg' is not given.");
    response(resp, "Missing parameter 'msg'.");
    return;
  }
  final Date date = MebDao.parseDate(dateString);
  if (date == null) {
    log.warn("Servlet call for receiving sms ignored because couln't parse parameter 'date'.");
    response(resp, "Unsupported date format.");
    return;
  }
  final ConfigurableListableBeanFactory beanFactory = Configuration.getInstance().getBeanFactory();
  beanFactory.autowireBeanProperties(this, AutowireCapableBeanFactory.AUTOWIRE_BY_NAME, false);
  MebEntryDO entry = new MebEntryDO();
  entry.setDate(date);
  entry.setSender(sender);
  entry.setMessage(msg);
  log.info("Servlet-call: date=[" + date + "], sender=[" + sender + "]");
  mebDao.checkAndAddEntry(entry, "SERVLET");
  response(resp, "OK");
}
 
Example 19
protected void service(HttpServletRequest request, HttpServletResponse response)
		throws ServletException, IOException {
	HttpSession session = request.getSession();
	request.setCharacterEncoding("UTF-8");
	response.setCharacterEncoding("UTF-8");
	String bookids = request.getParameter("bookid");
	int bookid = Integer.MAX_VALUE;
	if (bookids != null)
		bookid = Integer.valueOf(bookids);
	Reader reader = (Reader) session.getAttribute("ReaderEntity");
	int userid = Integer.MAX_VALUE;
	if (reader != null) {
		userid = reader.getId();
	}
	BorrowCartDAO borrowCartDAO = new BorrowCartDAO();
	borrowCartDAO.updateBorrowCart(bookid, userid);
	BookDAO bookDAO = new BookDAO();
	Book book = new Book();
	book = bookDAO.searchByID(bookid);
	String state = book.getState();
	if (book != null && !state.equals("inlib")) {
		borrowCartDAO.deleteBorrowCart(bookid, reader.getId());
		response.sendRedirect("readerFailedSubmitBorrowCart.jsp");
	} else {
		BorrowItemDAO borrowItemDAO = new BorrowItemDAO();
		int num = 0;
		List<Cart> carts = borrowCartDAO.getBorrowCartByReaderId(reader.getId());
		for (Cart cart : carts) {
			num++;
		}
		if (num >= 10) {
			PrintWriter out = response.getWriter();
			out.print(
					"<script language='javascript'>alert('You have reserved too many books!');window.location.href='readerFailedSubmitBorrowCart.jsp';</script>");
		} else {
			bookDAO.updateBookStateToReserve(bookid);
			// List<Cart>carts =
			// borrowCartDAO.getBorrowCartByReaderId(userid);
			// for(Cart cart : carts){
			// if(cart.getBookId()==bookid && cart.getReaderId()==userid &&
			// )
			// }
			// 写时还没有更改状态的方法。无法进行判断
			// 已有更改状态的方法,进行更改
			response.sendRedirect("readerSuccessSubmitBorrowCart.jsp");
		}
	}
}
 
Example 20
Source Project: Films   File: PaymentRequestAction.java    License: Apache License 2.0 4 votes vote down vote up
/** 
 * Method execute
 * @param mapping
 * @param form
 * @param request
 * @param response
 * @return ActionForward
 */
public ActionForward payment(ActionMapping mapping, ActionForm form,
		HttpServletRequest request, HttpServletResponse response) {
	// TODO Auto-generated method stub
	try {
		request.setCharacterEncoding("GBK");
	} catch (UnsupportedEncodingException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	String orderid = request.getParameter("orderid");
	String amount = request.getParameter("amount");
	String pd_FrpId = request.getParameter("pd_FrpId");
	String p1_MerId = ConfigInfo.getValue("p1_MerId");
	String keyValue = ConfigInfo.getValue("keyValue");
	String merchantCallbackURL = ConfigInfo.getValue("merchantCallbackURL");		
	String messageType = "Buy"; 
	String currency = "CNY"; 
	String productDesc = ""; 
	String productCat = ""; 
	String productId = ""; 
	String addressFlag = "0"; 	
	String sMctProperties = ""; 
	String pr_NeedResponse = "0"; 
	String md5hmac = PanymentUtil.buildHmac(messageType, p1_MerId, orderid, amount, currency,
			productId, productCat, productDesc, merchantCallbackURL, addressFlag, sMctProperties, 
			pd_FrpId, pr_NeedResponse, keyValue);
	
	request.setAttribute("messageType", messageType);
	request.setAttribute("merchantID", p1_MerId);
	request.setAttribute("orderId", orderid);
	request.setAttribute("amount", amount);
	request.setAttribute("currency", currency);
	request.setAttribute("productId", productId);
	request.setAttribute("productCat", productCat);
	request.setAttribute("productDesc", productDesc);
	request.setAttribute("merchantCallbackURL", merchantCallbackURL);
	request.setAttribute("addressFlag", addressFlag);
	request.setAttribute("sMctProperties", sMctProperties);
	request.setAttribute("frpId", pd_FrpId);
	request.setAttribute("pr_NeedResponse", pr_NeedResponse);
	request.setAttribute("hmac", md5hmac);
	return mapping.findForward("conected");
}