it says that : HTTP method POST is not supported by this URL.
The specified HTTP method is not allowed for the requested resource.
here's my servlet code:
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class UserController extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final int Id = 0;
private static final String Password = null;
private static final String Username = null;
private static final int Userid = 0;
private static String INSERT_OR_EDIT = "/user.jsp";
private static String LIST_USER = "/listUser.jsp";
public static String PARAM_USERNAME = "uname";
public static String PARAM_PASSWORD = "pass";
private UserDao dao;
private Connection connection;
public UserController() {
super();
dao = new UserDao();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
String forward="";
String act = request.getParameter("act");
if (act != null && !act.equalsIgnoreCase("null") && act.equalsIgnoreCase("login")) {
forward= "/Login.jsp";
}
else if (act != null && !act.equalsIgnoreCase("null") && act.equalsIgnoreCase("delete"))
{
int userId = Integer.parseInt(request.getParameter("userId"));
dao.deleteUser(userId);
forward = LIST_USER;
request.setAttribute("users", dao.getAllUsers());
} else if (act!=null && !act.equalsIgnoreCase("null") && act.equalsIgnoreCase("edit")){
forward = INSERT_OR_EDIT;
int userId = Integer.parseInt(request.getParameter("userId"));
User user1 = dao.getUserById(userId);
request.setAttribute("user", user1);
} else if (act!=null && !act.equalsIgnoreCase("null") && act.equalsIgnoreCase("listUser")){
forward = LIST_USER;
request.setAttribute("users", dao.getAllUsers());
} else if (act!=null && !act.equalsIgnoreCase("null") && act.equalsIgnoreCase("register")){
forward = "/reg.jsp";
// request.setAttribute("users", dao.getAllUsers());
}else if (act!=null && !act.equalsIgnoreCase("null") && act.equalsIgnoreCase("update")){
forward = "/welcome.jsp";
} else
forward = "/Login.jsp";
RequestDispatcher view = request.getRequestDispatcher(forward);
view.forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response, Details details) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out=response.getWriter();
String act = request.getParameter("act");
if (act != null && !act.equalsIgnoreCase("null") && act.equalsIgnoreCase("login")) {
String str=request.getParameter("username");
String str1=request.getParameter("password");
if(str.equalsIgnoreCase("shreya")&&str1.equalsIgnoreCase("singh"))
{
System.out.println("Login!");
request.setAttribute("users",dao.getAllUsers());
request.getRequestDispatcher("/listUser.jsp").forward(request, response);
}else
{
System.out.println("Login failed!");
}
}
if (act != null && !act.equalsIgnoreCase("null") && act.equalsIgnoreCase("register"))
{
String userid1=request.getParameter("userid");
String username=request.getParameter("username");
String password=request.getParameter("password");
String id=request.getParameter("id");
if(userid1.equals("") || username.equals("") || password.equals("") || id.equals(""))
{
out.println("Please insert valid data");
}
RequestDispatcher rd = request.getRequestDispatcher("/listUser.jsp");
rd.include(request, response);
}
else
{
RequestDispatcher rd = request.getRequestDispatcher("/listUser.jsp");
rd.include(request, response);
try {
PreparedStatement preparedStatement = connection.
prepareStatement("select * from details where id=?");
preparedStatement.setInt(1, Id);
ResultSet rs = preparedStatement.executeQuery();
if (rs.next()) {
details.setUserid(rs.getInt("userid"));
details.setUsername(rs.getString("username"));
details.setPassword(rs.getString("password"));
details.setId(rs.getInt("id"));
}
PreparedStatement preparedStatement1 = connection.
prepareStatement( "insert into details values(?,?,?,?)");
preparedStatement1.setInt(1, Userid);
preparedStatement1.setString(2, Username);
preparedStatement1.setString(3, Password);
preparedStatement1.setInt(4, Id);
int i=preparedStatement1.executeUpdate();
if(i>0)
{
System.out.println("Data updated sucessfully");
System.out.print("Student record successfully inserted");
RequestDispatcher rd1 = request.getRequestDispatcher("/registration.jsp");
rd1.include(request, response);
}
}
catch (Exception e)
{
System.out.println(e);
}
if (act != null && !act.equalsIgnoreCase("null") && act.equalsIgnoreCase("update"))
{
String userid=request.getParameter("userid");
String username=request.getParameter("username");
String password=request.getParameter("password");
String id=request.getParameter("id");
try
{
Statement stmt = connection.createStatement();
String sql = "UPDATE details SET username='hi',password='hello' where id=1";
stmt.executeUpdate(sql);
dao.saveData(details, sql);
System.out.println("Data update sucessfully");
}
catch (SQLException e) {
e.printStackTrace();
}
catch (Exception e) {
e.printStackTrace();
}
finally{
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}
}
earlier it was working properly . I guess there's something wrong with the post method
The HttpServlet doPost(HttpServletRequest req, HttpServletResponse resp) method is
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException
{
String protocol = req.getProtocol();
String msg = lStrings.getString("http.method_post_not_supported");
if (protocol.endsWith("1.1")) {
resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, msg);
} else {
resp.sendError(HttpServletResponse.SC_BAD_REQUEST, msg);
}
}
Which immediately responds with METHOD_NOT_ALLOWED. You haven't overriden this method. You have overloaded it to add a Details parameter. It's therefore not being called
protected void doPost(HttpServletRequest request, HttpServletResponse response, Details details) throws ServletException, IOException {
Where do you expect these Details to come from? If anything, override the doPost method and make it call your method.
Change
protected void doPost(HttpServletRequest request, HttpServletResponse response,
Details details) throws ServletException, IOException
To
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
doPost
Related
I am trying to do long polling in a struts web application. I start an AsyncContext inside an ActionSupport action method, do some time-consuming work async, and then would like to send the SUCCESS response to struts.
I know that I can do PrintWriter pw = asyncContext.getResponse().getWriter(); and write a raw response, but I would like to somehow signal struts to proceed with the predefined result in struts.xml. Is this possible?
<action name="myAction" method="action1" class="myActionClass">
<result name="success" type="redirectAction">
/pages/myPage.jsp <!-- I want to run this from async --->
</result>
</action>
In non-async action I can simply return SUCCESS and struts takes care of everything, but I am having trouble with achieving a similar effect with async action. This is what I have so far:
public void action1() {
HttpServletRequest req = ServletActionContext.getRequest();
HttpServletResponse res = ServletActionContext.getResponse();
final AsyncContext asyncContext = req.startAsync(req, res);
asyncContext.start(new Runnable() {
public void run() {
// Some time-consuming polling task is done here
asyncContext.complete();
// Can I somehow proceed to predefined struts result from here?
}
});
}
Currently it seems cannot be done clearly. I am working if I can import this support to Struts but for now, I have a hack which works. I extended StrutsExecuteFilter as below:
package me.zamani.yasser.ww_convention.utils;
import org.apache.struts2.dispatcher.PrepareOperations;
import org.apache.struts2.dispatcher.filter.StrutsExecuteFilter;
import org.apache.struts2.dispatcher.filter.StrutsPrepareFilter;
import org.apache.struts2.dispatcher.mapper.ActionMapping;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
/**
* Created by user on 8/31/2017.
*/
public class MYStrutsAsyncExecuteFilter extends StrutsExecuteFilter {
public final int REQUEST_TIMEOUT = 240000;//set your desired timeout here
private ExecutorService exe;
#Override
public void init(FilterConfig filterConfig) throws ServletException {
int size = 41;//set your desired pool size here
exe = Executors.newFixedThreadPool(
size,
new ThreadFactory() {
public Thread newThread(Runnable r) {
return new Thread(r, "My Struts Async Processor");
}
}
);
super.init(filterConfig);
}
#Override
public void doFilter(final ServletRequest req, final ServletResponse res, final FilterChain chain) throws IOException, ServletException {
final HttpServletRequest request = (HttpServletRequest) req;
final HttpServletResponse response = (HttpServletResponse) res;
if (excludeUrl(request)) {
chain.doFilter(request, response);
return;
}
// This is necessary since we need the dispatcher instance, which was created by the prepare filter
if (execute == null) {
lazyInit();
}
final ActionMapping mapping = prepare.findActionMapping(request, response);
//if recursion counter is > 1, it means we are in a "forward", in that case a mapping will still be
//in the request, if we handle it, it will lead to an infinite loop, see WW-3077
final Integer recursionCounter = (Integer) request.getAttribute(PrepareOperations.CLEANUP_RECURSION_COUNTER);
if (mapping == null || recursionCounter > 1) {
boolean handled = execute.executeStaticResourceRequest(request, response);
if (!handled) {
chain.doFilter(request, response);
}
} else {
/* I ADDED THESE */
final AsyncContext context = req.startAsync();
context.setTimeout(REQUEST_TIMEOUT);
context.addListener(new AsyncListener() {
public void onComplete(AsyncEvent asyncEvent) throws IOException {
}
public void onTimeout(AsyncEvent asyncEvent) throws IOException {
context
.getResponse()
.getWriter().write("Request Timeout");
}
public void onError(AsyncEvent asyncEvent) throws IOException {
context
.getResponse()
.getWriter().write("Processing Error");
}
public void onStartAsync(AsyncEvent asyncEvent) throws IOException {
}
});
exe.execute(new ContextExecution(context, mapping));
}
}
private boolean excludeUrl(HttpServletRequest request) {
return request.getAttribute(StrutsPrepareFilter.class.getName() + ".REQUEST_EXCLUDED_FROM_ACTION_MAPPING") != null;
}
#Override
public void destroy() {
exe.shutdown();
super.destroy();
}
class ContextExecution implements Runnable {
final AsyncContext context;
ActionMapping mapping;
public ContextExecution(AsyncContext context, ActionMapping mapping) {
this.context = context;
this.mapping=mapping;
}
public void run() {
try {
execute.executeAction((HttpServletRequest) context.getRequest(),
(HttpServletResponse) context.getResponse(), mapping);
context.complete();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
then
<filter>
<filter-name>struts2asyncexecute</filter-name>
<filter-class>me.zamani.yasser.ww_convention.utils.MYStrutsAsyncExecuteFilter</filter-class>
<async-supported>true</async-supported>
</filter>
then put your desired async actions in a specific package and exclude them from Strut's original filter but map them to above filter in your web.xml.
I'm working to improve this to be more configurable and clear then import to Struts.
Could you please test in your app? and please feel free to let me know any idea.
My Application is on Liferay 6.2 with spring mvc portlets.
I have filter for cross site scripting(XSS) for action and render mapping.
#RenderMapping , #RequestMapping and #ActionMapping
<filter>
<filter-name>MyFilter</filter-name>
<filter-class><pkg>.MyActionFilter</filter-class>
**<lifecycle>RENDER_PHASE</lifecycle>
<lifecycle>ACTION_PHASE</lifecycle>**
</filter>
<filter-mapping>
<filter-name>MyFilter</filter-name>
<portlet-name>*</portlet-name>
</filter-mapping>
But I am using #ResourceMapping for ajax call. where I am using HttpServletRequest to get the parameter value
#ResourceMapping(value = "ajaxOperation")
public void inboundOperationsAdd(ResourceRequest resourceRequest, ResourceResponse resourceResponse)
throws Exception
{
HttpServletRequest httpServletRequest = PortalUtil
.getHttpServletRequest(resourceRequest);
HttpServletRequest httpRequest= PortalUtil
.getOriginalServletRequest(httpServletRequest);
and getting the parameter value from httprequest
String parameterValue = httpRequest.getParameter("paraName");
Now I want to introduce same cross site scripting(XSS) filter for #ResourceMapping.
I tried <lifecycle>RESOURCE_PHASE</lifecycle> but it is not working.
Please guide me how to do it.
Updated on 26th Aug
the filter working for #RenderMapping , #RequestMapping and #ActionMapping
from portlet.xml
<filter>
<filter-name>FERenderActionFilter</filter-name>
<filter-class>sg.gov.frontier.filter.FERenderActionFilter</filter-class>
<lifecycle>RENDER_PHASE</lifecycle>
<lifecycle>ACTION_PHASE</lifecycle>
</filter>
<filter-mapping>
<filter-name>FERenderActionFilter</filter-name>
<portlet-name>*</portlet-name>
</filter-mapping>
And the filter
import java.io.IOException;
import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.PortletException;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;
import javax.portlet.filter.ActionFilter;
import javax.portlet.filter.FilterChain;
import javax.portlet.filter.FilterConfig;
import javax.portlet.filter.RenderFilter;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
public class FERenderActionFilter implements RenderFilter, ActionFilter {
private static Log log = LogFactoryUtil.getLog(FERenderActionFilter.class);
#Override
public void init(FilterConfig filterConfig)
throws PortletException {
}
#Override
public void destroy() {
}
#Override
public void doFilter(RenderRequest request, RenderResponse response, FilterChain chain)
throws IOException, PortletException {
chain.doFilter(new FERenderRequestWrapper(request), response);
}
#Override
public void doFilter(ActionRequest request, ActionResponse response, FilterChain chain)
throws IOException, PortletException {
chain.doFilter(new FEActionRequestWrapper(request), response);
}
}
and the Wrapper 1
import javax.portlet.ActionRequest;
import javax.portlet.filter.ActionRequestWrapper;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document.OutputSettings;
import org.jsoup.safety.Whitelist;
import sg.gov.frontier.common.filter.FEParameterCleanup;
public class FEActionRequestWrapper extends ActionRequestWrapper {
public FEActionRequestWrapper(ActionRequest request) {
super(request);
}
#Override
public String getParameter(String name) {
String value = super.getParameter(name);
if (value == null) {
return null;
}
return FEParameterCleanup.cleanXSS(value);
}
#Override
public String[] getParameterValues(String name) {
String[] values = super.getParameterValues(name);
if (values == null) {
return null;
}
int count = values.length;
String[] encodedValues = new String[count];
for (int i = 0; i < count; i++) {
encodedValues[i] = FEParameterCleanup.cleanXSS(values[i]);
}
return encodedValues;
}
}
and the Wrapper 2
import javax.portlet.RenderRequest;
import javax.portlet.filter.RenderRequestWrapper;
import sg.gov.frontier.common.filter.FEParameterCleanup;
public class FERenderRequestWrapper extends RenderRequestWrapper {
public FERenderRequestWrapper(RenderRequest request) {
super(request);
}
#Override
public String getParameter(String name) {
String value = super.getParameter(name);
if (value == null) {
return null;
}
return FEParameterCleanup.cleanXSS(value);
}
#Override
public String[] getParameterValues(String name) {
String[] values = super.getParameterValues(name);
if (values == null) {
return null;
}
int count = values.length;
String[] encodedValues = new String[count];
for (int i = 0; i < count; i++) {
encodedValues[i] = FEParameterCleanup.cleanXSS(values[i]);
}
return encodedValues;
}
}
this wierd problem is very interrupting me for a long time. I have a class name Connector inside dynamic web application in eclipse, with these code:
public class Connector {
private static final String dbURL = "jdbc:mysql://localhost:3306/";
private Connection con;
public Connector(String userName, String password) {
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
con = DriverManager.getConnection(dbURL, userName, password);
} catch (SQLException e) {
e.printStackTrace();
}
catch (ClassNotFoundException e) {
e.printStackTrace();
}
catch (Exception e) {
System.err.print("Unidentified exception has acurred!");
e.printStackTrace();
}
}
when I'm using it from different Class in the same package, named portal, it works fine, but when I'm trying to use it from servlet in package servlets, named LoginHandle.java, I get ClassNotFoundException.
The Class is in the build path of all classes, and I checked it by trying to import it from the servlet, but when I create new instance, it is not being recognized. I tried to move the servlet to the package of the connector, and vise versa, and it didn't affect. Here is the servlet's code:
package servlets;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import portal.Connector;
import portal.UserTableAnalyzer;
#WebServlet("/LoginHandle")
public class LoginHandle extends HttpServlet {
private static final long serialVersionUID = 1L;
public LoginHandle() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String referer = request.getHeader("Referer");
String pageName = referer.substring(referer.lastIndexOf('/') + 1);
if(pageName.equals("Login.jsp"))
{
HttpSession session = request.getSession(false);
Connector c = new Connector("root", "16180339887");
c.executeUpdate("USE Main");
String id = request.getParameter("id"), password = request.getParameter("password");
String query = "SELECT FROM Users WHERE id ='" + id + "' AND password = '" + password + "'";
String[][] result = c.executeQuery(query);
UserTableAnalyzer uta = new UserTableAnalyzer(result);
if(result.length > 0)
{
session.setAttribute("userID", uta.getID(0));
session.setAttribute("role", uta.getRole(0));
response.sendRedirect("Main.jsp");
}
else
{
request.setAttribute("wrongDetails", new Boolean(true));
response.sendRedirect("Login.jsp");
}
}
else
response.getWriter().print(pageName);
}
}
sorry if my english is bad, or if details are missing
Your driver is not in the server classpath, build path has nothing to do with that.
You didn't write which application server are you using. You also should use DataSource in servlets, rather than DriverManager. Here is sample configuration for Tomcat.
UPDATE
For Tomcat 7 you need to do the following:
Put mysql jar in the $CATALINA_HOME/lib
Configure Datasource in context
<Resource name="jdbc/TestDB" auth="Container" type="javax.sql.DataSource"
maxActive="100" maxIdle="30" maxWait="10000"
username="user" password="pass"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/databaseName"/>
Use Datasource in servlet (pseudo code)
#WebServlet("/LoginHandle")
public class LoginHandle extends HttpServlet {
private static final long serialVersionUID = 1L;
#Resource(lookup="jdbc/testDB")
private DataSource ds;
...
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Connection c = ds.getConnection();
...
the data is not getting updated in the database .
im developing a login functionality where im also registering the user. After the registration, i want to display the details that was used during registration.
im posting my code for the servlet that im using :
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class UserController extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final int Id = 0;
private static final String Password = null;
private static final String Username = null;
private static final int Userid = 0;
private static String INSERT_OR_EDIT = "/user.jsp";
private static String LIST_USER = "/listUser.jsp";
public static String PARAM_USERNAME = "uname";
public static String PARAM_PASSWORD = "pass";
private UserDao dao;
private Connection connection;
public UserController() {
super();
dao = new UserDao();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
String forward="";
String act = request.getParameter("act");
if (act != null && !act.equalsIgnoreCase("null") && act.equalsIgnoreCase("login")) {
forward= "/Login.jsp";
}
else if (act != null && !act.equalsIgnoreCase("null") && act.equalsIgnoreCase("delete"))
{
int userId = Integer.parseInt(request.getParameter("userId"));
dao.deleteUser(userId);
forward = LIST_USER;
request.setAttribute("users", dao.getAllUsers());
} else if (act!=null && !act.equalsIgnoreCase("null") && act.equalsIgnoreCase("edit")){
forward = INSERT_OR_EDIT;
int userId = Integer.parseInt(request.getParameter("userId"));
User user1 = dao.getUserById(userId);
request.setAttribute("user", user1);
} else if (act!=null && !act.equalsIgnoreCase("null") && act.equalsIgnoreCase("listUser")){
forward = LIST_USER;
request.setAttribute("users", dao.getAllUsers());
} else if (act!=null && !act.equalsIgnoreCase("null") && act.equalsIgnoreCase("register")){
forward = "/reg.jsp";
// request.setAttribute("users", dao.getAllUsers());
} else
forward = "/Login.jsp";
RequestDispatcher view = request.getRequestDispatcher(forward);
view.forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out=response.getWriter();
String act = request.getParameter("act");
if (act != null && !act.equalsIgnoreCase("null") && act.equalsIgnoreCase("login")) {
String str=request.getParameter("username");
String str1=request.getParameter("password");
if(str.equalsIgnoreCase("shreya")&&str1.equalsIgnoreCase("singh"))
{
System.out.println("Login!");
request.setAttribute("users",dao.getAllUsers());
request.getRequestDispatcher("/listUser.jsp").forward(request, response);
}else
{
System.out.println("Login failed!");
}
}
else
{
}
User user = new User();
Details details = new Details();
user.setFirstName(request.getParameter("firstName"));
user.setLastName(request.getParameter("lastName"));
details.setUsername(request.getParameter("uname"));
details.setPassword(request.getParameter("pass"));
if (act != null && !act.equalsIgnoreCase("null") && act.equalsIgnoreCase("register"))
{
String userid=request.getParameter("userid");
String username=request.getParameter("username");
String password=request.getParameter("password");
String id=request.getParameter("id");
if(userid.equals("") || username.equals("") || password.equals("") || id.equals(""))
{
out.println("Please insert valid data");
}
RequestDispatcher rd = request.getRequestDispatcher("/listUser.jsp");
rd.include(request, response);
}
else
{
RequestDispatcher rd = request.getRequestDispatcher("/listUser.jsp");
rd.include(request, response);
try {
PreparedStatement preparedStatement = connection.
prepareStatement("select * from details where id=?");
preparedStatement.setInt(1, Id);
ResultSet rs = preparedStatement.executeQuery();
if (rs.next()) {
details.setUserid(rs.getInt("userid"));
details.setUsername(rs.getString("username"));
details.setPassword(rs.getString("password"));
details.setId(rs.getInt("id"));
}
PreparedStatement preparedStatement1 = connection.
prepareStatement( "insert into details values(?,?,?,?)");
preparedStatement1.setInt(1, Userid);
preparedStatement1.setString(2, Username);
preparedStatement1.setString(3, Password);
preparedStatement1.setInt(4, Id);
int i=preparedStatement1.executeUpdate();
if(i>0)
{
System.out.println("Data update sucessfully");
System.out.print("Student record successfully inserted");
RequestDispatcher rd1 = request.getRequestDispatcher("/registration.jsp");
rd1.include(request, response);
}
}
catch (Exception e)
{
System.out.println(e);
}
}
}
}
ive been stuck on this since i dont remember when . help would be appreciated.
I have develop servlet for generate Captcha code & add session name code
Generate Capta-code
import javax.servlet.*;
import java.io.*;
import java.awt.*;
import java.util.Random;
import java.awt.image.*;
import javax.imageio.*;
import javax.servlet.http.*;
public class capta extends HttpServlet
{
final int LEN=10;
BufferedImage image;
Random rnd;
public void doGet(HttpServletRequest req,HttpServletResponse rep)
{
try
{
image = new BufferedImage(200, 80, BufferedImage.TYPE_INT_RGB);
rnd=new Random();
rep.setContentType("image/jpeg");
String random_String=getRandomNumbers();
HttpSession ses=req.getSession();
ses.setAttribute("code",random_String);
Graphics g = image.getGraphics();
g.setFont(new Font("Maiandra GD",1,30));
g.setColor(Color.blue);
g.drawString(random_String,3,50);
g.dispose();
/// it was here
ImageIO.write(image, "jpg", rep.getOutputStream());
}
catch(Exception e)
{
}
}
private String getRandomNumbers()
{
StringBuffer str=new StringBuffer();
for(int i=1;i<=9;i++)
{
str.append(new Integer(rnd.nextInt(9)).toString());
}
return str.toString();
}
public void doPost(HttpServletRequest req,HttpServletResponse rep)throws ServletException , IOException
{
doGet(req,rep);
}
}
Use Generate capta-image in other servlet
import javax.servlet.*;
import java.io.*;
import javax.servlet.http.*;
public class capta_test extends HttpServlet
{
public void doGet(HttpServletRequest req,HttpServletResponse rep)
{
PrintWriter out=null;
try
{
String input=req.getParameter("txt_capta");
out=rep.getWriter();
rep.setContentType("text/html");
out.println("<html><head><title>Capta Test</title></head>");
out.println("<body>");
out.println("<h1> Capta is Generated </h1>");
out.println("<img src=\"http://localhost:8080/mahesh/capta\" />");
HttpSession ses=req.getSession();
String original=(String)ses.getAttribute("code");
if(original!=null)
{
out.println("<h1>Original Value "+original+"</h1>");
}
ses.invalidate();
out.println("</body>");
out.println("</html>");
}
catch(Exception e)
{
}
}
public void doPost(HttpServletRequest req,HttpServletResponse rep)throws ServletException , IOException
{
doGet(req,rep);
}
}
Both servlet work fine but I am not getting the session value which is generate in Capta-code servelt(added in servlet)
I am getting session value which is generate in previous capta-image.
See output :
Output - 1
Output - 2
Output - 3
Thank you ..
Put the random number generation logic in capta_test servlet and put that number in session. Because you are rendering HTML, the capta servlet will be called after the page load like this and do not invalidate the session.
Random number generator
import javax.servlet.*;
import java.io.*;
import javax.servlet.http.*;
public class capta_test extends HttpServlet
{
public void doGet(HttpServletRequest req,HttpServletResponse rep)
{
PrintWriter out=null;
try
{
String original=getRandomNumbers();
HttpSession ses=req.getSession(false);
ses.setAttribute("code",random_String);
String input=req.getParameter("txt_capta");
out=rep.getWriter();
rep.setContentType("text/html");
out.println("<html><head><title>Capta Test</title></head>");
out.println("<body>");
out.println("<h1> Capta is Generated </h1>");
out.println("<img src=\"http://localhost:8080/mahesh/capta\" />");
out.println("<h1>Original Value "+original+"</h1>");
out.println("</body>");
out.println("</html>");
}
catch(Exception e)
{
}
}
public void doPost(HttpServletRequest req,HttpServletResponse rep)throws ServletException , IOException
{
doGet(req,rep);
}
private String getRandomNumbers()
{
Random rnd=new Random();
StringBuffer str=new StringBuffer();
for(int i=1;i<=9;i++)
{
str.append(new Integer(rnd.nextInt(9)).toString());
}
return str.toString();
}
}
Image generator servlet
import javax.servlet.*;
import java.io.*;
import java.awt.*;
import java.util.Random;
import java.awt.image.*;
import javax.imageio.*;
import javax.servlet.http.*;
public class capta extends HttpServlet
{
final int LEN=10;
BufferedImage image;
public void doGet(HttpServletRequest req,HttpServletResponse rep)
{
try
{
HttpSession ses=req.getSession(false);
String random_String=(String)ses.getAttribute("code");
image = new BufferedImage(200, 80, BufferedImage.TYPE_INT_RGB);
rep.setContentType("image/jpeg");
Graphics g = image.getGraphics();
g.setFont(new Font("Maiandra GD",1,30));
g.setColor(Color.blue);
g.drawString(random_String,3,50);
g.dispose();
/// it was here
ImageIO.write(image, "jpg", rep.getOutputStream());
}
catch(Exception e)
{
}
}
public void doPost(HttpServletRequest req,HttpServletResponse rep)throws ServletException , IOException
{
doGet(req,rep);
}
}
Your program flow is wrong , the session value is null because the capta_test servlet is called even before the capta servlet.
Have a look at this simple tutorial. Hope this helps you move in the right path
Captcha in JSP and Servlet