This perplexes me. In the following code not even "1" is being printed out in the console. If i place a breakpoint (using eclipse) in the first system.out line, the debugger never exits it. No exceptions thrown. I also tried passing a null argument to SFU's constructor to force it to throw an exception, but nothing happened.
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("1");
try {
ServletFileUpload upload = new ServletFileUpload();
} catch (Throwable e) {
throw new ServletException(e);
}
System.out.println("2");
}
And the html
<!DOCTYPE html>
<html lang="en">
<head>
<title>File Upload</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<form method="POST" action="loadFile" enctype="multipart/form-data" >
<input type="file" name="myFile" id="myFile" /> <br/>
<input type="submit" value="Upload" name="upload" id="upload" />
</form>
</body>
</html>
try remove "throws ServletException, IOException" from
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
and change
try {
ServletFileUpload upload = new ServletFileUpload();
} catch (Throwable e) {
throw new ServletException(e);
}
to:
try {
ServletFileUpload upload = new ServletFileUpload();
//... rest of code
} catch (FileUploadException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
Add any other exceptions to the catch clause, don't throw them. That's why you don't see what the error is about
Also noticed that the name of your form action is loadFile
does this correspond to your Servlet name? Servlets usually have a capitalized first letter ! My suspicion is that this is the real problem, you're sending a post request to a servlet the server can't find.
Related
I would like to be able to control whether or not a form retains it's values when the user navigates back to it. Take the following example.
User successfully submits form on page /transfertaxes/create
User is navigated to /transfertaxes/index
User uses browser back button to navigate back to /transfertaxes/create
The behavior I am currently observing is the form values are retained. I have tried disabling caching in several ways, none of which have worked. How can this be accomplished?
Chrome
Startup.cs
namespace LoanCalculator
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddRazorPages();
services.AddDbContext<LoanCalculatorContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("LoanCalculatorContext")));
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
//ADDED THIS
app.UseStaticFiles(new StaticFileOptions()
{
OnPrepareResponse = context =>
{
context.Context.Response.Headers.Add("Cache-Control", "no-cache, no-store");
context.Context.Response.Headers.Add("Expires", "-1");
}
});
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
});
}
}
}
Create.cshtml.cs
namespace LoanCalculator.Pages.TransferTaxes
{
public class CreateModel : PageModel
{
private readonly LoanCalculator.Data.LoanCalculatorContext _context;
public CreateModel(LoanCalculator.Data.LoanCalculatorContext context)
{
_context = context;
}
public IActionResult OnGet()
{
return Page();
}
[BindProperty]
public TransferTax TransferTax { get; set; }
// To protect from overposting attacks, see https://aka.ms/RazorPagesCRUD
public async Task<IActionResult> OnPostAsync()
{
if (!ModelState.IsValid)
{
return Page();
}
_context.TransferTax.Add(TransferTax);
await _context.SaveChangesAsync();
return RedirectToPage("./Index");
}
}
}
_Layout.cshtml
...
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate">
<meta http-equiv="Pragma" content="no-cache">
<meta http-equiv="Expires" content="0">
<title>#ViewData["Title"] - LoanCalculator</title>
<link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css" />
<link rel="stylesheet" href="~/css/site.css?v0000000002" />
</head>
...
Browsers implement back-forward cache (BFCache). When you hit back button the actual page is not reloaded and scripts doesn't rerun.
If you have to clear your form in case user hit back button, you can listen to "pageshow" event do something like the following:
window.addEventListener("pageshow", () => {
// update hidden input field
});
Note that reset() does not work for hidden input fields.
See this
You can bind to window.onbeforeunload to prevent the browser from fully caching the page.Add the following code to your _Layout.cshtml:
<script>
window.onbeforeunload = function () {
$('form')[0].reset();
};
</script>
Result:
Reference:
https://stackoverflow.com/a/14548415/11398810
I have a RestEasy based service in which I am doing some cleanup work in a ContainerResponseFilter. The problem is that if an unknown runtime exception (i.e. an exception for which I do not have a mapper) is thrown by a resource, the ContainerResponseFilter is never executed.
Is this the expected behavior? Is there a workaround to this? I was looking at the following question (answer by Jonas):
How should I log uncaught exceptions in my RESTful JAX-RS web service?
and that made it seem like the ContainerResponseFilter is executed even when an exception is thrown in the controller?
Am I missing something?
Didn't work for me either. This claims it should work: https://github.com/Graylog2/graylog2-server/issues/1826
I didn't want to investigate further, and simply use a plain old javax.servlet.Filter, but of course there it's hard to set the reponses-headers (after chain.doFilter(), ... grr..
So used a Spring solution:
public static class MyFilter extends OncePerRequestFilter {
#Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
response.setHeader("MyHeader", "MyValue");
filterChain.doFilter(request, response);
}
}
Base on the source code of SynchronousDispatcher in RestEasy.
protected void writeResponse(HttpRequest request, HttpResponse response, Response jaxrsResponse) {
try {
ServerResponseWriter.writeNomapResponse((BuiltResponse)jaxrsResponse, request, response, this.providerFactory);
} catch (Exception var5) {
this.writeException(request, response, var5);
}
}
public void writeException(HttpRequest request, HttpResponse response, Throwable e) {
if (response.isCommitted()) {
throw new UnhandledException("Response is committed, can't handle exception", e);
} else {
Response handledResponse = (new ExceptionHandler(this.providerFactory, this.unwrappedExceptions)).handleException(request, e);
if (handledResponse == null) {
throw new UnhandledException(e);
} else {
try {
ServerResponseWriter.writeNomapResponse((BuiltResponse)handledResponse, request, response, this.providerFactory);
} catch (Exception var6) {
throw new UnhandledException(var6);
}
}
}
}
ContainerResponseFilter will not execute.
If you want to set headers when exceptions happen, you need an exception handler to deal with it.
I use the :contains() method but I get the error below:
Test Name: TheMahler3Test
Test FullName: TestingCssSelector.Mahler3.TheMahler3Test
Test Source: c:\Users\amahallati\Desktop\TestContainsSelector\TestingCssSelector\Mahler3.cs : line 50
Test Outcome: Failed
Test Duration: 0:00:05.135
Result Message: System.InvalidOperationException : An invalid or illegal string was specified
Result StackTrace:
at OpenQA.Selenium.Support.UI.DefaultWait1.PropagateExceptionIfNotIgnored(Exception e)
at OpenQA.Selenium.Support.UI.DefaultWait1.Until[TResult](Func`2 condition)
at TestingCssSelector.Mahler3.TheMahler3Test() in c:\Users\amahallati\Desktop\TestContainsSelector\TestingCssSelector\Mahler3.cs:line 59
This is the page's source code:
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<div>
<div id="myDiv">
<select name="mySelectInput">
<option value="">Select one...</option>
<option value="1">AT&T</option>
<option value="2">TMobile</option>
</select>
</div>
</div>
</body>
</html>
And this is the WebDriver C# code:
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using NUnit.Framework;
using OpenQA.Selenium;
using OpenQA.Selenium.IE;
using OpenQA.Selenium.Support.UI;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium.Interactions;
namespace TestingCssSelector
{
[TestFixture]
public class Mahler3
{
private IWebDriver driver;
private StringBuilder verificationErrors;
private string baseURL;
private bool acceptNextAlert = true;
[SetUp]
public void SetupTest()
{
driver = new FirefoxDriver();
baseURL = "http://localhost:49638/";
verificationErrors = new StringBuilder();
}
[TearDown]
public void TeardownTest()
{
try
{
driver.Quit();
}
catch (Exception)
{
// Ignore errors if unable to close the browser
}
Assert.AreEqual("", verificationErrors.ToString());
}
[Test]
public void TheMahler3Test()
{
driver.Navigate().GoToUrl(baseURL + "/");
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(40));
wait.Until(d =>
{
return driver.FindElement(By.XPath("/html/body/div/div/select"));
});
driver.FindElement(By.XPath("/html/body/div/div/select")).Click();
wait.Until(d =>
{
return driver.FindElement(By.CssSelector("option:contains('AT&T')"));
});
driver.FindElement(By.CssSelector("option:contains('AT&T')")).Click();
// ERROR: Caught exception [ReferenceError: selectLocator is not defined]
}
private bool IsElementPresent(By by)
{
try
{
driver.FindElement(by);
return true;
}
catch (NoSuchElementException)
{
return false;
}
}
private bool IsAlertPresent()
{
try
{
driver.SwitchTo().Alert();
return true;
}
catch (NoAlertPresentException)
{
return false;
}
}
private string CloseAlertAndGetItsText()
{
try
{
IAlert alert = driver.SwitchTo().Alert();
string alertText = alert.Text;
if (acceptNextAlert)
{
alert.Accept();
}
else
{
alert.Dismiss();
}
return alertText;
}
finally
{
acceptNextAlert = true;
}
}
}
}
contains is not part of the CSS selector specification and is therefore not going to work.
The contains selector we all know and love comes from Sizzle, the CSS-selector engine behind jQuery. Unless you wish to physically load Sizzle or jQuery into your page, then you are not going to be able to use your current solution.
The only real way of doing text-based searching is using XPath, or find a list of elements (using anyway you like) and filtering them within code.
For your basic page, it's easy enough to simply select it by ID, so simply:
Select select = new Select(driver.FindElement(By.Id("mySelectInput")));
You would then select it by using:
select.SelectByVisibleText("AT&T");
I have a servlet which is supposed to process uploaded file. Apache common file upload library is used for that.
The problem is that file comes corrupted. Looks like symbols "~" are replaced on "?" in the file.
Here my html form is:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title></title>
</head>
<body>
<FORM action="http://localhost:8081/wihome-connector-bpm/bpmFileUpload"
enctype="multipart/form-data"
method="post">
What files are you sending?
<INPUT type="file" name="uploadedFiles"><BR>
<INPUT type="submit" value="Send">
<INPUT type="reset">
</FORM>
</body>
</html>
And that is the servlet:
public class FileUploadServlet extends HttpServlet {
private static final Log LOG = LogFactory.getLog(FileUploadServlet.class);
/**
* {#inheritDoc}
*/
#Override
protected void doPost(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException {
try {
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (isMultipart) {
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List items = upload.parseRequest(request);
Iterator iter = items.iterator();
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
if (!item.isFormField()) {
LOG.info("Uploading file: " + item.getName());
byte[] fileContents = IOUtils.toByteArray(item.getInputStream());
//...
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
I am trying to upload image
But instead I get that:
Can you please help me? What can be the problem?
Ok, there was a problem with filters. Project had a filter that currupted request before it rich servlet.
I am trying to develop a simple BigQuery App using JSP Servlets. I am following the exampla given on https://developers.google.com/bigquery/docs/authorization
In the early stages, the doGet method was not getting invoked and so I overrided the Service method. The code looks like this
public class BigQueryWebServerAuthDemo extends AbstractAuthorizationCodeServlet {
protected void service(HttpServletRequest req, HttpServletResponse resp)
throws IOException, ServletException {
System.out.println(" Start service ");
doGet(req, resp);
}
#Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException {
System.out.println(" Start doGet ");
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException {
System.out.println(" Start doPost ");
response.setContentType("text/html");
PrintWriter writer = response.getWriter();
System.out.println(" Begin loadbigquery() ");
Bigquery bigquery = CredentialUtils.loadbigquery();
System.out.println(" end loadbigquery() ");
Bigquery.Projects.List projectListRequest = bigquery.projects().list();
ProjectList projectList = projectListRequest.execute();
if (projectList.getProjects() != null) {
java.util.List<Projects> projects = projectList.getProjects();
writer.println("<h3>BigQuery project list:</h3>");
for (ProjectList.Projects project : projects) {
writer.printf("%s<br />", project.getProjectReference().getProjectId());
}
}
System.out.println(" End doPost ");
}
#Override
protected AuthorizationCodeFlow initializeFlow() throws ServletException, IOException {
System.out.println(" inside BigQueryWebServerAuthDemo --- initializeFlow() ");
return CredentialUtils.newFlow();
}
#Override
protected String getRedirectUri(HttpServletRequest request) throws ServletException, IOException {
System.out.println(" inside BigQueryWebServerAuthDemo --- getRedirectUri() ");
return CredentialUtils.getRedirectUri(request);
}
#Override
protected String getUserId(HttpServletRequest request) throws ServletException, IOException {
System.out.println(" inside BigQueryWebServerAuthDemo --- getUserId ");
return request.getParameter("userId");
}
}
I have a JSP page from where I am getting the parameter "userId". Now I get a
NoSuchMethodError on execute() method [projectListRequest.execute()] though Eclipse compiler doesnt show any error.
Below is my web.xml config info
<servlet>
<servlet-name>oauth2callback</servlet-name>
<servlet-class>main.BigQueryWebServerAuthCallBack</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>oauth2callback</servlet-name>
<url-pattern>/oauth2callback</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>ServletBigQuery</servlet-name>
<servlet-class>main.BigQueryWebServerAuthDemo</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ServletBigQuery</servlet-name>
<url-pattern>/ServletBigQuery</url-pattern>
</servlet-mapping>
I have 2 more classes CredentialUtils and BigQueryWebServerAuthCallBack as given in the tutorial mentioned above.
I am actually new to Java . I want get rid of the NoSuchMethodError error. Any help will be greatly appreciated.