I have a page who is divided by campus. Is basically the same page but I change the information depending to the campus.
The param "campus", set who is the currently used campus.
This work very well, for example if I access to localhost/page/campus1/index.action, the getCampus method return "campus1", has expected.
But if I access to localhost/page/campus1/index.action?campus=campus2, the getCampus() method return "campus2"; I try to avoid this behavior. I want the {campus} param was in the top of the priority and nobody can override him.
I tray using "excludeParams" from the "param" interceptor to exclude "campus" but now getCampus return null.
how can I exclude some get/post method from the param read by struts2?
or
can avoid the static param been override by others param?
EDIT:
I have a interceptor who say if the chosen campus is valid one or not.
If someone enter a real campus in the url, but put a "get method" with a wrong campus the test will pass but all the information will be wrong.
My action
#Action(value="{campus}/index",
results={
#Result(name=SUCCESS,location="/jsp/campusindex.jsp"),
}
)
public String campusIndex(){
return SUCCESS;
}
public void setCampus(String campus){
this.campus=campus;
}
public String getCampus(){
return this.campus;
}
My jsp
<%# taglib prefix="s" uri="/struts-tags"%>
<s:label name="campus"/>
My Interceptor
public String intercept(ActionInvocation actionInvocation) throws Exception {
ActionConfig config = actionInvocation.getProxy().getConfig();
String campus = config.getParams().get("campus");
try{
Campus.isaValidCampus(campus);
} catch(Exception e){
return "error404";
}
return actionInvocation.invoke();
}
Related
I'm currently using a Spring Boot application I'm tinkering around the the error page and the messages given to it. Currently I can change the HTTP Status Number and Message, but I'm not sure how to change the "Unknown reason" or Description without changing it to something besides 418. Is there a way to customize those as well, or am I stuck with the embedded code provide?
Current Code Tinkering
for(String serialNo : serialNoList) {
if(serialNo.length() < MIN_SERIALNO_SIZE ) {
response.sendError(401, "Serial Number Length Exceeded: " + serialNo);
}
if(serialNo.length() > MAX_SERIALNO_SIZE) {
response.sendError(403, "Serial Number Legth Too Short: " + serialNo);
}
}
First, you need to disable whiteLabel error pages.
server.error.whitelabel.enabled=false
or
// adding this on your main class
#EnableAutoConfiguration(exclude = {ErrorMvcAutoConfiguration.class})
Now, create a html page (error.html), which you want to display and place it in resources/templates directory, it will be picked automatically.
To customize, differently for each error you can implement ErrorController.
#Controller
public class CustomErrorController implements ErrorController {
// override this error path to custom error path
#Override
public String getErrorPath() {
return "/custom-error";
}
#GetMapping("/custom-error")
public String customHandling(HttpServletRequest request){
// you can use request to get different error codes
// request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE)
// you can return different `view` based on error codes.
// return 'error-404' or 'error-500' based on errors
}
}
I'd like to redirect the user to an error page from within an Advice without having to throw an exception if a param is not specified. Is that possible? If so, how can I do it?
I'm currently throwing an exception but I feel it's overkill and the log it leaves is too much:
#Aspect
#Component
public class ParamTracker{
private static final Logger logger = LogManager.getLogger("ParamTrackerLogger");
#Before("execution(* com.controller.MainController.*(..)) && !execution(* com.controller.MainController.doNotUseThis(..))")
public void trackParam(JoinPoint point) throws Exception {
String methodName = point.getSignature().getName();
String param = point.getArgs()[0].toString();
if(param.isEmpty()) {
logger.error("Param is empty");
throw new Exception("Please specify param");
} else {
logger.info(param + ". " + methodName);
}
}
}
Having the user redirected to an error page and a simple Param not specified. Redirecting to error page ... on the log would be ideal. Also, it doesn't have to be a #Before, as long as it works.
Thanks in advance.
I think one possible solution might be something like this:
You can write a custom exception for when a param is invalid. eg ParamIsEmptyException.
When param is empty, throw above exception instead of normal exception.
In your central exception handler(if you don't have it, you can simply make it), check the exception type, if the exception has ParamIsEmptyException type, you can use HttpServletResponse.sendRedirect method for redirecting user to any url.
I have been struggling to print text inside a Java method on a Java server page. Here are some ways I've attempted to print the text and errors thrown from the Tomcat (Version 7.0.56) compiler:
<%
class Base {
public void main() {
String Text = "ThisIsText";
out.println(Text);
}
}
%>
Error: Cannot refer to the non-final local variable out defined in an enclosing
scope
<%
class Base {
static Text;
public void main() {
String Text = "ThisIsText";
}
out.println(Text);
}
%>
Syntax error, insert "Identifier (" to complete MethodHeaderName
<%
class Base {
static Text;
public String text() {
String Text = "NewText";
return Text;
}
}
%>
<%text();%>
The method text() is undefined for the type Base_jsp
Is there any way to print HTML Text directly from a Java method in a JSP scriptlet?
The out variable is already inside a method - _jspService. So if you are going to use out, declare another method that takes out as parameter using declaration - <%! and then just call this method.
Use a declarative tag instead
<%!
class Base {
JspWriter out;
public Base(JspWriter out) {
this.out = out;
}
public void main() {
String Text = "ThisIsText";
try {
out.println(Text);
} catch (Exception e) {
e.printStackTrace();
}
}
}
%>
<%(new Base(out)).main();%>
when you write something in <%%> the code between these tags is placed in methods so you cant declare function or class inside that tags because we cant have methods or class inside methods.
Similar,Also check
Is there any way to do that?
I heard something about implemented RequestCycle, how to acomplish that?
Tried How can I get the responsePage from a RequestCycle in Wicket 1.5? this, but doesnt work.
The reason why you get a PageExpiredException in Wicket is because Wicket is unable to find the page. There is no way of determining the type of the page that is no longer available, because, well, the page actually is no longer there. It ceased to exist, met its maker, bereft of life, rests in peace, its lifecycle are now 'istory, kicked the bucket. It is an ex-page.
So Wicket's only recourse is to serve the PageExpiredException, and there is no way (in Wicket itself) to retrieve the page that was attempted to resurrect.
Now what you can try to do is to store the class of the last rendered page in the session, and use that in your RequestCycleListener implementation of onException() and return the appropriate request handler. In code:
#Override
public void onRequestHandlerExecuted(RequestCycle cycle, IRequestHandler handler) {
Class<? extends Page> p = null;
if(handler instanceof IPageRequestHandler)
p = ((IPageRequestHandler)handler).getPageClass();
else if(handler instanceof IComponentRequestHandler)
p = ((IComponentRequestHandler)handler).getComponent().getPage().getClass();
MySession.get().setLastPageClass(p);
}
#Override
public IRequestHandler onException(RequestCycle cycle, Exception ex) {
Class<? extends Page> pageClass MySession.get().getLastPageClass();
... return some handler based on your logic
}
You might want to check for more IRequestHandler implementations in onRequestHandlerExecuted.
If I understand correctly you want to redirect user only if pageExpired happened from specific page? You can try something like this in you implementation of Application:
getRequestCycleListeners().add(new AbstractRequestCycleListener() {
#Override
public IRequestHandler onException(RequestCycle cycle, Exception e) {
if(e.getClass().equals(PageExpiredException.class)) {
//check if url in request responds to correct mounted page type
if(isPageUrl(cycle.getRequest().getUrl()))) {
return new RenderPageRequestHandler(new PageProvider(MyPage.class));
} else {
return super.onException(cycle, e);
}
} else {
return super.onException(cycle, e);
}
}
}
This assumes few things - that the page at which you got the exception has been mounted, and that you will be able to parse request url to be sure it is it.
I haven't tested it but we are doing something similar.
I am writing a class in JSP to retrieve a bunch of config values from an XML file. My plan is to have a class "XMLConfig" that loads in the values from the file, and then uses access methods to get at the values in the config object.
My problem is that i cannot seem to call application.getRealPath() from within the class, since eclipse tells me that "application cannot be resolved". I suspect that I must change "application" to something else but I am unsure what.
My code for the class:
<%!
//Config object
public class XMLConfig {
public boolean loadConfigFile(String strName) {
String XMLfileName = application.getRealPath(strName);
try {
DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = null;
doc = db.parse(XMLFileName);
}catch(Exception e)
{
System.out.println(e.getMessage());
return false;
}
return true;
}
}
%>
application isn't a global var. If you want to use it in your method then you'll need to pass it as a parameter.
Not sure why you're defining the class within the jsp though instead of just creating a 'normal' java class.
That's a job for a servlet instead of JSP. Create a class which extends HttpServlet and implement the doGet() method as follows:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String strName = getOrDefineItSomehow();
Document doc = loadConfigFile(getServletContext().getRealPath(strName));
// Do whatever you want with it and then display JSP page.
request.getRequestDispatcher("/WEB-INF/config.jsp").forward(request, response);
}
Map this servlet in web.xml on an url-pattern of for example /config and invoke it by for example http://example.com/context/config. It'll run the code in doGet().
See also:
Beginning and intermediate JSP/Servlet tutorials
How to avoid Java code in JSP?
Hidden features of JSP/Servlet