Tomcat always run failure - java

I want to build a web project in Tomcat, but the code always fails to run.
I tried many hints from web,but no method succeeded.
Because I am Java beginner,I supply my IDEA setting.
public class AddServlet extends HttpServlet {
#Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String fname = request.getParameter("fname");
String priceStr = request.getParameter("price");
Integer price = Integer.parseInt(priceStr);
String fcountStr = request.getParameter("fcount");
Integer fcount = Integer.parseInt(fcountStr);
String remark = request.getParameter("remark");
System.out.println("fname = " +fname);
System.out.println("price = " +price);
System.out.println("fcount = " +fcount);
System.out.println("remark = " +remark);
}
}
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<servlet>
<servlet-name>AddServlet</servlet-name>
<servlet-class>com.atguigu.servlets.AddServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>AddServlet</servlet-name>
<url-pattern>/add</url-pattern>
</servlet-mapping>
https://imgur.com/a/DS9Z3lF

Related

context.getInitParameter("") and config.getInitParameter("") always returning null

I am a beginner in servlets and JSP and I've tried my best to get the values yet I am getting null, any help is welcomed:
This is basic code on using ServletConfig and ServletContext to get param-value from web.xml
Servlet_Ex_4.java (- servlet):
#WebServlet("/Servlet_Ex_4")
public class Servlet_Ex_4 extends HttpServlet {
ServletContext context;
ServletConfig config;
String appUser ;
String Database ;
#Override
public void init() {
ServletContext context =getServletContext();
appUser = context.getInitParameter("appUser");
ServletConfig config =getServletConfig();
Database = config.getInitParameter("Database");
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("text/html");
PrintWriter out = response.getWriter();
//get ServletContext object.
//get context parameter from ServletContext object.
out.print("<h1>Application User: " + appUser + "</h1>");
out.print("<h1>Database: " + Database + "</h1>");
out.close();
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
Web.xml
<?xml version="1.0" encoding="UTF-8"?>
<element>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID" version="4.0">
<display-name>Servlet_Exercise_4</display-name>
<servlet>
<servlet-name>Servlet_4</servlet-name>
<servlet-class>Servlet_Ex_4</servlet-class>
<context-param>
<param-name>Database</param-name>
<param-value>Oracle</param-value>
</context-param>
</servlet>
<context-param>
<param-name>appUser</param-name>
<param-value>jai</param-value>
</context-param>
<servlet-mapping>
<servlet-name>Servlet_4</servlet-name>
<url-pattern>/Servlet_Ex_4</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.jsp</welcome-file>
<welcome-file>default.htm</welcome-file>
</welcome-file-list>
</web-app>
</element>
tag <element> must be removed from web.xml because it not part of XML definition in this case
<context-param> must not be used inside the <servlet>, it must be replaced by <init-param> to access parameters from ServletConfig object. This is the reason why the OP is getting null value.
<context-param> will work for parameter "appUser", it can be accessed using ServletContext object.
And mixing annotations with XML for same type of configurations can result in undesirable effects. So, #WebServlet should be removed from the source code as majority of configuration is done using XML.
So final web.xml should like below (with #WebServlet annotation removed from the Servlet_Ex_4 class)
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
id="WebApp_ID" version="4.0">
<display-name>ServletParams</display-name>
<servlet>
<servlet-name>Servlet_4</servlet-name>
<servlet-class>Servlet_Ex_4</servlet-class>
<init-param>
<param-name>Database</param-name>
<param-value>Oracle</param-value>
</init-param>
</servlet>
<context-param>
<param-name>appUser</param-name>
<param-value>jai</param-value>
</context-param>
<servlet-mapping>
<servlet-name>Servlet_4</servlet-name>
<url-pattern>/Servlet_Ex_4</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
</web-app>

Google app engine No handlers matched this URL

i am going to call firebase Http request from a cron job i setup on google app engine.the cron job is deployed successfully but it did not trigger the firebase url as i think i am missing some setting in the web.xml file or in other files.
In the log viewer i see this type of info "No handlers matched this URL"
Any one have any idea.Any would be appreciated.
Following is my cron.xml setting
<?xml version="1.0" encoding="UTF-8"?>
<cronentries>
<cron>
<url>/cron</url>
<target>beta</target>
<description>Keymitt cron job</description>
<schedule>every 1 minutes</schedule>
</cron>
</cronentries>
this is my web.xml setting
<?xml version="1.0" encoding="utf-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1">
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>HelloAppEngine</servlet-name>
<servlet-class>com.company.HelloAppEngine</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloAppEngine</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>KeymittCron</servlet-name>
<servlet-class>com.company.KeymittCron</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>KeymittCron</servlet-name>
<url-pattern>/cron</url-pattern>
</servlet-mapping>
</web-app>
and this is my associated WebServlet
#WebServlet(name = "KeymittCron",value = "/cron")
public class KeymittCron extends HttpServlet {
private static final Logger _logger = Logger.getLogger(KeymittCron.class.getName());
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// super.doGet(req, resp);
URL url=new URL("httplink");
HttpURLConnection connection= (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setDoOutput(true);
connection.setDoInput(true);
connection.connect();
int requestCode=connection.getResponseCode();
if(requestCode==200){
_logger.info("firebase link triggered successfully");
_logger.info("Executed cron job");
}
else{
_logger.info("Error while triggering firebase link");
}
connection.disconnect();
resp.setStatus(200);
resp.getWriter().println("Done");
}
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//
doGet(req,resp);
}
}
And this is my Logger info
My answer here may be relevant - Google Cloud App Engine cron job - not calling the service
Basically, you may need this in your appengine-web.xml:
<service>beta</service>
The <target> you specify in your cron.xml must match the <service> you define in your appengine-web.xml

Sending file upload size exceed error to client in java

Basically I have a type="file" which sends an image to server, In server I need to check that the image size is not higher than 1MB if it's send an error to client about the image size so the client could pop an error to user.
Here is my servlet script:
#MultipartConfig(
maxFileSize=1024*1024 // 1Mb max
)
public class ProPicUploader extends HttpServlet {
private static final long serialVersionUID = 1L;
public void init() throws ServletException
{
System.out.println("Initiate method is called in " + this.getClass().getName());
}
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
try{
MultipartRequest multipartRequest = new MultipartRequest(request, "D:\\");
} catch(IOException e){
out.print("Image size is bigger than 1MB");
System.out.println(e.getMessage());
}
out.print("Successfully Uploaded");
}
public void destroy(){
System.out.println("Destory method is called in: " + this.getClass().getName());
}
}
client-side script:
if(formdata){
$.ajax({
url: '../propicuploader',
type: 'POST',
data: formdata,
processData: false,
contentType: false,
success: function(data){
alert(data);
if(data == "0x00000035"){
$("#NotPictureerror_spn").text("File size is too big, Please select a file upto 2MB");
}
}
error: function(data){
alert(data);
}
});
}
and my web.xml script:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>Duck</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>ProPicUploader</servlet-name>
<servlet-class>/ProPicUploader</servlet-class>
</servlet>
</web-app>
So far it does if the Image size is lower than 1MB it says Successfully Uploaded but if the image size is higher than 1MB it pop nothing although I have inputed to send an error saying out.print("Image size is bigger than 1MB") but my client never gets to receive that.
I really appreciate if somebody tell me what am i doing wrong:)
Remove this part
#MultipartConfig(
maxFileSize=1024*1024 // 1Mb max
)
and retry.
By default MultipartRequest is limiting the upload size to 1 Megabyte

How do I add a servlet to spring framework java web application?

I thought this would be pretty straightforward, but apparently I'm missing something, and I can't seem to figure out what it is.
I'm trying to add a servlet to an existing web application written using java and spring. Here's what I did:
I added the following to web.xml:
<servlet>
<servlet-name>SettingServlet</servlet-name>
<display-name>SettingServlet</display-name>
<description>Provides a rest endpoint for getting and setting settings.</description>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/SettingServlet-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>SettingServlet</servlet-name>
<url-pattern>/setting/*</url-pattern>
</servlet-mapping>
Then I created the following file (.../WEB-INF/SettingServlet-servlet.xml):
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd"
>
<bean id="settingController"
class="com.my.package.path.SettingController"
p:settingService-ref="settingService"/>
</beans>
Then I created the following Controller (com.my.package.path.SettingController.java):
#Controller
#RequestMapping("/setting")
public class SettingController {
private SettingService settingService;
public void setSettingService(final SettingService settingService) {
Validate.notNull(settingService, "SettingController::settingService cannot be null");
this.settingService = settingService;
}
#ResponseBody
#RequestMapping(value = "/{name}", method = RequestMethod.GET)
#Secured({ "ROLE_ADMINISTRATOR", "ROLE_CURIOUS_GEORGE" })
public ResponseEntity<String> getSettingRequest(#PathVariable("name") final String name, #RequestParam("setting_family") final String settingFamily) {
final String jsonBody = "{\"setting\":\"" + name + "\", \"Setting Family\":\"" + settingFamily + "\", \"value\":\"test\"}";
return new ResponseEntity<String>(jsonBody, HttpStatus.OK);
}
}
WHAT AM I DOING WRONG? :( I get a 404 not found exception when trying to do a GET request at /setting/fruit?setting_family=foods
as you declared url pattern to your dispatcher as "/setting/*" and then in controller you declared "/setting" as a root requestMapping for this controller, you should be able to access your controller using this url: /setting/setting/fruit?setting_family=foods
:)

Session Filter usage

I need to do a session filter. localhost:8080/Project/faces/index.xhtml is the login. If login is successful, the user will be redirected for app/conta.xhtml, but if user writes localhost:8080/Project/faces/app/conta.xhtml directly in address bar and not logged in must be redirected for index.xhtml again.
All pages that are in app/* must not be accessed without successful login.
My class LoginFilter is in the package filtro
#WebFilter("/app/*")
public class LoginFilter implements Filter {
#Override
public void init(FilterConfig config) throws ServletException {
// If you have any <init-param> in web.xml, then you could get them
// here by config.getInitParameter("name") and assign it as field.
}
#Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
HttpSession session = request.getSession(false);
if (session == null || session.getAttribute("idUsuario") == null) {
response.sendRedirect(request.getContextPath() + "../index.xhtml"); // No logged-in user found, so redirect to login page.
} else {
chain.doFilter(req, res); // Logged-in user found, so just continue request.
}
}
#Override
public void destroy() {
// If you have assigned any expensive resources as field of
// this Filter class, then you could clean/close them here.
}
}
My web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<context-param>
<param-name>javax.faces.PROJECT_STAGE</param-name>
<param-value>Development</param-value>
</context-param>
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>/faces/*</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>faces/index.xhtml</welcome-file>
</welcome-file-list>
<filter>
<filter-name>Login Filter</filter-name>
<filter-class>filtro.LoginFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>Login Filter</filter-name>
<url-pattern>/app/*</url-pattern>
</filter-mapping>
</web-app>
Despite all this, I can enter /faces/app/conta.xhtml and have normal access!
This is my code for Login Validation = validarLogin()
BeanUsuarios.java
#ManagedBean
#ViewScoped
public class BeanUsuarios {
private Usuario usuario;
public Usuario getUsuario() {
return usuario;
}
public void setUsuario(Usuario usuario) {
this.usuario = usuario;
}
#PostConstruct
public void BeanUsuario(){
if(getUsuario()==null){
usuario = new Usuario();
}
}
public void validarLogin(){
UsuarioJpaController cUsuario = new UsuarioJpaController();
cUsuario.getEntityManager().createNamedQuery("Usuario.findByLogin").setParameter("login", this.usuario.getLogin()).getSingleResult();
if(usuario != null){
if(usuario.getSenha().equals(this.usuario.getSenha())){
FacesContext fc = FacesContext.getCurrentInstance();
HttpSession session = (HttpSession) fc.getExternalContext().getSession(false);
session.setAttribute("idUsuario", this.usuario.getId());
try {
FacesContext.getCurrentInstance()
.getExternalContext()
.redirect("app/conta.xhtml");
} catch (IOException ex) {
Logger.getLogger(BeanUsuarios.class.getName()).log(Level.SEVERE, null, ex);
}
}else{
}
}
}
}
You have two options:
Change the filter URL mapping to /faces/app* since that's how you're accessing your pages.
In the web.xml file, get rid of the /faces/* servlet mapping and use *.xhtml instead. This would require to change your welcome file to index.xhtml only.
IMO I would use option 2 since I don't like the Faces Servlet process the non-JSF related requests as JavaScript, CSS and images files.

Categories

Resources