private void get(HttpServletRequest request, HttpServletResponse response) throws IOException { PrintWriter out = response.getWriter(); String sPage = request.getParameter("page"); String sRows = request.getParameter("rows"); String order = request.getParameter("order"); String sort = request.getParameter("sort"); int page = 0; int rows = 0; if (sPage != null && sRows != null) { page = Integer.parseInt(sPage); rows = Integer.parseInt(sRows); } int total = service.count(); List list = service.get(page, rows, order, sort); Map m = new HashMap(); m.put("total", total); m.put("rows", list); JSONArray jsonArray = new JSONArray().fromObject(m); String json = jsonArray.toString(); String j = json.substring(1, json.lastIndexOf("]")); out.write(j); }
@Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { Object usrLogin = request.getSession().getAttribute(Constants.SESS_USER_KEY); String sevPath = request.getServletPath(); logger.info("ServletPath: " + sevPath); String rootPath = ""; if (!StringUtil.isBlankOrNull(sevPath) && !sevPath.equals("/" + showLogin) && !sevPath.equals("/" + login)) { int len = sevPath.split("/").length; for (int i = 2; i < len; i++) { rootPath += "../"; } if (usrLogin == null) { // response.sendRedirect(rootPath+showLogin); StringBuffer toLoginScript = new StringBuffer(); toLoginScript.append("<script type=\"text/javascript\">"); toLoginScript.append("top.window.location=\"" + rootPath + showLogin + "\""); toLoginScript.append("</script>"); logger.info(toLoginScript); PrintWriter writer = response.getWriter(); writer.write(toLoginScript.toString()); writer.flush(); } } return true; }
private Callable<Void> createAsyncCheckCallable(final CacheKey cacheKey) { final HttpServletRequest originalRequest = Context.get().getRequest(); LOG.debug( "OriginalRequest: url={}, uri={}, servletPath={}", originalRequest.getRequestURL(), originalRequest.getRequestURI(), originalRequest.getServletPath()); final HttpServletRequest request = new PreserveDetailsRequestWrapper(originalRequest); return ContextPropagatingCallable.decorate( new Callable<Void>() { public Void call() throws Exception { final String location = ResourceWatcherRequestHandler.createHandlerRequestPath(cacheKey, request); try { dispatcherLocator.locateExternal(request, location); return null; } catch (final IOException e) { final StringBuffer message = new StringBuffer("Could not check the following cacheKey: " + cacheKey); if (e instanceof SocketTimeoutException) { message .append(". The invocation of ") .append(location) .append(" timed out. Consider increasing the connectionTimeout configuration."); LOG.error(message.toString()); } else { LOG.error(message.toString(), e); } throw e; } } }); }
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest req = (HttpServletRequest) request; String fileName = req.getRequestURI().split("/")[req.getRequestURI().split("/").length - 1]; boolean bExcept = false; for (String prefix : exceptList) { if (fileName.startsWith(prefix)) { bExcept = true; break; } } if (!bExcept) { HttpSession session = ((HttpServletRequest) request).getSession(); if (!(session != null && session.getAttribute("user") != null)) { session.setAttribute("lastFileName", fileName); HttpServletResponse resp = (HttpServletResponse) response; resp.sendRedirect("login.jsp"); return; } } // String browserDet = ((HttpServletRequest) request).getHeader("User-Agent").toLowerCase(); // if (browserDet.indexOf("msie") != -1) { // PrintWriter out = response.getWriter(); // out.println("<html><head></head><body>"); // out.println("<h1>Sorry, page cannot be displayed!</h1>"); // out.println("</body></html>"); // out.flush(); // return; // } chain.doFilter(request, response); }
// 修改学院信息 private void edit(HttpServletRequest request, HttpServletResponse response) throws IOException { PrintWriter out = response.getWriter(); JsonBean j = new JsonBean(); int id = Integer.parseInt(request.getParameter("id")); int college_num = Integer.parseInt(request.getParameter("college_num")); int college_state = Integer.parseInt(request.getParameter("college_state")); String college_name = request.getParameter("college_name"); College co = new College(); co.setCollege_name(college_name); co.setCollege_num(college_num); co.setCollege_state(college_state); co.setId(id); if (service.edit(co)) { j.setSuccess(true); j.setMsg("修改[" + college_name + "]成功!"); } else { j.setMsg("修改[" + college_name + "]失败!"); } JSONArray jsonArray = new JSONArray().fromObject(j); String jsonS = jsonArray.toString(); String json = jsonS.substring(1, jsonS.lastIndexOf("]")); out.write(json); }
/** @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); String first_name = request.getParameter("firstName"); String last_name = request.getParameter("lastName"); String email = request.getParameter("email"); String addrid = request.getParameter("addr"); SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String date = df.format(new Date()); String sql = "INSERT INTO customer(first_name,last_name,email,address_id,store_id,create_date) VALUES('" + first_name + "','" + last_name + "','" + email + "'," + addrid + ",1,'" + date + "')"; // 日期自动添加 // TODO Auto-generated method stub int i = DbOperater.DML(sql); response.getWriter().print("<script>alert('success')</script>"); response.sendRedirect("index.jsp"); }
// 编辑器上传图片 @RequestMapping("/upload") @ResponseBody public JSONObject upload( @RequestParam("imgFile") MultipartFile file, HttpServletRequest request, ModelMap m) throws IOException { // String filetype = // StringUtils.substringAfterLast(file.getOriginalFilename(), "."); SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd"); String ymd = sdf.format(new Date()); String realRootPath = getServletContext().getResource("/").toString() + "upload/choicenesscontent/" + ymd + "/"; YztUtil.writeFile(file.getInputStream(), realRootPath, file.getOriginalFilename()); /**/ String path = request.getContextPath(); String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/"; // System.out.println("getContextPath==="+ // basePath+"upload/user/headimg/"+user.getId()+"."+filetype); String picurl = basePath + "upload/choicenesscontent/" + ymd + "/" + file.getOriginalFilename(); // user.setPicurl(picurl); JSONObject json = new JSONObject(); json.put("error", 0); json.put("url", picurl); return json; }
@GET @Path("/") @Produces("application/json") public List<Visitor> getVisitors() { visitorService.addVisitor(request.getRemoteAddr(), request.getHeader("User-Agent")); return visitorService.getVisitors(); }
public static String getCatalogTopCategory(ServletRequest request, String defaultTopCategory) { HttpServletRequest httpRequest = (HttpServletRequest) request; Map<String, Object> requestParameters = UtilHttp.getParameterMap(httpRequest); String topCatName = null; boolean fromSession = false; // first see if a new category was specified as a parameter topCatName = (String) requestParameters.get("CATALOG_TOP_CATEGORY"); // if no parameter, try from session if (topCatName == null) { topCatName = (String) httpRequest.getSession().getAttribute("CATALOG_TOP_CATEGORY"); if (topCatName != null) fromSession = true; } // if nothing else, just use a default top category name if (topCatName == null) topCatName = defaultTopCategory; if (topCatName == null) topCatName = "CATALOG1"; if (!fromSession) { if (Debug.infoOn()) Debug.logInfo( "[CategoryWorker.getCatalogTopCategory] Setting new top category: " + topCatName, module); httpRequest.getSession().setAttribute("CATALOG_TOP_CATEGORY", topCatName); } return topCatName; }
private void prepareEnterAuthenticateOneTimeUser(boolean authenticated) throws Exception { when(mockHttpServletRequest.getParameter(ServletUtil.VERSION)).thenReturn(versionString); when(mockHttpServletRequest.getParameter(ServletUtil.LOGIN)).thenReturn(loginString); when(mockHttpServletRequest.getParameter(ServletUtil.PASSWD)).thenReturn(passwdString); spy(ConnectionUtil.class); doNothing().when(ConnectionUtil.class); ConnectionUtil.checkParameter(versionString); doNothing().when(ConnectionUtil.class); ConnectionUtil.checkVersion(versionString); prepareForOtpManagerHelper(); when(otpManagerHelper.authenticateOneTimeUser(anyString(), (byte[]) any())) .thenReturn(authenticated); mockUserHelper = mock(UserHelper.class); whenNew(UserHelper.class).withNoArguments().thenReturn(mockUserHelper); User user = AdminFactory.eINSTANCE.createUser(); user.setLogin("*****@*****.**"); when(mockUserHelper.findByLogin(anyString())).thenReturn(user); }
@Test public void testCloseSessionByNormalUser() throws Exception { String sessionIdString = "555"; String actionString = Action.CloseSession.toString(); long sessionIdLong = Long.parseLong(sessionIdString); when(mockHttpServletRequest.getParameter(ServletUtil.ACTION)).thenReturn(actionString); when(mockHttpServletRequest.getParameter(ServletUtil.SESSION_ID)).thenReturn(sessionIdString); // set AuthenticateOneTimeUser false prepareEnterAuthenticateOneTimeUser(false); User user = stubbingCheckUser(); UsersCache userCacheHelper = mock(UsersCache.class); mockStatic(UsersCacheFactory.class); when(UsersCacheFactory.getInstance()).thenReturn(userCacheHelper); doNothing().when(userCacheHelper); userCacheHelper.remove(sessionIdLong); // RUN... defaultConnectionStrategy.execute(mockHttpServletRequest, mockHttpServletResponse); verifyNecessaryChecks(actionString); verifyStatic(org.mockito.Mockito.times(1)); ConnectionUtil.checkUser(loginString, password, false); PrintWriter writer = mockHttpServletResponse.getWriter(); writer.flush(); System.out.println(outStringWriter.toString()); // ASSERT... assertThat(outStringWriter.toString(), is("RESPONSE:" + String.valueOf(sessionIdLong))); }
@Test public void testOpenSessionByNormalUser() throws Exception { long sessionLong = 555; String actionString = Action.OpenSession.toString(); when(mockHttpServletRequest.getParameter(ServletUtil.ACTION)).thenReturn(actionString); when(mockHttpServletRequest.getParameter(ServletUtil.PROJECT)).thenReturn(projectString); // set AuthenticateOneTimeUser false prepareEnterAuthenticateOneTimeUser(false); User user = stubbingCheckUser(); UsersCache userCacheHelper = mock(UsersCache.class); mockStatic(UsersCacheFactory.class); when(UsersCacheFactory.getInstance()).thenReturn(userCacheHelper); when(userCacheHelper.logWithProjectLabel(loginString, CLIENT_TYPE, projectString)) .thenReturn(sessionLong); // RUN... defaultConnectionStrategy.execute(mockHttpServletRequest, mockHttpServletResponse); verifyNecessaryChecks(actionString); verifyStatic(org.mockito.Mockito.times(1)); ConnectionUtil.checkUser(loginString, password, false); PrintWriter writer = mockHttpServletResponse.getWriter(); writer.flush(); System.out.println(outStringWriter.toString()); // ASSERT... assertThat(outStringWriter.toString(), is("RESPONSE:" + String.valueOf(sessionLong))); }
@Test public void testLoginActionByAuthenticateOneTimeUser() throws Exception { String actionString = Action.Login.toString(); when(mockHttpServletRequest.getParameter(ServletUtil.ACTION)).thenReturn(actionString); when(mockHttpServletRequest.getParameter(ServletUtil.PROJECT)).thenReturn(projectString); // set AuthenticateOneTimeUser true prepareEnterAuthenticateOneTimeUser(true); String xmi = constructProjectsObjectsXmi(); doThrow( new org.talend.gwtadministrator.server.remoteconnection.ConnectionUtil .ResponseException(xmi)) .when(ConnectionUtil.class); ConnectionUtil.returnProjectAndUsers(anyString(), (User) any(), anyBoolean()); // RUN... defaultConnectionStrategy.execute(mockHttpServletRequest, mockHttpServletResponse); verifyNecessaryChecks(actionString); // verify called listAllProjects once verifyStatic(org.mockito.Mockito.times(1)); ConnectionUtil.returnProjectAndUsers(anyString(), (User) any(), anyBoolean()); PrintWriter writer = mockHttpServletResponse.getWriter(); writer.flush(); System.out.println(outStringWriter.toString()); // ASSERT... assertThat(outStringWriter.toString(), is("RESPONSE:" + xmi)); }
// 负责菜单的加载 @RequestMapping(value = "/menus") public String getMenus(HttpServletRequest request, HttpServletResponse response, Model model) { // 从session中获取所有的角色信息 AdminUserDTO userDTO = (AdminUserDTO) request.getSession().getAttribute(ADMIN_USER_SESSION); Map<String, MenuManagerDTO> menusMap = userDTO.getMenuList(); if (menusMap != null) { List<MenuManagerDTO> menus = null; String godPhone = request.getSession().getServletContext().getInitParameter("godPhone"); if (userDTO.getPhone() != null && userDTO.getPhone().equals(godPhone)) { menus = menuManagerService.getNavMenu(); // 获取所有的菜单组或者页面菜单, } else { menus = new ArrayList<MenuManagerDTO>(); menus.addAll(menusMap.values()); } // 根据ID排序 Collections.sort( menus, new Comparator<MenuManagerDTO>() { @Override public int compare(MenuManagerDTO menu1, MenuManagerDTO menu2) { return menu1.getMenuId() - menu2.getMenuId(); } }); model.addAttribute("pageMenus", menus); } return "admin/menu"; }
// 更改密码 // 登陆后跳转的页面 @RequestMapping(value = "/updatePsw") public String updatePsw(HttpServletRequest request, HttpServletResponse response, Model model) { AdminUserDTO loginUser = (AdminUserDTO) request.getSession().getAttribute(ADMIN_USER_SESSION); String oldPsw = request.getParameter("oldPsw"); String newPsw = request.getParameter("newPsw"); JsonDTO json = new JsonDTO(); if (oldPsw != null && newPsw != null && oldPsw.length() <= 50 && newPsw.length() <= 50) { AdminUser adminUser = new AdminUser(); adminUser.setAdminUserId(loginUser.getAdminUserId()); adminUser.setPassword(PasswordUtil.MD5(oldPsw)); loginUser = adminUserService.getUserByParam(adminUser); if (loginUser != null) { // 验证成功,修改密码 adminUser.setPassword(PasswordUtil.MD5(newPsw)); try { adminUserService.updateUserAndRole(adminUser, null); json.setStatus(1).setMessage("密码更新成功!"); } catch (Exception e) { e.printStackTrace(); json.setStatus(0).setMessage("密码更新失败!:" + e.getMessage()); } model.addAttribute("json", JSONUtil.object2json(json)); return JSON; } } json.setStatus(0).setMessage("密码错误!"); model.addAttribute("json", JSONUtil.object2json(json)); return "json"; }
public ActionForward updateAppointmentReason( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { HashMap<String, Object> hashMap = new HashMap<String, Object>(); OscarAppointmentDao appointmentDao = (OscarAppointmentDao) SpringUtils.getBean("oscarAppointmentDao"); Appointment appointment = appointmentDao.find(Integer.parseInt(request.getParameter("appointmentNo"))); if (appointment != null) { appointment.setReason(request.getParameter("reason")); appointmentDao.merge(appointment); hashMap.put("success", true); hashMap.put("appointmentNo", appointment.getId()); } JsonConfig config = new JsonConfig(); config.registerJsonBeanProcessor(java.sql.Date.class, new JsDateJsonBeanProcessor()); JSONObject json = JSONObject.fromObject(hashMap, config); response.getOutputStream().write(json.toString().getBytes()); return null; }
/** * Query the relevant overlap region and additional information according to user's uploaded * spans. * * @throws InterruptedException e */ public void runSpanOverlapQuery() throws InterruptedException { // Use spanConstraintMap to check whether the spanUpload is duplicated, the map is saved in // the session @SuppressWarnings("unchecked") Map<SpanUploadConstraint, String> spanConstraintMap = (HashMap<SpanUploadConstraint, String>) request.getSession().getAttribute("spanConstraintMap"); if (spanConstraintMap == null) { spanConstraintMap = new HashMap<SpanUploadConstraint, String>(); } SpanUploadConstraint c = new SpanUploadConstraint(); c.setFtKeys(ftKeys); c.setSubKeys(subKeys); c.setSpanList(spanList); c.setSpanOrgName(orgName); if (spanConstraintMap.size() == 0) { spanConstraintMap.put(c, spanUUIDString); } else { if (spanConstraintMap.containsKey(c)) { spanUUIDString = spanConstraintMap.get(c); request.setAttribute("spanUUIDString", spanUUIDString); } else { spanConstraintMap.put(c, spanUUIDString); } } request.getSession().setAttribute("spanConstraintMap", spanConstraintMap); request.setAttribute("spanQueryTotalCount", spanList.size()); (new Thread(this)).start(); }
private String getSAMLVersion(HttpServletRequest request) { String samlResponse = request.getParameter(GeneralConstants.SAML_RESPONSE_KEY); String version; try { Document samlDocument = toSAMLResponseDocument(samlResponse, "POST".equalsIgnoreCase(request.getMethod())); Element element = samlDocument.getDocumentElement(); // let's try SAML 2.0 Version attribute first version = element.getAttribute("Version"); if (isNullOrEmpty(version)) { // fallback to SAML 1.1 Minor and Major attributes String minorVersion = element.getAttribute("MinorVersion"); String majorVersion = element.getAttribute("MajorVersion"); version = minorVersion + "." + majorVersion; } } catch (Exception e) { throw new RuntimeException("Could not extract version from SAML Response.", e); } return version; }
@Override protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/xml"); response.setCharacterEncoding("UTF-8"); System.out.println("*** Data tags"); String sid = (String) request.getParameter("sid"); if (sid == null) throw new IOException("Invalid session"); String firstLetter = (String) request.getParameter("firstLetter"); // Headers required by Internet Explorer response.setHeader("Pragma", "public"); response.setHeader("Cache-Control", "must-revalidate, post-check=0,pre-check=0"); response.setHeader("Expires", "0"); PrintWriter writer = response.getWriter(); writer.write("<list>"); for (int i = 0; i < 1000; i++) { writer.print("<tag>"); writer.print("<index>" + i + "</index>"); if (firstLetter != null) { writer.print("<word>" + firstLetter.charAt(0) + "tag" + i + "</word>"); writer.print("<count>" + i + "</count>"); } else { writer.print("<word>tag" + i + "</word>"); writer.print("<count></count>"); } writer.print("</tag>"); } writer.write("</list>"); }
/* * This controller method is for demonstration purposes only. It contains a call to * catalogService.findActiveProductsByCategory, which may return a large list. A * more performant solution would be to utilize data paging techniques. */ protected boolean addProductsToModel( HttpServletRequest request, ModelMap model, CatalogSort catalogSort) { boolean productFound = false; String productId = request.getParameter("productId"); Product product = null; try { product = catalogService.findProductById(new Long(productId)); } catch (Exception e) { // If product is not found, return all values in category } if (product != null && product.isActive()) { productFound = validateProductAndAddToModel(product, model); addRatingSummaryToModel(productId, model); } else { Category currentCategory = (Category) model.get("currentCategory"); List<Product> productList = catalogService.findActiveProductsByCategory(currentCategory, SystemTime.asDate()); SearchFilterUtil.filterProducts( productList, request.getParameterMap(), new String[] {"manufacturer", "sku.salePrice"}); if ((catalogSort != null) && (catalogSort.getSort() != null)) { populateProducts(productList, currentCategory); model.addAttribute("displayProducts", sortProducts(catalogSort, productList)); } else { catalogSort = new CatalogSort(); catalogSort.setSort("featured"); populateProducts(productList, currentCategory); model.addAttribute("displayProducts", sortProducts(catalogSort, productList)); } } return productFound; }
/** * 将用户提交的简介写入html文件中, 并将文件的url设置进的htmlurl属性中 * * @param request * @param choicenesscontent * @throws IOException */ private void saveHtmlUrl(HttpServletRequest request, YztChoicenesscontent choicenesscontent) throws IOException { // 保存简介的html String introduction = choicenesscontent.getIntroduction(); String htmlStr = "<!DOCTYPE html><head><meta charset=\"UTF-8\"><title>内容简介</title></head><body>" + introduction + "</body></html>"; /* String htmlStr = choicenesscontent.getIntroduction(); */ // 返回简介html 要存在服务器上的绝对路径 String path = "upload/choicenesscontent/" + choicenesscontent.getId() + ".html"; String realRootPath = request.getServletContext().getRealPath("/") + path; File file = new File(realRootPath); BufferedWriter bw = new BufferedWriter(new FileWriter(file)); bw.write(htmlStr); // 拼成一个url路径 String htmlurl = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() + "/" + path; choicenesscontent.setIntroductionHtmlUrl(htmlurl); bw.close(); }
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { // 登录界面login.jsp进入前判断是否已经登陆,是则直接跳转 HttpServletRequest req = (HttpServletRequest) request; HttpServletResponse res = (HttpServletResponse) response; Cookie cookies[] = req.getCookies(); Cookie login = null; Cookie user = null; Cookie admin = null; // 1)判断cookie为空。2)cookie存在,但没有"loginName"。 // 3)cookie存在,但有"loginName",但loginName为null或0。 if (cookies != null) { for (int i = 0; i < cookies.length; i++) { if (cookies[i].getName().equals("LoginName")) { login = cookies[i]; } else if (cookies[i].getName().equals("superUser")) { user = cookies[i]; } else if (cookies[i].getName().equals("adminRight")) { admin = cookies[i]; } } } if (login != null && !login.getValue().equals("")) { if (admin != null && !admin.getValue().equals("")) { res.sendRedirect("/Login_Servlet/administrator/login/success.jsp"); } else if (user != null && !user.getValue().equals("")) { res.sendRedirect("/Login_Servlet/user/login/success.jsp"); } } else { chain.doFilter(request, response); } }
/** Get Cancer Study ID in a backward compatible fashion. */ public static String getCancerStudyId(HttpServletRequest request) { String cancerStudyId = request.getParameter(WebService.CANCER_STUDY_ID); if (cancerStudyId == null || cancerStudyId.length() == 0) { cancerStudyId = request.getParameter(WebService.CANCER_TYPE_ID); } return cancerStudyId; }
/** * Grabs the appropriate stuff from a request and returns a list of case_ids * * @param request * @return * @throws ProtocolException * @throws DaoException */ public static ArrayList<String> getSampleIds(HttpServletRequest request) throws ProtocolException, DaoException { String samples = request.getParameter(WebService.CASE_LIST); String sampleSetId = request.getParameter(WebService.CASE_SET_ID); String sampleIdsKey = request.getParameter(WebService.CASE_IDS_KEY); if (sampleIdsKey != null) { samples = SampleSetUtil.getSampleIds(sampleIdsKey); } ArrayList<String> sampleList = new ArrayList<String>(); if (sampleSetId != null && !(sampleSetId.equals("-1"))) { DaoSampleList dao = new DaoSampleList(); SampleList selectedSampleList = dao.getSampleListByStableId(sampleSetId); if (selectedSampleList == null) { throw new ProtocolException( "Invalid " + WebService.CASE_SET_ID + ": " + sampleSetId + "."); } sampleList = selectedSampleList.getSampleList(); } else if (samples != null) { for (String _sample : samples.split("[\\s,]+")) { _sample = _sample.trim(); if (_sample.length() == 0) continue; sampleList.add(_sample); } } else if (samples != null) { // todo: this is a hack, samples is just another word for patients return new ArrayList(Arrays.asList(samples.split(" "))); } else { throw new ProtocolException( WebService.CASE_SET_ID + " or " + WebService.CASE_LIST + " must be specified."); } return sampleList; }
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String strOp1 = request.getParameter("op1"); String strOp2 = request.getParameter("op2"); int sum = 0; int op1 = 0; int op2 = 0; if (strOp1 != null && strOp2 != null) { try { op1 = Integer.parseInt(strOp1); op2 = Integer.parseInt(strOp2); sum = op1 + op2; } catch (Exception e) { request.setAttribute("hasError", true); } } request.setAttribute("op1", op1); request.setAttribute("op2", op2); request.setAttribute("sum", sum); request.setAttribute("formSubmitted", true); doGet(request, response); }
private ExtendedMap parseSimpleRequest(HttpServletRequest request, boolean keepEmpty) { ExtendedMap formItems = new ExtendedMap(keepEmpty); Enumeration paramNames = request.getParameterNames(); while (paramNames.hasMoreElements()) { String key = paramNames.nextElement().toString(); String[] paramValues = request.getParameterValues(key); if (paramValues != null) { if (paramValues.length == 1 && paramValues[0] != null) { String value = paramValues[0]; if (value.length() > 0) { if ("true".equals(value)) { formItems.putBoolean(key, true); } else if ("false".equals(value)) { formItems.putBoolean(key, false); } else { formItems.putString(key, value); } } else if (keepEmpty) { formItems.putString(key, value); } } else if (paramValues.length > 1) { formItems.put(key, paramValues); } } } return formItems; }
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 接收时设置的编码 request.setCharacterEncoding("utf-8"); // 转发时设置的编码 response.setCharacterEncoding("utf-8"); // 以 超文本格式 方式转发 response.setContentType("text/html"); // 获取了一个输出流 PrintWriter out = response.getWriter(); // 修改库存数量Ajax String id = request.getParameter("id"); String number = request.getParameter("number"); NeProductsDao neProductsDao = new NeProductsDaoImpl(); int count = neProductsDao.updateNumber(Integer.parseInt(id), Integer.parseInt(number)); if (count > 0) { out.println("商品" + id + "库存数量修改成功"); } else { out.println("商品" + id + "库存数量修改失败"); } out.flush(); out.close(); }
private String getFromRequest(String parameter, HttpServletRequest request) { String parameterString = request.getParameter(parameter); if (parameterString == null) { parameterString = (String) request.getAttribute(parameter); } return parameterString; }
@RequestMapping("/dumpThead") @ResponseBody public void doDumpThread(HttpServletRequest request, HttpServletResponse response) { try { String app = request.getParameter("app"); String threadId = request.getParameter("threadId"); ThreadMXBean tBean = JMConnManager.getThreadMBean(app); JSONObject data = new JSONObject(); if (threadId != null) { Long id = Long.valueOf(threadId); ThreadInfo threadInfo = tBean.getThreadInfo(id, Integer.MAX_VALUE); data.put("info", threadInfo.toString()); } else { ThreadInfo[] dumpAllThreads = tBean.dumpAllThreads(false, false); StringBuffer info = new StringBuffer(); for (ThreadInfo threadInfo : dumpAllThreads) { info.append("\n").append(threadInfo); } data.put("info", info); } writeFile(request, response, data); } catch (IOException e) { throw new RuntimeException(e); } }
/** * 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 { response.setContentType("text/html;charset=UTF-8"); RequestDispatcher rd; // HttpSession HttpSession session; session = request.getSession(false); String dni; String password; if (session == null) { rd = this.getServletContext().getRequestDispatcher("/error.jsp"); rd.forward(request, response); } else { Administrador a = (Administrador) session.getAttribute("entidad"); Integer idRol = (Integer) session.getAttribute("id"); session.setAttribute("entidad", a); session.setAttribute("id", idRol); } List<Especialidad> especialidad; // List <Roles> rol; especialidad = (List<Especialidad>) facadeEspecialidad.findAll(); // rol = (List <Roles>) facadeRoles.findAll(); request.setAttribute("lista_especialidad", especialidad); // request.setAttribute("lista_rol", rol); rd = this.getServletContext().getRequestDispatcher("/inma/NuevoMedico.jsp"); rd.forward(request, response); }