I have looked in to How to skip a filter in the filter chain in java and followed the solution but this didn't help.
I have three filters in my web.xml. Struts filter, custom filter and IAM Agent filter in this order. I want to skip IAM filter based on some condition. I do not have control on IAM filter its external peace of code. So when ever the front end parameter says that the usertype is internal I need to call IAM agent filter else I need to skip this filter.
Web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID"
version="2.5">
<display-name>App</display-name>
<!-- Struts2 Filter -->
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>*.action</url-pattern>
</filter-mapping>
<!-- Custom App Filter for Handling Internal And External User-->
<filter>
<filter-name>UserType</filter-name>
<filter-class>com.App.web.filter.LoginFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>UserType</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- IAM Filter for Internal Users only-->
<filter>
<filter-name>Agent</filter-name>
<filter-class>com.sun.identity.agents.filter.AmAgentFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>Agent</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<listener>
<listener-class>org.apache.tiles.web.startup.TilesListener</listener-class>
</listener>
<listener>
<listener-class>com.App.init.InitListener</listener-class>
</listener>
<context-param>
<param-name>org.apache.tiles.impl.BasicTilesContainer.DEFINITIONS_CONFIG</param-name>
<param-value>/WEB-INF/tiles.xml</param-value>
</context-param>
<!-- Web Service -->
<servlet>
<servlet-name>EventManagementWS</servlet-name>
<servlet-class>com.App.eventmanagement.ws.EventManagementWS</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>EventManagementWS</servlet-name>
<url-pattern>/EventManagementWS</url-pattern>
</servlet-mapping>
<resource-ref>
<res-ref-name>url/ConfigProperty</res-ref-name>
<res-type>java.net.URL</res-type>
<res-auth>Container</res-auth>
<res-sharing-scope>Shareable</res-sharing-scope>
</resource-ref>
I am using RequestDispatcher#forward(), but I not getting anything in my index.jsp page output, just a blank page. The css files are giving 404 error. When I was using Struts tag it gave error
Uncaught exception created in one of the service methods of the servlet /index.jsp in application App. Exception created: The Struts dispatcher cannot be found. This is usually caused by using Struts tags without the associated filter. Struts tags are only usable when the request has passed through its servlet filter, which initializes the Struts dispatcher needed for this tag.
So i removed S tag and used hard coding, but now I am getting 404 error in all css which i was trying to include.
I feel as if the forward is not working fine.
Java Filter Code:
package com.App.web.filter;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.commons.lang.StringUtils;
import com.App.constant.Constant;
import com.App.init.WIMSInitListener;
import com.App.log.WIMSMessageLogger;
public class LoginFilter implements Filter{
FilterConfig _filterConfig = null;
#Override
public void destroy(){
// TODO Auto-generated method stub
}
#Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain filterChain) throws IOException, ServletException{
// Check IAM is enabled
if (InitListener.isIAMEnabled()){
HttpSession session = httpRequest.getSession();
String userType = (String) session.getAttribute(Constant.USER_TYPE);
if(userType == null || "".equals(userType)){
MessageLogger.putMessageLog("User type is null : First Request" + userType, getClass());
userType = request.getParameter(Constant.USER_TYPE);
session.setAttribute(Constant.USER_TYPE, userType);
request.getRequestDispatcher(((HttpServletRequest)request).getServletPath() +
StringUtils.defaultString(((HttpServletRequest)request).getPathInfo()))
.forward(request, response);
}
if("external".equals(userType)){
MessageLogger.putMessageLog("External User" + userType, getClass());
request.getRequestDispatcher(((HttpServletRequest)request).getServletPath() +
StringUtils.defaultString(((HttpServletRequest)request).getPathInfo()))
.forward(request, response);
}
else if("internal".equals(userType)){
MessageLogger.putMessageLog("Internal User" + userType, getClass());
//IAM Filter com.sun.identity.agents.filter.AmAgentFilter
filterChain.doFilter(request, response);
}
}
//Its always External User
else{
MessageLogger.putMessageLog("User IAM Not Enabled", getClass());
request.getRequestDispatcher(((HttpServletRequest)request).getServletPath() +
StringUtils.defaultString(((HttpServletRequest)request).getPathInfo()) )
.forward(request, response);
}
}
#Override
public void init(FilterConfig filterConfig) throws ServletException{
this._filterConfig = filterConfig;
}
}
Index.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>App</title>
<link rel="stylesheet" type="text/css" media="screen"
href="/App/css/common.css" />
<link rel="stylesheet" type="text/css" media="screen"
href="/App/css/rcorp.css" />
<link rel="stylesheet" type="text/css" media="all"
href="/App/css/style.css" />
<link rel="stylesheet" type="text/css" media="all"
href="/App/css/rcorp.css" />
<link rel="stylesheet" type="text/css" media="all"
href="/App/css/default.css" />
<script type="text/javascript">
function selectUserType(){
var frm = document.forms["UserTypeForm"];
if(document.getElementById("userTypeInternal").checked){
//frm.action='<s:url action="loginAction.action?usertype=internal" namespace="" />';
frm.action='/App/loginAction.action?usertype=internal';
}
else{
//frm.action='<s:url action="loginAction.action?usertype=external" namespace="" />';
frm.action='/App/loginAction.action?usertype=external';
}
frm.target='_parent';
frm.submit();
}
function checkUserType(){
//var userType = '<s:property value="#session.usertype" />';
var userType = '<%= session.getAttribute("usertype") %>';
if(userType == 'internal'){
//frm.action='<s:url action="loginAction.action?usertype=internal" namespace="" />';
frm.action='/App/loginAction.action?usertype=internal';
frm.target='_parent';
frm.submit();
}
else if(userType == 'external'){
//frm.action='<s:url action="loginAction.action?usertype=external" namespace="" />';
frm.action='/App/loginAction.action?usertype=external';
frm.target='_parent';
frm.submit();
}
}
</script>
</head>
<body onload="javascript:checkUserType();">
<form method="POST" action="loginAction.action" name="UserTypeForm">
<div id="display_option"
style="DISPLAY: none; position: absolute; top: 40%; width: 100%;"
align="center">
<div class="rcorp-tbl">
<div style="width: 340px;">
<div style="border: 1px solid #6da6fe; padding: 5px;">
<table style="background-color: #f0f8ff;" cellspacing=2 border=0>
<tr>
<td class="t-cellsecnowrap">Select User type:</td>
<td>
<td class="t-cell">
<div id="wwgrp_systemType" class="wwgrp">
<div id="wwctrl_systemType" class="wwctrl">
<input type="radio" name="UserType" id="internal" value="internal" checked/>
<label for="userTypeInternal">Internal User (Sydney Trains Users)</label>
<input type="radio" name="userType" id="external" value="external"/>
<label for="userTypeExternal">External User</label>
<input type="button" name="applyBtn" id="applyBtn" class="btn" value="Go" title="Go" onclick="javascript:selectUserType();"/>
</div>
</div>
</td>
</tr>
</table>
</div>
</div>
</div>
</div>
</form>
</body>
</html>
Instead of trying to control it in your LoginFilter, create a new class that extends com.sun.identity.agents.filter.AmAgentFilter and configure that in your web.xml. You class would look something like this:
public class CustomFilter extends AmAgentFilter {
#Override
public void init(FilterConfig filterConfig) throws ServletException {
super.init(filterConfig);
}
#Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
if (InitListener.isIAMEnabled()) {
HttpSession session = httpRequest.getSession();
String userType = (String) session.getAttribute(Constant.USER_TYPE);
if ("internal".equals(userType)) {
super.doFilter(servletRequest, servletResponse, filterChain);
}
}
filterChain.doFilter(servletRequest, servletResponse);
}
#Override
public void destroy() {
super.destroy();
}
}
The super.doFilter() call will only perform the actions in AmAgentFilter if the criteria in that if-block is met; otherwise, we ignore that filter and move on to the next one in the chain.
You would configure this filter in your web.xml instead of the AmAgentFilter.
Related
I'm doing a project of user management web application for school and when I deploy to Tomcat I got this error.
Additional: On web.xml Intellij cannot recognize class UserFilter when I try to add <filter>. I have a class called UserFilter with the right path.
HTTP Status 500 - Filter execution threw an exception
type Exception report
message Filter execution threw an exception
description The server encountered an internal error that prevented it from fulfilling this request.
exception
javax.servlet.ServletException: Filter execution threw an exception
root cause
java.lang.ExceptionInInitializerError
teste.web.SecurityFilter.openSession(SecurityFilter.java:26)
teste.web.SecurityFilter.doFilter(SecurityFilter.java:19)
root cause
java.lang.NullPointerException
java.util.Properties$LineReader.readLine(Properties.java:434)
java.util.Properties.load0(Properties.java:353)
java.util.Properties.load(Properties.java:341)
teste.pluginSession.PluginFactory.<clinit>(PluginFactory.java:12)
teste.web.SecurityFilter.openSession(SecurityFilter.java:26)
teste.web.SecurityFilter.doFilter(SecurityFilter.java:19)
note The full stack trace of the root cause is available in the Apache Tomcat/9.0.0.M6 logs.
Apache Tomcat/9.0.0.M6
SecurityFilter.java
package teste.web;
import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import teste.pluginSession.*;
public class SecurityFilter implements Filter {
#Override
public void init (FilterConfig filterConfig) throws ServletException{
}
#Override
public void doFilter (ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException{
HttpServletResponse response = (HttpServletResponse) servletResponse;
openSession (servletRequest,filterChain, response);
}
private void openSession(ServletRequest servletRequest, FilterChain filterChain, HttpServletResponse response) throws IOException, ServletException{
RegisterSession plugin = null;
try {
plugin = (RegisterSession) PluginFactory.getPlugin(RegisterSession.class);
plugin.openSession(servletRequest,filterChain,response);
} catch (ClassNotFoundException e){
e.printStackTrace();
}catch (IllegalAccessException e){
e.printStackTrace();
}catch (InstantiationException e){
e.printStackTrace();
}
}
#Override
public void destroy() {
}
}
PluginFactory
package teste.pluginSession;
import java.io.IOException;
import java.util.Properties;
public class PluginFactory
{
static Properties properties = new Properties();
static
{
try {
properties.load(PluginFactory.class.getResourceAsStream("/plugins.properties"));
} catch (IOException e) {
e.printStackTrace();
}
}
public static Object getPlugin(Class iface) throws ClassNotFoundException, IllegalAccessException, InstantiationException
{
String classNameVerdadeiro = properties.getProperty(iface.getName());
return Class.forName(classNameVerdadeiro).newInstance();
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" >
<filter>
<filter-name>UserFilter</filter-name>
<filter-class>teste.web.UserFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>UserFilter</filter-name>
<url-pattern>/user/*</url-pattern>
</filter-mapping>
<filter>
<filter-name>SecurityFilter</filter-name>
<filter-class>teste.web.SecurityFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>SecurityFilter</filter-name>
<url-pattern>*</url-pattern>
</filter-mapping>
<servlet>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>teste.web.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>LogoutServlet</servlet-name>
<servlet-class>teste.web.LogoutServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LogoutServlet</servlet-name>
<url-pattern>/logout</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>Rest</servlet-name>
<servlet-class>teste.web.RestServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Rest</servlet-name>
<url-pattern>/soa</url-pattern>
</servlet-mapping>
<error-page>
<error-code>404</error-code>
<location>/errors/erro404.jsp</location>
</error-page>
<!--START FILES-->
<welcome-file-list>
<welcome-file>login.jsp</welcome-file>
</welcome-file-list>
</web-app>
login.jsp
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<%# page import="teste.web.LoginServlet" %>
<html>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<title>Login</title>
<style>
.login-form {
border: hidden;
padding: 20px;
position: fixed;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
.form-group{
padding-left:40px;
padding-right:40px;
}
h3{
text-align: center;
}
body{
background-color: darkslateblue;
}
</style>
</head>
<body>
<div class="container" style="text-align:center;color:white;transform: translate(0%, 400%);">
<h2><strong>Soft</strong>Ware</h2>
</div>
<div class="container login-form">
<div class="panel panel-default">
<div class="panel-body">
<form class="form-horizontal" action="<%=request.getContextPath()%>/login" method="POST">
<div class="input-group" style="padding-bottom: 10px;">
<span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
<input id="username" class="form-control" placeholder="Username" type="text" name="username">
</div>
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-lock"></i></span>
<input id="password" class="form-control" placeholder="Password" type="password" name="password">
</div>
<div class="form-group" style="text-align: center;padding-top: 10px;">
<button type="submit" class="btn btn-success" onclick=""><span class="glyphicon glyphicon-ok"></span> Submeter</button>
</div>
</form>
</div>
</div>
</div>
</body>
</html>
Many thanks!
I have a servlet, a filter and a login.jsp. I fill the username and pasword and then click the login button and the filter isn't called, only the servlet is called. The servlet and filter are in different packages and I see this is the problem. If I put servlet and filter in the same package the filter is called successfully. But I want to use them in different packages. What should I do? Thanks in advance!
Filter:
package log.reg.myfilter;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
#WebFilter("/LoginFilter")
public class LoginFilter implements Filter {
public void destroy() {
// TODO Auto-generated method stub
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
PrintWriter out = response.getWriter();
HttpServletRequest req = (HttpServletRequest) request;
String username = req.getParameter("username");
String pass = req.getParameter("password1");
System.out.println(username);
if ((username.length() > 6) && (pass.length() > 3)) {
System.out.println("In filter");
chain.doFilter(request, response);
}
else
out.println("Invalid Input");
}
public void init(FilterConfig fConfig) throws ServletException {
// TODO Auto-generated method stub
}
}
Servlet:
package log.reg;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#WebServlet("/firstServlet")
public class FirstServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("In servlet");
PrintWriter out = response.getWriter();
String username = request.getParameter("username");
out.println("Welcome " + username);
}
}
login.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="firstServlet" method="get">
<table style="background-color: lightgreen; margin-left: 20px; margin-top: 20px">
<tr>
<td>
<h3 style="color: red">Login Page!!!</h3>
</td>
</tr>
<tr>
<td>UserName : </td>
<td><input type="text" name="username"></td>
</tr>
<tr>
<td>Password : </td>
<td><input type="password" name="password1"></td>
</tr>
<tr>
<td><input type="submit" name="submit" value="login"></td>
</tr>
</table>
</form>
</body>
</html>
web.xml
<?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>Servlet ex29 - filter</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>
</web-app>
The value() of #WebServlet and #WebFilter don't have the same meaning.
The first one specifies the URL patterns of the servlet (that is its URL mapping) while the second one specifies the URL patterns to which the filter applies.
But in both cases you specified as name the simple name of the underlying class.
For the servlet, #WebServlet("/firstServlet") makes sense but annotating your Filter with #WebFilter("/LoginFilter") is not what you are looking for as
you don't want to filter only the "/LoginFilter" URL.
For example to filter any requested URL you could specify :
#WebFilter("/*")
A Servlet filter is an object that can intercept HTTP requests targeted at your web application. As I see here, you have not associated filter with servlet. You have to tell the url pattern you want to intercept/filter.
Note: Filter won't be executed independently it works with
Servlet. So You have to associated Filter with Servlets.
If you have to associate with FirstServlet then use below one.
#WebFilter("/firstServlet")
If you want to filter each request you can use /*
#WebFilter("/*")
I am learning Java CRUD Operation . I am trying to insert ,update and delete records from sql database.The insert and displaying all records methods is working but the problem is when I click edit and delete links ,its throw http 404 not found exception
Here is my HTML code display all the records .
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>All Posts</title>
</head>
<body>
<div style="width: 1200px; margin-left: auto; margin-right: auto;">
<table cellpadding="10">
<tr>
<th>Id</th>
<th>Title</th>
<th>Description</th>
<th>Detail</th>
<th>Category</th>
<th>Date</th>
<th>Image</th>
<th></th>
</tr>
<c:forEach items="${AllPost}" var="p">
<tr>
<td>${p.id}</td>
<td>${p.title}...</td>
<td>${p.description}...</td>
<td>${p.detail}...</td>
<td>${p.category}</td>
<td>${p.date}...</td>
<td>${p.image}...</td>
<td>
Edit
Delete
</td>
</tr>
</c:forEach>
</table>
</div>
</body>
</html>
Here is the HTML for EidtPost.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Edit</title>
</head>
<body>
<h1>Edit News</h1>
<div style="width: 900px; margin-left: auto; margin-right: auto">
<c:forEach items="${getNewsById}" var="p">
<form action="JSP/ManagerEditPost.jsp" method="post">
<input type="hidden" name="id" value="${p.id}">
Title:<br>
<input type="text" value="${p.title}" name="title" style="width: 200px"><br>
Description:<br>
<input type="text" value="${p.description}" name="description" style="width: 200px"><br>
Detail:<br>
<textarea name="detail" style="width: 400px; height: 200px">${p.detail}</textarea><br>
Category:
<select name="category">
<option value="${p.category}">${p.category}</option>
<option value="World">World</option>
<option value="Tech">Tech</option>
<option value="Sport">Sport</option>
</select><br>
Image:<br>
<input type="text" value="${p.image}" name="image" style="width: 200px"><br>
<input type="submit" value="Submit">
</form>
</c:forEach>
</div>
</body>
</html>
Here is the Data Access code for CRUD operation.
public void edit(int id, String title, String description, String detail, String category, String image){
try {
String sql = "update News SET title = ?, description = ?, detail = ?, category = ?, image = ?" + " where id = ?";
PreparedStatement ps= DBUtils.getPreparedStatement(sql);
ps.setString(1, title);
ps.setString(2, description);
ps.setString(3, detail);
ps.setString(4, category);
ps.setString(5, image);
ps.setInt(6, id);
ps.executeUpdate();
} catch (ClassNotFoundException | SQLException ex) {
Logger.getLogger(DataAccess.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
Here is the servlet code .
#WebServlet(name = "EditPost", urlPatterns = {"/EditPost"})
public class EditPost extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
{
String idTemp = request.getParameter("id");
int id = Integer.parseInt(idTemp);
request.setAttribute("getNewsById", DataAccess.getNewById(id));
RequestDispatcher rd = request.getRequestDispatcher("CRUD/EditPost.jsp");
try {
rd.forward(request, response);
} catch (ServletException | IOException ex) {
Logger.getLogger(EditPost.class.getName()).log(Level.SEVERE, null, ex);
}
}
Here is the code web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" 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">
<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>
<servlet-name>EditPost</servlet-name>
<servlet-class>servlet.EditPost</servlet-class>
</servlet>
<servlet>
<servlet-name>DeletePost</servlet-name>
<servlet-class>servlet.DeletePost</servlet-class>
</servlet>
<servlet>
<servlet-name>AllPost</servlet-name>
<servlet-class>servlet.AllPost</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>/faces/*</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>EditPost</servlet-name>
<url-pattern>/EditPost</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>DeletePost</servlet-name>
<url-pattern>/DeletePost</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>AllPost</servlet-name>
<url-pattern>/AllPost</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>
</web-app>
Here is the screen shot of the error when i click the edit and delete link .
The following shows the minimum necessary to create the desired functionality. Obviously everything about the true implementation needs to be added.
Ultimately, the path in the .jsp needs to match to the #WebServlet path. Though the specific forwarding depends a bit on absolute vs. relative URLs.
This works in tomcat 9.0, but is likely applicable to other such servers such as glassfish, etc.
web.xml
This provides the basic information.
<web-app>
<welcome-file-list>
<welcome-file>welcome.jsp</welcome-file>
</welcome-file-list>
</web-app>
welcome.jsp
This is just an example .jsp that provides an href.
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h1>Hello World!</h1>
<!-- note this can also be ./EditPost -->
<!-- also note that not passing any query here -->
Edit Post
</body>
</html>
EditPost.java
This is a quick example of an annotated servlet.
#WebServlet("/EditPost")
public class EditPost extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* Default constructor.
*/
public EditPost() {
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.getWriter().append("Served at: ").append(request.getContextPath());
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
I'm unable to pass userName from below JSP and access it in Servlet filter. Below are the JSP & Filter. I have tried accessing using request Paramter,attribute and ParameterNames, but getting only null values.
I have run the application in debug mode and it is hitting the filter after I press submit button.
Please let me know if I'm doing anything wrong.
JSP:
<html>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<head>
</head>
<body>
<p><bean:message key="logonForm.info.text"/></p>
<form action="/uchpweb/login.do" name="login_form" method="post">
<div id="layLogInContainer">
<div id="layLogInFields" class="inputAreaLight">
<b>UserName</b><br>
<input type="text" name="username" id="username" tabindex="1" size="10" maxlength="10" /><br />
</div>
<div id="layLogInButtonBar" class="btnBar">
<input type="submit" name="submit" value="submit"/>
</div>
</div>
</form>
</body>
</html>`
Filter:
public class UserFilter implements Filter {
FilterConfig config;
Boolean flag;
#SuppressWarnings("unused")
private Logger log = ResourceLocator.getInstance().getLogger(this);
public void init(FilterConfig config) {
this.config = config;
}
#SuppressWarnings("unchecked")
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpSession httpSession = httpRequest.getSession();
Enumeration<String> params = httpRequest.getParameterNames();
while(params.hasMoreElements()){
String name = params.nextElement();
String value = request.getParameter(name);
log.debug("Name : ",name);
log.debug("value : ",value);
}
if (request.getParameter("username") == null && (request.getAttribute("username") == null)) {
RequestDispatcher dispatcher1 = request.getRequestDispatcher("/logon.jsp");
if (dispatcher1 != null) {
dispatcher1.forward(request, response);
return;
}
}
}
web.xml
<filter>
<filter-name>CommonUserContextFilter</filter-name>
<filter-class>UserContextFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>CommonUserContextFilter</filter-name>
<url-pattern>*.do</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>CommonUserContextFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>CommonUserContextFilter</filter-name>
<url-pattern>*.jsp</url-pattern>
</filter-mapping>
I have a simple JSP project, which has 3 classes, controllers and DAO's
I can Login but when I click on my buttons, I just can't get the Parameters from the form.
Lemme show the code, and maybe You'll figure it out:
package school.controller;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import school.dao.StudentDAO;
import school.model.Student;
public class StudentController extends HttpServlet {
private static final long serialVersionUID = 1L;
private static String UPDATE = "/student.jsp";
private static String VIEW_COURSES = "CourseController";
private static String VIEW_GRADES = "GradeController";
private StudentDAO dao;
public StudentController() {
dao = new StudentDAO();
}
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String forward = "";
String action = request.getParameter("name");
if (action.equalsIgnoreCase("update")) {
forward = UPDATE;
Student student = (Student) request.getAttribute("student");
request.setAttribute("student", student);
} else if (action.equalsIgnoreCase("viewgrades")) {
forward = VIEW_GRADES;
Student student = (Student) request.getAttribute("student");
request.setAttribute("student", student);
} else if (action.equalsIgnoreCase("viewcourses")) {
forward = VIEW_COURSES;
Student student = (Student) request.getAttribute("student");
request.setAttribute("student", student);
}
RequestDispatcher view = request.getRequestDispatcher(forward);
view.forward(request, response);
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
And here's the WEB.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>School_JSP</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<description></description>
<display-name>CourseController</display-name>
<servlet-name>CourseController</servlet-name>
<servlet-class>school.controller.CourseController</servlet-class>
</servlet>
<servlet>
<description></description>
<display-name>StudentController</display-name>
<servlet-name>StudentController</servlet-name>
<servlet-class>school.controller.StudentController</servlet-class>
</servlet>
<servlet>
<description></description>
<display-name>LoginServlet</display-name>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>school.controller.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>StudentController</servlet-name>
<url-pattern>/StudentController</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>CourseController</servlet-name>
<url-pattern>/CourseController</url-pattern>
</servlet-mapping>
</web-app>
And the mainPage.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Main Page</title>
</head>
<body>
<h3>
Welcome,
<c:out value="${student.firstName}" />
</br>
<h1>My Personal Information</h1>
<center>
<form method="POST" action='StudentController' name="viewgrades">
<input type="submit" value="View My Grades" />
</form>
<form method="POST" action='StudentController' name="viewcourses">
<input type="submit" id="hidden" value="View My Courses" />
</form>
<form method="POST" action='StudentController' name="update">
<input type="submit" id="hidden" value="Update Personal Information" />
</form>
</center>
</h3>
</body>
</html>
You're confusing attributes and parameters.
Parameters are String values sent by the browser. They're accessed using the getParameterXxx() family of methods.
Attributes are data that you can add to a request (or session, or servlet context), or any type, in order to get them backlater. You typically add an attribute to the request in a servlet (for example, the information about the logged in user) in order to get back this attribute in the JSP and display the information.
In your code, the only place where you get a parameter is commented out. And you're trying to get a parameter named "hidden", although none of the form has an input field with than name. It's the name attribute of an input field that is submitted by the browser, and not its id attribute.
Also, you should use GET rather than POST for actions which consist in getting or reading things.
The reason you don't get any values is that the attribute "name" in the form, indeed is just the name of the form and isn't sent at all.
To actually send data, you need to provide some in the innerHTML of the form. Like this (not the best solution, but should you get running):
<form method="GET" action="StudentController" name="formName">
<input type="hidden" name="viewgrades" value="show" />
<input type="submit" value="View My Grades" />
</form>
After this you can read the sent data "viewgrades=show" (parameter=value) in your Java-class.
Also, btw, you shouldn't use "h3" as a paragraph ("p") or section. It is intended to be a headline.